Files

29 lines
1.4 KiB
Swift
Raw Permalink Normal View History

import Foundation
import UserNotifications
/// Focuses the terminal when a banner is clicked. The delegate must be set before the app finishes
/// launching or macOS drops the click, so it is installed from AppState.start().
final class BannerClickHandler: NSObject, UNUserNotificationCenterDelegate {
static let terminalKey = "terminalBundleID"
static let shared = BannerClickHandler()
static func install() {
guard Bundle.main.bundleIdentifier != nil else { return }
UNUserNotificationCenter.current().delegate = shared
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let id = response.notification.request.content.userInfo[Self.terminalKey] as? String
StatusFile.set("last-banner-click", "terminal=\(id ?? "none")")
DispatchQueue.main.async { TerminalFocuser.focus(bundleID: id) }
completionHandler()
}
/// Show banners even while the app is frontmost (e.g. its menu is open); otherwise macOS hides them.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.banner, .sound])
}
}