public import AppKit public import Foundation @MainActor public final class WorkspaceObserver { static let notificationNames: [Notification.Name] = [ NSWorkspace.didLaunchApplicationNotification, NSWorkspace.didTerminateApplicationNotification, NSWorkspace.didActivateApplicationNotification, NSWorkspace.didHideApplicationNotification, NSWorkspace.didUnhideApplicationNotification, NSWorkspace.activeSpaceDidChangeNotification, NSWorkspace.didWakeNotification, ] private let center: NotificationCenter private let workspace: NSWorkspace? private var applicationsObservation: NSKeyValueObservation? private var knownProcesses: Set = [] private let enqueue: @Sendable (@escaping @MainActor @Sendable () -> Void) -> Void private var observers: [any NSObjectProtocol] = [] private var receive: (@MainActor (Notification.Name, NSRunningApplication?) -> Void)? private var lifetime: UInt64 = 0 public convenience init() { self.init(center: NSWorkspace.shared.notificationCenter, workspace: NSWorkspace.shared) } init( center: NotificationCenter, workspace: NSWorkspace? = nil, enqueue: @escaping @Sendable (@escaping @MainActor @Sendable () -> Void) -> Void = { action in MainActor.assumeIsolated { action() } } ) { self.center = center self.workspace = workspace self.enqueue = enqueue } public func start(receive: @escaping @MainActor (Notification.Name, NSRunningApplication?) -> Void) { stop() self.receive = receive let generation = lifetime if let workspace { knownProcesses = Set(workspace.runningApplications.map(\.processIdentifier)) // Removals arrive with no new value, so always re-read the whole list. applicationsObservation = workspace.observe(\.runningApplications) { [weak self] _, _ in Task { @MainActor [weak self] in guard let self, self.lifetime == generation, let workspace = self.workspace else { return } self.receiveRunningApplications(workspace.runningApplications) } } } let enqueue = enqueue for name in Self.notificationNames { observers.append( center.addObserver(forName: name, object: nil, queue: .main) { [weak self] notification in let running = notification.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication enqueue { [weak self] in guard let self, self.lifetime == generation else { return } self.receive?(name, running) } }) } } func receiveRunningApplications(_ applications: [NSRunningApplication]) { let current = Set(applications.map(\.processIdentifier)) let added = current.subtracting(knownProcesses) knownProcesses = current for application in applications where added.contains(application.processIdentifier) { receive?(NSWorkspace.didLaunchApplicationNotification, application) } } public func stop() { applicationsObservation?.invalidate() applicationsObservation = nil knownProcesses.removeAll() lifetime &+= 1 receive = nil for observer in observers { center.removeObserver(observer) } observers.removeAll() } isolated deinit { stop() } }