diff --git a/macos/Sources/Ghostty/SurfaceView.swift b/macos/Sources/Ghostty/SurfaceView.swift index 91f2f5263..8448cb5d2 100644 --- a/macos/Sources/Ghostty/SurfaceView.swift +++ b/macos/Sources/Ghostty/SurfaceView.swift @@ -74,6 +74,35 @@ extension Ghostty { windowFocus = false } } + .onAppear() { + // Welcome to the SwiftUI bug house of horrors. On macOS 12 (at least + // 12.5.1, didn't test other versions), the order in which the view + // is added to the window hierarchy is such that $surfaceFocus is + // not set to true for the first surface in a window. As a result, + // new windows are key (they have window focus) but the terminal surface + // does not have surface until the user clicks. Bad! + // + // There is a very real chance that I am doing something wrong, but it + // works great as-is on macOS 13, so I've instead decided to make the + // older macOS hacky. A workaround is on initial appearance to "steal + // focus" under certain conditions that seem to imply we're in the + // screwy state. + if #available(macOS 13, *) { + // If we're on a more modern version of macOS, do nothing. + return + } + if #available(macOS 12, *) { + // On macOS 13, the view is attached to a window at this point, + // so this is one extra check that we're a new view and behaving odd. + guard surfaceView.window == nil else { return } + DispatchQueue.main.async { + surfaceFocus = true + } + } + + // I don't know how older macOS versions behave but Ghostty only + // supports back to macOS 12 so its moot. + } } .ghosttySurfaceView(surfaceView) }