import Foundation import AppKit // WorkspaceEvents subscribes to the NSWorkspace notifications and the screen // parameter notification (spec section 7.4). The type turns each notification // into a callback. The type is main-actor isolated. @MainActor final class WorkspaceEvents { var onFrontmostChanged: ((pid_t) -> Void)? var onAppLaunched: ((NSRunningApplication) -> Void)? var onAppTerminated: ((pid_t) -> Void)? var onActiveSpaceChanged: (() -> Void)? var onScreenParametersChanged: (() -> Void)? private var tokens: [NSObjectProtocol] = [] // start subscribes to the notifications. func start() { let workspaceCenter = NSWorkspace.shared.notificationCenter tokens.append(workspaceCenter.addObserver( forName: NSWorkspace.didActivateApplicationNotification, object: nil, queue: .main) { [weak self] note in MainActor.assumeIsolated { guard let app = Self.app(from: note) else { return } self?.onFrontmostChanged?(app.processIdentifier) } }) tokens.append(workspaceCenter.addObserver( forName: NSWorkspace.didLaunchApplicationNotification, object: nil, queue: .main) { [weak self] note in MainActor.assumeIsolated { guard let app = Self.app(from: note) else { return } self?.onAppLaunched?(app) } }) tokens.append(workspaceCenter.addObserver( forName: NSWorkspace.didTerminateApplicationNotification, object: nil, queue: .main) { [weak self] note in MainActor.assumeIsolated { guard let app = Self.app(from: note) else { return } self?.onAppTerminated?(app.processIdentifier) } }) tokens.append(workspaceCenter.addObserver( forName: NSWorkspace.activeSpaceDidChangeNotification, object: nil, queue: .main) { [weak self] _ in MainActor.assumeIsolated { self?.onActiveSpaceChanged?() } }) tokens.append(NotificationCenter.default.addObserver( forName: NSApplication.didChangeScreenParametersNotification, object: nil, queue: .main) { [weak self] _ in MainActor.assumeIsolated { self?.onScreenParametersChanged?() } }) } // stop removes the subscriptions. func stop() { let workspaceCenter = NSWorkspace.shared.notificationCenter for token in tokens { workspaceCenter.removeObserver(token) NotificationCenter.default.removeObserver(token) } tokens.removeAll() } // app reads the NSRunningApplication from the notification user info. private static func app(from note: Notification) -> NSRunningApplication? { return note.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication } }