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

@ -84,12 +84,25 @@ extension Ghostty {
self.app = app
#if os(macOS)
// Subscribe to notifications for keyboard layout change so that we can update Ghostty.
NotificationCenter.default.addObserver(
// 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)
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
@ -100,11 +113,7 @@ extension Ghostty {
self.app = nil
#if os(macOS)
// Remove our observer
NotificationCenter.default.removeObserver(
self,
name: NSTextInputContext.keyboardSelectionDidChangeNotification,
object: nil)
NotificationCenter.default.removeObserver(self)
#endif
}
@ -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) {

View File

@ -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;
}