Repository navigation
Fit main windows after display topology changes #7308
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 10 commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
832f437
Add regression test for cut-off main window restore
austinywang 7853062
Fit main windows after display topology changes
austinywang 936d0e6
Trim WorkspaceDetailView to satisfy file budget
austinywang fc36250
Use cancellable task for window fit coalescing
austinywang cb16203
Use visible-frame edge distance for window fit fallback
austinywang 4d0ce24
Use instance helpers in window fit core
austinywang d7b0dcd
Preserve visible windows spanning displays
austinywang 4cde410
Preserve spanning restored windows
austinywang a4ac6dc
Add mobile terminal theme support
austinywang ac9e58d
Merge remote-tracking branch 'origin/main' into issue-7306-multi-moni…
austinywang fc695b2
Stabilize visible-frame rescue topology gate
austinywang 300e45a
Run visible-frame rescue from guarded reconcile path
austinywang acff65c
Route window fit through guarded display reconcile
austinywang d48d684
Merge remote-tracking branch 'origin/main' into issue-7306-multi-moni…
austinywang d71aa53
Gate visible-frame rescue on visible topology
austinywang a932869
Fix macOS CI preflight routing
austinywang 0539fe8
Handle untrusted visible topology transitions
austinywang c3e6690
Merge remote-tracking branch 'origin/main' into issue-7306-multi-moni…
austinywang abc619f
Decouple visible topology retry from capture firewall
austinywang 23cd0ca
Merge remote-tracking branch 'origin/main' into issue-7306-multi-moni…
austinywang c2ce925
Fit restored windows using all current displays
austinywang File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
230 changes: 230 additions & 0 deletions
230
...es/macOS/CmuxWindowing/Sources/CmuxWindowing/Geometry/MainWindowVisibleFrameFitCore.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,230 @@ | ||
| public import CoreGraphics | ||
|
|
||
| /// Pure decision core for fitting main-window frames into current visible displays. | ||
| /// | ||
| /// Callers use this after a real display-topology change, or while restoring | ||
| /// stale persisted geometry onto a different display arrangement. A frame that | ||
| /// already fits fully inside any current visible display is always a no-op. | ||
| public struct MainWindowVisibleFrameFitCore: Sendable { | ||
| /// Creates a visible-frame fit core. | ||
| public init() {} | ||
|
|
||
| /// Returns an order-independent signature for display-topology changes. | ||
| /// | ||
| /// - Parameter displays: Display geometry snapshots in any order. | ||
| /// - Returns: A sorted signature that excludes side and bottom Dock insets. | ||
| public func topologySignature( | ||
| of displays: [SessionDisplayGeometry] | ||
| ) -> [MainWindowVisibleFrameTopologySignatureEntry] { | ||
| displays | ||
| .map { display in | ||
| MainWindowVisibleFrameTopologySignatureEntry( | ||
| displayID: display.displayID, | ||
| frame: display.frame, | ||
| visibleFrame: display.visibleFrame | ||
| ) | ||
| } | ||
| .sorted { lhs, rhs in | ||
| let lhsID = displayIDSortValue(lhs.displayID) | ||
| let rhsID = displayIDSortValue(rhs.displayID) | ||
| if lhsID != rhsID { return lhsID < rhsID } | ||
| if lhs.frame.minX != rhs.frame.minX { return lhs.frame.minX < rhs.frame.minX } | ||
| if lhs.frame.minY != rhs.frame.minY { return lhs.frame.minY < rhs.frame.minY } | ||
| if lhs.frame.width != rhs.frame.width { return lhs.frame.width < rhs.frame.width } | ||
| if lhs.frame.height != rhs.frame.height { return lhs.frame.height < rhs.frame.height } | ||
| return lhs.topInset < rhs.topInset | ||
| } | ||
| } | ||
|
|
||
| /// Returns fit decisions for `frames`, preserving input order. | ||
| /// | ||
| /// - Parameters: | ||
| /// - frames: Window frames in global screen coordinates. | ||
| /// - displays: Current display geometry snapshots. | ||
| /// - minimumWidth: Minimum width to enforce when an offscreen frame must be clamped. | ||
| /// - minimumHeight: Minimum height to enforce when an offscreen frame must be clamped. | ||
| /// - Returns: A fitted frame for each input, or `nil` when that frame must not move. | ||
| public func fittedFrames( | ||
| for frames: [CGRect], | ||
| displays: [SessionDisplayGeometry], | ||
| minimumWidth: CGFloat, | ||
| minimumHeight: CGFloat | ||
| ) -> [CGRect?] { | ||
| frames.map { frame in | ||
| fittedFrame( | ||
| for: frame, | ||
| displays: displays, | ||
| minimumWidth: minimumWidth, | ||
| minimumHeight: minimumHeight | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| /// Returns a fitted frame, or `nil` when `frame` already fits a visible display. | ||
| /// | ||
| /// - Parameters: | ||
| /// - frame: Window frame in global screen coordinates. | ||
| /// - displays: Current display geometry snapshots. | ||
| /// - minimumWidth: Minimum width to enforce when clamping. | ||
| /// - minimumHeight: Minimum height to enforce when clamping. | ||
| /// - Returns: The clamped/shrunk frame, or `nil` for a strict no-op. | ||
| public func fittedFrame( | ||
| for frame: CGRect, | ||
| displays: [SessionDisplayGeometry], | ||
| minimumWidth: CGFloat, | ||
| minimumHeight: CGFloat | ||
| ) -> CGRect? { | ||
| let standardizedFrame = frame.standardized | ||
| guard isUsableRect(standardizedFrame) else { return nil } | ||
|
|
||
| let usableDisplays = displays.filter { isUsableRect($0.visibleFrame) } | ||
| guard !usableDisplays.isEmpty else { return nil } | ||
| if isFullyCovered(standardizedFrame, by: usableDisplays.map(\.visibleFrame)) { | ||
| return nil | ||
| } | ||
|
|
||
| let targetDisplay = targetDisplay(for: standardizedFrame, in: usableDisplays) | ||
| ?? usableDisplays[0] | ||
| let fitted = clampFrame( | ||
| standardizedFrame, | ||
| within: targetDisplay.visibleFrame, | ||
| minimumWidth: minimumWidth, | ||
| minimumHeight: minimumHeight | ||
| ) | ||
| return rectApproximatelyEqual(fitted, standardizedFrame) ? nil : fitted | ||
| } | ||
|
|
||
| private func targetDisplay( | ||
| for frame: CGRect, | ||
| in displays: [SessionDisplayGeometry] | ||
| ) -> SessionDisplayGeometry? { | ||
| let overlaps = displays.map { display in | ||
| (display: display, area: intersectionArea(frame, display.visibleFrame)) | ||
| } | ||
| if let best = overlaps.max(by: { $0.area < $1.area }), best.area > 0 { | ||
| return best.display | ||
| } | ||
|
|
||
| let center = CGPoint(x: frame.midX, y: frame.midY) | ||
| return displays.min { lhs, rhs in | ||
| distanceSquared(from: center, to: lhs.visibleFrame) | ||
| < distanceSquared(from: center, to: rhs.visibleFrame) | ||
| } | ||
| } | ||
|
|
||
| private func clampFrame( | ||
| _ frame: CGRect, | ||
| within visibleFrame: CGRect, | ||
| minimumWidth: CGFloat, | ||
| minimumHeight: CGFloat | ||
| ) -> CGRect { | ||
| let maxWidth = max(visibleFrame.width, 1) | ||
| let maxHeight = max(visibleFrame.height, 1) | ||
| let widthFloor = min(minimumWidth, maxWidth) | ||
| let heightFloor = min(minimumHeight, maxHeight) | ||
|
|
||
| let width = min(max(frame.width, widthFloor), maxWidth) | ||
| let height = min(max(frame.height, heightFloor), maxHeight) | ||
| let maxX = visibleFrame.maxX - width | ||
| let maxY = visibleFrame.maxY - height | ||
| let x = min(max(frame.minX, visibleFrame.minX), maxX) | ||
| let y = min(max(frame.minY, visibleFrame.minY), maxY) | ||
|
|
||
| return CGRect(x: x, y: y, width: width, height: height) | ||
| } | ||
|
|
||
| private func intersectionArea(_ lhs: CGRect, _ rhs: CGRect) -> CGFloat { | ||
| let intersection = lhs.intersection(rhs) | ||
| guard !intersection.isNull else { return 0 } | ||
| return max(0, intersection.width) * max(0, intersection.height) | ||
| } | ||
|
|
||
| private func distanceSquared(from point: CGPoint, to rect: CGRect) -> CGFloat { | ||
| let nearestX = min(max(point.x, rect.minX), rect.maxX) | ||
| let nearestY = min(max(point.y, rect.minY), rect.maxY) | ||
| let dx = nearestX - point.x | ||
| let dy = nearestY - point.y | ||
| return (dx * dx) + (dy * dy) | ||
| } | ||
|
|
||
| private func isFullyCovered(_ frame: CGRect, by visibleFrames: [CGRect]) -> Bool { | ||
| var uncovered = [frame] | ||
| for visibleFrame in visibleFrames { | ||
| uncovered = uncovered.flatMap { rect in | ||
| uncoveredPieces(of: rect, afterCoveringWith: visibleFrame) | ||
| } | ||
| if uncovered.isEmpty { return true } | ||
| } | ||
| return false | ||
| } | ||
|
|
||
| private func uncoveredPieces(of rect: CGRect, afterCoveringWith cover: CGRect) -> [CGRect] { | ||
| let intersection = rect.intersection(cover) | ||
| guard isUsableRect(intersection) else { return [rect] } | ||
|
|
||
| var pieces: [CGRect] = [] | ||
| if intersection.minY > rect.minY { | ||
| pieces.append(CGRect( | ||
| x: rect.minX, | ||
| y: rect.minY, | ||
| width: rect.width, | ||
| height: intersection.minY - rect.minY | ||
| )) | ||
| } | ||
| if intersection.maxY < rect.maxY { | ||
| pieces.append(CGRect( | ||
| x: rect.minX, | ||
| y: intersection.maxY, | ||
| width: rect.width, | ||
| height: rect.maxY - intersection.maxY | ||
| )) | ||
| } | ||
|
|
||
| let middleMinY = max(rect.minY, intersection.minY) | ||
| let middleMaxY = min(rect.maxY, intersection.maxY) | ||
| if middleMaxY > middleMinY { | ||
| if intersection.minX > rect.minX { | ||
| pieces.append(CGRect( | ||
| x: rect.minX, | ||
| y: middleMinY, | ||
| width: intersection.minX - rect.minX, | ||
| height: middleMaxY - middleMinY | ||
| )) | ||
| } | ||
| if intersection.maxX < rect.maxX { | ||
| pieces.append(CGRect( | ||
| x: intersection.maxX, | ||
| y: middleMinY, | ||
| width: rect.maxX - intersection.maxX, | ||
| height: middleMaxY - middleMinY | ||
| )) | ||
| } | ||
| } | ||
|
|
||
| return pieces.filter { isUsableRect($0) } | ||
| } | ||
|
|
||
| private func isUsableRect(_ rect: CGRect) -> Bool { | ||
| rect.origin.x.isFinite | ||
| && rect.origin.y.isFinite | ||
| && rect.width.isFinite | ||
| && rect.height.isFinite | ||
| && rect.width > 0 | ||
| && rect.height > 0 | ||
| } | ||
|
|
||
| private func rectApproximatelyEqual( | ||
| _ lhs: CGRect, | ||
| _ rhs: CGRect, | ||
| tolerance: CGFloat = 0.5 | ||
| ) -> Bool { | ||
| abs(lhs.minX - rhs.minX) <= tolerance | ||
| && abs(lhs.minY - rhs.minY) <= tolerance | ||
| && abs(lhs.width - rhs.width) <= tolerance | ||
| && abs(lhs.height - rhs.height) <= tolerance | ||
| } | ||
|
|
||
| private func displayIDSortValue(_ displayID: UInt32?) -> UInt64 { | ||
| displayID.map(UInt64.init) ?? UInt64.max | ||
| } | ||
| } |
31 changes: 31 additions & 0 deletions
31
...ndowing/Sources/CmuxWindowing/Geometry/MainWindowVisibleFrameTopologySignatureEntry.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| public import CoreGraphics | ||
|
|
||
| /// One display's stable contribution to the main-window visible-frame fit gate. | ||
| /// | ||
| /// Side and bottom `visibleFrame` insets are deliberately omitted so Dock | ||
| /// resizes do not look like display-topology changes. Full display frames, | ||
| /// display IDs, and top insets catch monitor arrangement and menu-bar changes. | ||
| public struct MainWindowVisibleFrameTopologySignatureEntry: Equatable, Sendable { | ||
| /// CoreGraphics display id, when available. | ||
| public let displayID: UInt32? | ||
| /// The display's full frame in global screen coordinates. | ||
| public let frame: CGRect | ||
| /// Height excluded from the display's top edge. | ||
| public let topInset: CGFloat | ||
|
|
||
| /// Creates a topology-signature entry for one display. | ||
| /// | ||
| /// - Parameters: | ||
| /// - displayID: CoreGraphics display id, when available. | ||
| /// - frame: The display's full frame. | ||
| /// - visibleFrame: The display's visible frame after system insets. | ||
| public init( | ||
| displayID: UInt32?, | ||
| frame: CGRect, | ||
| visibleFrame: CGRect | ||
| ) { | ||
| self.displayID = displayID | ||
| self.frame = frame | ||
| self.topInset = frame.maxY - visibleFrame.maxY | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| import AppKit | ||
| import CmuxWindowing | ||
|
|
||
| /// Watches real display-topology changes and fits cut-off main windows back | ||
| /// into a current visible frame. This complements the titlebar-stranding rescue | ||
| /// in PR #7265: that pass handles unreachable drag handles; this pass handles | ||
| /// reachable windows whose body is still clipped or oversized. | ||
| @MainActor | ||
| final class MainWindowVisibleFrameFitRescue: NSObject { | ||
| private let fitCore: MainWindowVisibleFrameFitCore | ||
| private var cachedSignature: [MainWindowVisibleFrameTopologySignatureEntry] = [] | ||
| private var pendingFitTask: Task<Void, Never>? | ||
| private var isInstalled = false | ||
|
|
||
| /// Owned and installed by `AppDelegate`. | ||
| init(fitCore: MainWindowVisibleFrameFitCore = MainWindowVisibleFrameFitCore()) { | ||
| self.fitCore = fitCore | ||
| super.init() | ||
| } | ||
|
|
||
| func install() { | ||
| guard !isInstalled else { return } | ||
| cachedSignature = currentTopologySignature() | ||
| NotificationCenter.default.addObserver( | ||
| self, | ||
| selector: #selector(screenParametersDidChange(_:)), | ||
| name: NSApplication.didChangeScreenParametersNotification, | ||
| object: nil | ||
| ) | ||
| isInstalled = true | ||
| } | ||
|
|
||
| deinit { | ||
| pendingFitTask?.cancel() | ||
| NotificationCenter.default.removeObserver(self) | ||
| } | ||
|
|
||
| @objc private func screenParametersDidChange(_: Notification) { | ||
| pendingFitTask?.cancel() | ||
| pendingFitTask = Task { @MainActor [weak self] in | ||
| await Task.yield() | ||
| guard !Task.isCancelled else { return } | ||
| self?.performFitIfNeeded() | ||
| } | ||
| } | ||
|
|
||
| private func performFitIfNeeded() { | ||
| let displays = Self.currentDisplays() | ||
| guard !displays.isEmpty else { return } | ||
|
|
||
| let signature = fitCore.topologySignature(of: displays) | ||
| let topologyChanged = signature != cachedSignature | ||
| cachedSignature = signature | ||
| guard topologyChanged else { return } | ||
|
|
||
| let windows = NSApp.windows | ||
| .compactMap { $0 as? CmuxMainWindow } | ||
| .filter { window in | ||
| !window.styleMask.contains(.fullScreen) | ||
| } | ||
| guard !windows.isEmpty else { return } | ||
|
|
||
| let fittedFrames = fitCore.fittedFrames( | ||
| for: windows.map(\.frame), | ||
| displays: displays, | ||
| minimumWidth: CGFloat(SessionPersistencePolicy.minimumWindowWidth), | ||
| minimumHeight: CGFloat(SessionPersistencePolicy.minimumWindowHeight) | ||
| ) | ||
| for (window, targetFrame) in zip(windows, fittedFrames) { | ||
| guard let targetFrame, targetFrame != window.frame else { continue } | ||
| let originalFrame = window.frame | ||
| #if DEBUG | ||
| cmuxDebugLog( | ||
| "mainWindow.visibleFrameFit.clamp win=\(window.windowNumber) " + | ||
| "from={\(Self.rectDescription(originalFrame))} to={\(Self.rectDescription(targetFrame))}" | ||
| ) | ||
| #endif | ||
| sentryBreadcrumb( | ||
| "mainWindow.visibleFrameFit.clamp", | ||
| category: "window", | ||
| data: [ | ||
| "from": Self.rectDescription(originalFrame), | ||
| "to": Self.rectDescription(targetFrame), | ||
| ] | ||
| ) | ||
| window.setFrame(targetFrame, display: true) | ||
| } | ||
| } | ||
|
|
||
| private static func currentDisplays() -> [SessionDisplayGeometry] { | ||
| NSScreen.screens.map { screen in | ||
| SessionDisplayGeometry( | ||
| displayID: screen.cmuxDisplayID, | ||
| frame: screen.frame, | ||
| visibleFrame: screen.visibleFrame | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| private func currentTopologySignature() -> [MainWindowVisibleFrameTopologySignatureEntry] { | ||
| fitCore.topologySignature(of: Self.currentDisplays()) | ||
| } | ||
|
|
||
| private static func rectDescription(_ rect: CGRect) -> String { | ||
| "\(Int(rect.minX.rounded())),\(Int(rect.minY.rounded())) " + | ||
| "\(Int(rect.width.rounded()))x\(Int(rect.height.rounded()))" | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.