macos: set the proper app focus state

This commit is contained in:
Mitchell Hashimoto
2024-10-06 10:06:07 -10:00
parent 8dc4ebb4f7
commit e56cfbdc8b
2 changed files with 35 additions and 12 deletions

View File

@ -83,14 +83,27 @@ extension Ghostty {
} }
self.app = app self.app = app
#if os(macOS) #if os(macOS)
// Subscribe to notifications for keyboard layout change so that we can update Ghostty. // Set our initial focus state
NotificationCenter.default.addObserver( ghostty_app_set_focus(app, NSApp.isActive)
let center = NotificationCenter.default
center.addObserver(
self, self,
selector: #selector(keyboardSelectionDidChange(notification:)), selector: #selector(keyboardSelectionDidChange(notification:)),
name: NSTextInputContext.keyboardSelectionDidChangeNotification, name: NSTextInputContext.keyboardSelectionDidChangeNotification,
object: nil) 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 self.readiness = .ready
} }
@ -98,14 +111,10 @@ extension Ghostty {
deinit { deinit {
// This will force the didSet callbacks to run which free. // This will force the didSet callbacks to run which free.
self.app = nil self.app = nil
#if os(macOS) #if os(macOS)
// Remove our observer NotificationCenter.default.removeObserver(self)
NotificationCenter.default.removeObserver( #endif
self,
name: NSTextInputContext.keyboardSelectionDidChangeNotification,
object: nil)
#endif
} }
// MARK: App Operations // MARK: App Operations
@ -266,6 +275,19 @@ extension Ghostty {
ghostty_app_keyboard_changed(app) 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) // MARK: Ghostty Callbacks (macOS)
static func closeSurface(_ userdata: UnsafeMutableRawPointer?, processAlive: Bool) { static func closeSurface(_ userdata: UnsafeMutableRawPointer?, processAlive: Bool) {

View File

@ -288,6 +288,7 @@ pub fn setQuit(self: *App) !void {
/// This is separate from surface focus events. See the `focused` /// This is separate from surface focus events. See the `focused`
/// field for more information. /// field for more information.
pub fn focusEvent(self: *App, focused: bool) void { pub fn focusEvent(self: *App, focused: bool) void {
log.debug("focus event focused={}", .{focused});
self.focused = focused; self.focused = focused;
} }