Repository navigation
Restore window positions when external displays reconnect #2491
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
Changes from 7 commits
6d185f0
bca310c
8e3535e
05d1aec
d96cf7d
4c585e4
a8bea41
4c83c9f
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2302,6 +2302,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent | |
| private var mainWindowContexts: [ObjectIdentifier: MainWindowContext] = [:] | ||
| private var mainWindowControllers: [MainWindowController] = [] | ||
|
|
||
| /// Per-display window frame cache for restoring positions when external displays reconnect. | ||
| /// Keyed by CGDirectDisplayID, values map stable window UUID to the last known frame on that display. | ||
| private var displayWindowFrameCache: [UInt32: [UUID: CGRect]] = [:] | ||
| /// Set of display IDs that were connected at last check, used to detect reconnections. | ||
| private var knownConnectedDisplayIDs: Set<UInt32> = [] | ||
|
|
||
| /// Tracks the cascade point for new windows, matching Ghostty's upstream algorithm. | ||
| /// Reset to `.zero` so the first window seeds the point from its own position. | ||
| private var lastCascadePoint = NSPoint.zero | ||
|
|
@@ -2426,6 +2432,33 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent | |
| suspensionBehavior: .deliverImmediately | ||
| ) | ||
|
|
||
| // Track external display connect/disconnect for window position restoration. | ||
| knownConnectedDisplayIDs = Set(NSScreen.screens.compactMap { $0.cmuxDisplayID }) | ||
| NotificationCenter.default.addObserver( | ||
| self, | ||
| selector: #selector(handleScreenParametersDidChange(_:)), | ||
| name: NSApplication.didChangeScreenParametersNotification, | ||
| object: nil | ||
| ) | ||
| NotificationCenter.default.addObserver( | ||
| self, | ||
| selector: #selector(handleWindowDidChangeScreen(_:)), | ||
| name: NSWindow.didChangeScreenNotification, | ||
| object: nil | ||
| ) | ||
| NotificationCenter.default.addObserver( | ||
| self, | ||
| selector: #selector(handleWindowDidMove(_:)), | ||
| name: NSWindow.didMoveNotification, | ||
| object: nil | ||
| ) | ||
| NotificationCenter.default.addObserver( | ||
| self, | ||
| selector: #selector(handleWindowDidResize(_:)), | ||
| name: NSWindow.didResizeNotification, | ||
| object: nil | ||
| ) | ||
|
Comment on lines
+2438
to
+2463
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Seed the display cache when a main window becomes managed. Right now the cache is only populated by future move/resize/screen-change notifications. A window that's already sitting on an external display when it registers can unplug before any of those fire, leaving Also applies to: 3577-3590 🤖 Prompt for AI Agents |
||
|
|
||
| #if DEBUG | ||
| // UI tests run on a shared VM user profile, so persisted shortcuts can drift and make | ||
| // key-equivalent routing flaky. Force defaults for deterministic tests. | ||
|
|
@@ -3525,6 +3558,69 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent | |
| ) | ||
| } | ||
|
|
||
| // MARK: - Display reconnection window restoration | ||
|
|
||
| /// Cache the current frame of a managed window, keyed by its current display. | ||
| /// Only clears entries on other *currently connected* displays so that a | ||
| /// disconnect-driven relocation to the primary display doesn't erase the | ||
| /// frame we need for restoration. | ||
| private func cacheWindowFrameForDisplay(_ window: NSWindow) { | ||
| guard let ctx = mainWindowContexts[ObjectIdentifier(window)] else { return } | ||
| guard let displayID = window.screen?.cmuxDisplayID else { return } | ||
| let windowID = ctx.windowId | ||
| for otherDisplayID in displayWindowFrameCache.keys where otherDisplayID != displayID { | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
|
||
| // Only prune entries for displays that are still connected. | ||
| // Disconnected display entries are preserved for restoration. | ||
| if knownConnectedDisplayIDs.contains(otherDisplayID) { | ||
| displayWindowFrameCache[otherDisplayID]?.removeValue(forKey: windowID) | ||
| } | ||
| } | ||
| displayWindowFrameCache[displayID, default: [:]][windowID] = window.frame | ||
|
Comment on lines
+3570
to
+3581
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Don't restore windows that were intentionally rehomed while a display was away. The disconnected-display entry survives later moves/resizes on a connected display, and the reconnect path restores every window still cached under that old display. If a user unplugs display A, keeps working on display B, and manually repositions the window on B, reconnecting A will still snap it back to A. This needs a per-window recency / pending-restore check so post-disconnect user moves clear the stale entry. Also applies to: 3603-3620 🤖 Prompt for AI Agents |
||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
|
|
||
| @objc private func handleWindowDidMove(_ notification: Notification) { | ||
| guard let window = notification.object as? NSWindow else { return } | ||
| cacheWindowFrameForDisplay(window) | ||
| } | ||
|
|
||
| @objc private func handleWindowDidResize(_ notification: Notification) { | ||
| guard let window = notification.object as? NSWindow else { return } | ||
| cacheWindowFrameForDisplay(window) | ||
| } | ||
|
|
||
| @objc private func handleWindowDidChangeScreen(_ notification: Notification) { | ||
| guard let window = notification.object as? NSWindow else { return } | ||
| cacheWindowFrameForDisplay(window) | ||
| } | ||
|
Comment on lines
+3570
to
+3597
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Only prune other display entries on confirmed user moves/resizes.
🤖 Prompt for AI Agents |
||
|
|
||
| @objc private func handleScreenParametersDidChange(_ notification: Notification) { | ||
| let currentDisplayIDs = Set(NSScreen.screens.compactMap { $0.cmuxDisplayID }) | ||
| let reconnected = currentDisplayIDs.subtracting(knownConnectedDisplayIDs) | ||
| knownConnectedDisplayIDs = currentDisplayIDs | ||
|
|
||
| guard !reconnected.isEmpty else { return } | ||
|
|
||
| for displayID in reconnected { | ||
| guard let cachedFrames = displayWindowFrameCache[displayID], | ||
| let screen = NSScreen.screens.first(where: { $0.cmuxDisplayID == displayID }) else { | ||
| continue | ||
| } | ||
| for (windowUUID, frame) in cachedFrames { | ||
| guard let ctx = mainWindowContexts.values.first(where: { $0.windowId == windowUUID }), | ||
| let window = ctx.window else { | ||
| continue | ||
| } | ||
| let clamped = Self.clampFrame( | ||
| frame, | ||
| within: screen.visibleFrame, | ||
| minWidth: CGFloat(SessionPersistencePolicy.minimumWindowWidth), | ||
| minHeight: CGFloat(SessionPersistencePolicy.minimumWindowHeight) | ||
| ) | ||
| window.setFrame(clamped, display: true, animate: true) | ||
| } | ||
| } | ||
| } | ||
|
Comment on lines
+3599
to
+3635
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Comment on lines
+3599
to
+3635
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Wire the disconnected-display cache into session persistence too. This reconnect handler restores the live window, but 🤖 Prompt for AI Agents |
||
|
|
||
| private func startSessionAutosaveTimerIfNeeded() { | ||
| guard sessionAutosaveTimer == nil else { return } | ||
| let env = ProcessInfo.processInfo.environment | ||
|
|
@@ -4064,6 +4160,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent | |
| ) | ||
| #endif | ||
| notifyMainWindowContextsDidChange() | ||
| cacheWindowFrameForDisplay(window) | ||
| if window.isKeyWindow { | ||
| setActiveMainWindow(window) | ||
| } | ||
|
|
@@ -8052,9 +8149,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent | |
| })(); | ||
| """ | ||
|
|
||
| panel.webView.evaluateJavaScript(script) { [weak self] result, _ in | ||
| panel.webView.evaluateJavaScript(script, in: nil, in: .defaultClient) { [weak self] callResult in | ||
| guard let self else { return } | ||
| let payload = result as? [String: Any] | ||
| let payload = (try? callResult.get()) as? [String: Any] | ||
| let focused = (payload?["focused"] as? Bool) ?? false | ||
| let inputId = (payload?["id"] as? String) ?? "" | ||
| let secondaryInputId = (payload?["secondaryId"] as? String) ?? "" | ||
|
|
@@ -8260,8 +8357,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent | |
| })(); | ||
| """ | ||
|
|
||
| panel.webView.evaluateJavaScript(script) { result, _ in | ||
| let payload = result as? [String: Any] | ||
| panel.webView.evaluateJavaScript(script, in: nil, in: .defaultClient) { callResult in | ||
| let payload = (try? callResult.get()) as? [String: Any] | ||
| completion([ | ||
| "id": (payload?["id"] as? String) ?? "", | ||
| "tag": (payload?["tag"] as? String) ?? "", | ||
|
|
@@ -11475,6 +11572,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent | |
| commandPaletteSelectionByWindowId.removeValue(forKey: removed.windowId) | ||
| commandPaletteSnapshotByWindowId.removeValue(forKey: removed.windowId) | ||
|
|
||
| // Purge per-display frame cache for the closing window. | ||
| for displayID in displayWindowFrameCache.keys { | ||
| displayWindowFrameCache[displayID]?.removeValue(forKey: removed.windowId) | ||
| } | ||
|
|
||
| // Avoid stale notifications that can no longer be opened once the owning window is gone. | ||
| if let store = notificationStore { | ||
| for tab in removed.tabManager.tabs { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2517,7 +2517,8 @@ final class BrowserPanel: Panel, ObservableObject { | |
| WKUserScript( | ||
| source: Self.telemetryHookBootstrapScriptSource, | ||
| injectionTime: .atDocumentStart, | ||
| forMainFrameOnly: true | ||
| forMainFrameOnly: true, | ||
| in: .defaultClient | ||
| ) | ||
| ) | ||
| // Track the last editable focused element continuously so omnibar exit can | ||
|
|
@@ -2527,7 +2528,8 @@ final class BrowserPanel: Panel, ObservableObject { | |
| WKUserScript( | ||
| source: Self.addressBarFocusTrackingBootstrapScript, | ||
| injectionTime: .atDocumentStart, | ||
| forMainFrameOnly: true | ||
| forMainFrameOnly: true, | ||
| in: .defaultClient | ||
| ) | ||
| ) | ||
| } | ||
|
|
@@ -3540,8 +3542,8 @@ final class BrowserPanel: Panel, ObservableObject { | |
| continuation.resume(returning: value) | ||
| } | ||
|
|
||
| webView.evaluateJavaScript(script) { result, _ in | ||
| let value = result as? String | ||
| webView.evaluateJavaScript(script, in: nil, in: .defaultClient) { result in | ||
| let value = (try? result.get()) as? String | ||
| Task { @MainActor in | ||
| resume(value) | ||
| } | ||
|
|
@@ -4806,8 +4808,8 @@ extension BrowserPanel { | |
| } | ||
|
|
||
| /// Execute JavaScript | ||
| func evaluateJavaScript(_ script: String) async throws -> Any? { | ||
| try await webView.evaluateJavaScript(script) | ||
| func evaluateJavaScript(_ script: String, contentWorld: WKContentWorld = .defaultClient) async throws -> Any? { | ||
| try await webView.evaluateJavaScript(script, in: nil, in: contentWorld) | ||
| } | ||
|
|
||
| // MARK: - Find in Page | ||
|
|
@@ -4867,15 +4869,15 @@ extension BrowserPanel { | |
| func findNext() { | ||
| Task { @MainActor [weak self] in | ||
| guard let self else { return } | ||
| let result = try? await self.webView.evaluateJavaScript(BrowserFindJavaScript.nextScript()) | ||
| let result = try? await self.webView.evaluateJavaScript(BrowserFindJavaScript.nextScript(), in: nil, in: .defaultClient) | ||
| self.parseFindResult(result) | ||
| } | ||
| } | ||
|
|
||
| func findPrevious() { | ||
| Task { @MainActor [weak self] in | ||
| guard let self else { return } | ||
| let result = try? await self.webView.evaluateJavaScript(BrowserFindJavaScript.previousScript()) | ||
| let result = try? await self.webView.evaluateJavaScript(BrowserFindJavaScript.previousScript(), in: nil, in: .defaultClient) | ||
| self.parseFindResult(result) | ||
| } | ||
| } | ||
|
|
@@ -4909,7 +4911,7 @@ extension BrowserPanel { | |
| guard let self else { return } | ||
| let js = BrowserFindJavaScript.searchScript(query: needle) | ||
| do { | ||
| let result = try await self.webView.evaluateJavaScript(js) | ||
| let result = try await self.webView.evaluateJavaScript(js, in: nil, in: .defaultClient) | ||
| self.parseFindResult(result) | ||
| } catch { | ||
| NSLog("Find: browser JS search error: %@", error.localizedDescription) | ||
|
|
@@ -4921,7 +4923,7 @@ extension BrowserPanel { | |
| Task { @MainActor [weak self] in | ||
| guard let self else { return } | ||
| do { | ||
| _ = try await self.webView.evaluateJavaScript(BrowserFindJavaScript.clearScript()) | ||
| _ = try await self.webView.evaluateJavaScript(BrowserFindJavaScript.clearScript(), in: nil, in: .defaultClient) | ||
| } catch { | ||
| NSLog("Find: browser JS clear error: %@", error.localizedDescription) | ||
| } | ||
|
|
@@ -5236,25 +5238,25 @@ extension BrowserPanel { | |
| } | ||
|
|
||
| private func captureAddressBarPageFocusIfNeeded() { | ||
| webView.evaluateJavaScript(Self.addressBarFocusCaptureScript) { [weak self] result, error in | ||
| webView.evaluateJavaScript(Self.addressBarFocusCaptureScript, in: nil, in: .defaultClient) { [weak self] callResult in | ||
| #if DEBUG | ||
| guard let self else { return } | ||
| if let error { | ||
| switch callResult { | ||
| case .failure(let error): | ||
| dlog( | ||
| "browser.focus.addressBar.capture panel=\(self.id.uuidString.prefix(5)) " + | ||
| "result=error message=\(error.localizedDescription)" | ||
| ) | ||
| return | ||
| case .success(let result): | ||
| let resultValue = (result as? String) ?? "unknown" | ||
| dlog( | ||
| "browser.focus.addressBar.capture panel=\(self.id.uuidString.prefix(5)) " + | ||
| "result=\(resultValue)" | ||
| ) | ||
| } | ||
| let resultValue = (result as? String) ?? "unknown" | ||
| dlog( | ||
| "browser.focus.addressBar.capture panel=\(self.id.uuidString.prefix(5)) " + | ||
| "result=\(resultValue)" | ||
| ) | ||
| #else | ||
| _ = self | ||
| _ = result | ||
| _ = error | ||
| _ = callResult | ||
| #endif | ||
| } | ||
| } | ||
|
|
@@ -5308,7 +5310,14 @@ extension BrowserPanel { | |
| completion(false) | ||
| return | ||
| } | ||
| webView.evaluateJavaScript(Self.addressBarFocusRestoreScript) { [weak self] result, error in | ||
| webView.evaluateJavaScript(Self.addressBarFocusRestoreScript, in: nil, in: .defaultClient) { [weak self] callResult in | ||
| let result: Any? | ||
| let error: Error? | ||
| switch callResult { | ||
| case .success(let value): result = value; error = nil | ||
| case .failure(let err): result = nil; error = err | ||
| } | ||
|
|
||
| guard let self else { | ||
| completion(false) | ||
| return | ||
|
Comment on lines
5310
to
5323
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
The callback decomposes the Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time! |
||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.