diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index bffe3632e333..f1782c2b6651 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -2302,6 +2302,15 @@ 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 = [] + /// Brief flag set during system-driven display relayout to suppress pruning + /// of disconnected display cache entries. + private var isHandlingDisplayDisconnect = false + /// 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 +2435,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 + ) + #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 +3561,79 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent ) } + // MARK: - Display reconnection window restoration + + /// Cache the current frame of a managed window, keyed by its current display. + /// During system-driven relayout (display disconnect), disconnected display + /// entries are preserved. User-initiated moves clear all other entries so + /// the window won't snap back to a display it was moved away from. + 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 { + if isHandlingDisplayDisconnect && !knownConnectedDisplayIDs.contains(otherDisplayID) { + // Preserve disconnected display entries during system relayout. + continue + } + displayWindowFrameCache[otherDisplayID]?.removeValue(forKey: windowID) + } + displayWindowFrameCache[displayID, default: [:]][windowID] = window.frame + } + + @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) + } + + @objc private func handleScreenParametersDidChange(_ notification: Notification) { + let currentDisplayIDs = Set(NSScreen.screens.compactMap { $0.cmuxDisplayID }) + let reconnected = currentDisplayIDs.subtracting(knownConnectedDisplayIDs) + let disconnected = knownConnectedDisplayIDs.subtracting(currentDisplayIDs) + knownConnectedDisplayIDs = currentDisplayIDs + + // Briefly suppress pruning of disconnected display entries so that + // the system-driven window relocation preserves the restore frame. + if !disconnected.isEmpty { + isHandlingDisplayDisconnect = true + DispatchQueue.main.async { [weak self] in + self?.isHandlingDisplayDisconnect = false + } + } + + 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) + } + } + } + private func startSessionAutosaveTimerIfNeeded() { guard sessionAutosaveTimer == nil else { return } let env = ProcessInfo.processInfo.environment @@ -4064,6 +4173,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent ) #endif notifyMainWindowContextsDidChange() + cacheWindowFrameForDisplay(window) if window.isKeyWindow { setActiveMainWindow(window) } @@ -8052,9 +8162,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 +8370,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 +11585,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 { diff --git a/Sources/Panels/BrowserPanel.swift b/Sources/Panels/BrowserPanel.swift index dfbd8a9c125f..f4fcab518441 100644 --- a/Sources/Panels/BrowserPanel.swift +++ b/Sources/Panels/BrowserPanel.swift @@ -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,7 +4869,7 @@ 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) } } @@ -4875,7 +4877,7 @@ extension BrowserPanel { 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 diff --git a/Sources/Panels/CmuxWebView.swift b/Sources/Panels/CmuxWebView.swift index 9693e3727ab2..f883c611210f 100644 --- a/Sources/Panels/CmuxWebView.swift +++ b/Sources/Panels/CmuxWebView.swift @@ -415,8 +415,8 @@ final class CmuxWebView: WKWebView { return ''; })(); """ - evaluateJavaScript(js) { result, _ in - guard let href = result as? String, !href.isEmpty, + evaluateJavaScript(js, in: nil, in: .defaultClient) { callResult in + guard let href = (try? callResult.get()) as? String, !href.isEmpty, let url = URL(string: href) else { completion(nil) return @@ -860,8 +860,8 @@ final class CmuxWebView: WKWebView { return candidateFromElement(single) || ''; })(); """ - evaluateJavaScript(js) { result, _ in - guard let src = result as? String, !src.isEmpty, + evaluateJavaScript(js, in: nil, in: .defaultClient) { callResult in + guard let src = (try? callResult.get()) as? String, !src.isEmpty, let url = URL(string: src) else { completion(nil) return @@ -940,8 +940,8 @@ final class CmuxWebView: WKWebView { return linkFromElement(single) || ''; })(); """ - evaluateJavaScript(js) { result, _ in - guard let href = result as? String, !href.isEmpty, + evaluateJavaScript(js, in: nil, in: .defaultClient) { callResult in + guard let href = (try? callResult.get()) as? String, !href.isEmpty, let url = URL(string: href) else { completion(nil) return @@ -982,9 +982,9 @@ final class CmuxWebView: WKWebView { return JSON.stringify({count: nodes.length, entries}); })(); """ - evaluateJavaScript(js) { [weak self] result, _ in + evaluateJavaScript(js, in: nil, in: .defaultClient) { [weak self] callResult in guard let self, - let payload = result as? String, + let payload = (try? callResult.get()) as? String, !payload.isEmpty else { return } self.debugContextDownload( "browser.ctxdl.inspect trace=\(traceID) kind=\(kind) payload=\(payload)" diff --git a/Sources/TerminalController.swift b/Sources/TerminalController.swift index 66d1c7232f63..2b5224235882 100644 --- a/Sources/TerminalController.swift +++ b/Sources/TerminalController.swift @@ -6837,6 +6837,7 @@ class TerminalController { } } } else { + // macOS < 11.0: contentWorld parameter is ignored; JS runs in .page webView.evaluateJavaScript(script) { value, error in if let error { finish(nil, error.localizedDescription) @@ -7106,7 +7107,7 @@ class TerminalController { script: asyncFunctionBody, timeout: timeout, preferAsync: true, - contentWorld: .page + contentWorld: .defaultClient ) } else { let evaluateFallback = """ @@ -7114,25 +7115,7 @@ class TerminalController { \(asyncFunctionBody) })() """ - rawResult = v2RunJavaScript(webView, script: evaluateFallback, timeout: timeout, contentWorld: .page) - } - - if !useEval, case .failure(let pageMessage) = rawResult, #available(macOS 11.0, *) { - let isolatedResult = v2RunJavaScript( - webView, - script: asyncFunctionBody, - timeout: timeout, - preferAsync: true, - contentWorld: .defaultClient - ) - switch isolatedResult { - case .success: - rawResult = isolatedResult - case .failure(let isolatedMessage): - if isolatedMessage != pageMessage { - rawResult = .failure("\(pageMessage) (isolated-world retry: \(isolatedMessage))") - } - } + rawResult = v2RunJavaScript(webView, script: evaluateFallback, timeout: timeout, contentWorld: .defaultClient) } switch rawResult { @@ -9373,7 +9356,8 @@ class TerminalController { browserPanel.webView, script: BrowserPanel.telemetryHookBootstrapScriptSource, timeout: 5.0, - contentWorld: .page + preferAsync: true, + contentWorld: .defaultClient ) } @@ -9382,7 +9366,8 @@ class TerminalController { browserPanel.webView, script: BrowserPanel.dialogTelemetryHookBootstrapScriptSource, timeout: 5.0, - contentWorld: .page + preferAsync: true, + contentWorld: .defaultClient ) } @@ -9414,7 +9399,7 @@ class TerminalController { })() """ - switch v2RunJavaScript(browserPanel.webView, script: script, timeout: 5.0, contentWorld: .page) { + switch v2RunJavaScript(browserPanel.webView, script: script, timeout: 5.0, preferAsync: true, contentWorld: .defaultClient) { case .failure(let message): return .err(code: "js_error", message: message, data: nil) case .success(let value): @@ -10072,7 +10057,7 @@ class TerminalController { return { ok: true, items }; })() """ - switch v2RunJavaScript(browserPanel.webView, script: script, timeout: 5.0, contentWorld: .page) { + switch v2RunJavaScript(browserPanel.webView, script: script, timeout: 5.0, preferAsync: true, contentWorld: .defaultClient) { case .failure(let message): return .err(code: "js_error", message: message, data: nil) case .success(let value): @@ -10110,7 +10095,7 @@ class TerminalController { return { ok: true, items }; })() """ - switch v2RunJavaScript(browserPanel.webView, script: script, timeout: 5.0, contentWorld: .page) { + switch v2RunJavaScript(browserPanel.webView, script: script, timeout: 5.0, preferAsync: true, contentWorld: .defaultClient) { case .failure(let message): return .err(code: "js_error", message: message, data: nil) case .success(let value): @@ -10287,7 +10272,7 @@ class TerminalController { scripts.append(script) v2BrowserInitScriptsBySurface[surfaceId] = scripts - let userScript = WKUserScript(source: script, injectionTime: .atDocumentStart, forMainFrameOnly: false) + let userScript = WKUserScript(source: script, injectionTime: .atDocumentStart, forMainFrameOnly: false, in: .defaultClient) browserPanel.webView.configuration.userContentController.addUserScript(userScript) _ = v2RunBrowserJavaScript(browserPanel.webView, surfaceId: surfaceId, script: script, timeout: 10.0) @@ -10340,7 +10325,7 @@ class TerminalController { })() """ - let userScript = WKUserScript(source: source, injectionTime: .atDocumentStart, forMainFrameOnly: false) + let userScript = WKUserScript(source: source, injectionTime: .atDocumentStart, forMainFrameOnly: false, in: .defaultClient) browserPanel.webView.configuration.userContentController.addUserScript(userScript) _ = v2RunBrowserJavaScript(browserPanel.webView, surfaceId: surfaceId, script: source, timeout: 10.0)