From e56cfbdc8b8a5550889452f9da0d71d382938bc1 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Sun, 6 Oct 2024 10:06:07 -1000 Subject: [PATCH] macos: set the proper app focus state --- macos/Sources/Ghostty/Ghostty.App.swift | 46 ++++++++++++++++++------- src/App.zig | 1 + 2 files changed, 35 insertions(+), 12 deletions(-) diff --git a/macos/Sources/Ghostty/Ghostty.App.swift b/macos/Sources/Ghostty/Ghostty.App.swift index 3ed082d87..5716e9801 100644 --- a/macos/Sources/Ghostty/Ghostty.App.swift +++ b/macos/Sources/Ghostty/Ghostty.App.swift @@ -83,14 +83,27 @@ extension Ghostty { } self.app = app - #if os(macOS) - // Subscribe to notifications for keyboard layout change so that we can update Ghostty. - NotificationCenter.default.addObserver( +#if os(macOS) + // Set our initial focus state + ghostty_app_set_focus(app, NSApp.isActive) + + let center = NotificationCenter.default + center.addObserver( self, selector: #selector(keyboardSelectionDidChange(notification:)), name: NSTextInputContext.keyboardSelectionDidChangeNotification, object: nil) - #endif + center.addObserver( + self, + selector: #selector(applicationDidBecomeActive(notification:)), + name: NSApplication.didBecomeActiveNotification, + object: nil) + center.addObserver( + self, + selector: #selector(applicationDidResignActive(notification:)), + name: NSApplication.didResignActiveNotification, + object: nil) +#endif self.readiness = .ready } @@ -98,14 +111,10 @@ extension Ghostty { deinit { // This will force the didSet callbacks to run which free. self.app = nil - - #if os(macOS) - // Remove our observer - NotificationCenter.default.removeObserver( - self, - name: NSTextInputContext.keyboardSelectionDidChangeNotification, - object: nil) - #endif + +#if os(macOS) + NotificationCenter.default.removeObserver(self) +#endif } // MARK: App Operations @@ -266,6 +275,19 @@ extension Ghostty { ghostty_app_keyboard_changed(app) } + // Called when the app becomes active. + @objc private func applicationDidBecomeActive(notification: NSNotification) { + guard let app = self.app else { return } + ghostty_app_set_focus(app, true) + } + + // Called when the app becomes inactive. + @objc private func applicationDidResignActive(notification: NSNotification) { + guard let app = self.app else { return } + ghostty_app_set_focus(app, false) + } + + // MARK: Ghostty Callbacks (macOS) static func closeSurface(_ userdata: UnsafeMutableRawPointer?, processAlive: Bool) { diff --git a/src/App.zig b/src/App.zig index b557aaa08..6a4a7a546 100644 --- a/src/App.zig +++ b/src/App.zig @@ -288,6 +288,7 @@ pub fn setQuit(self: *App) !void { /// This is separate from surface focus events. See the `focused` /// field for more information. pub fn focusEvent(self: *App, focused: bool) void { + log.debug("focus event focused={}", .{focused}); self.focused = focused; }