|
| 1 | +import AppKit |
| 2 | +import ApplicationServices |
| 3 | +import Foundation |
| 4 | + |
| 5 | +public final class AXNotificationStream: AsyncSequence { |
| 6 | + public typealias Stream = AsyncStream<Element> |
| 7 | + public typealias Continuation = Stream.Continuation |
| 8 | + public typealias AsyncIterator = Stream.AsyncIterator |
| 9 | + public typealias Element = (name: String, info: CFDictionary) |
| 10 | + |
| 11 | + private var continuation: Continuation |
| 12 | + private let stream: Stream |
| 13 | + |
| 14 | + public func makeAsyncIterator() -> Stream.AsyncIterator { |
| 15 | + stream.makeAsyncIterator() |
| 16 | + } |
| 17 | + |
| 18 | + deinit { |
| 19 | + continuation.finish() |
| 20 | + } |
| 21 | + |
| 22 | + public init( |
| 23 | + app: NSRunningApplication, |
| 24 | + element: AXUIElement? = nil, |
| 25 | + notificationNames: String... |
| 26 | + ) { |
| 27 | + var cont: Continuation! |
| 28 | + stream = Stream { continuation in |
| 29 | + cont = continuation |
| 30 | + } |
| 31 | + continuation = cont |
| 32 | + var observer: AXObserver? |
| 33 | + |
| 34 | + func callback( |
| 35 | + observer: AXObserver, |
| 36 | + element: AXUIElement, |
| 37 | + notificationName: CFString, |
| 38 | + userInfo: CFDictionary, |
| 39 | + pointer: UnsafeMutableRawPointer? |
| 40 | + ) { |
| 41 | + guard let pointer = pointer?.assumingMemoryBound(to: Continuation.self) |
| 42 | + else { return } |
| 43 | + pointer.pointee.yield((notificationName as String, userInfo)) |
| 44 | + } |
| 45 | + |
| 46 | + _ = AXObserverCreateWithInfoCallback( |
| 47 | + app.processIdentifier, |
| 48 | + callback, |
| 49 | + &observer |
| 50 | + ) |
| 51 | + guard let observer else { |
| 52 | + continuation.finish() |
| 53 | + return |
| 54 | + } |
| 55 | + |
| 56 | + let observingElement = element ?? AXUIElementCreateApplication(app.processIdentifier) |
| 57 | + continuation.onTermination = { @Sendable _ in |
| 58 | + for name in notificationNames { |
| 59 | + AXObserverRemoveNotification(observer, observingElement, name as CFString) |
| 60 | + } |
| 61 | + CFRunLoopRemoveSource( |
| 62 | + CFRunLoopGetMain(), |
| 63 | + AXObserverGetRunLoopSource(observer), |
| 64 | + .commonModes |
| 65 | + ) |
| 66 | + } |
| 67 | + for name in notificationNames { |
| 68 | + AXObserverAddNotification(observer, observingElement, name as CFString, &continuation) |
| 69 | + } |
| 70 | + CFRunLoopAddSource( |
| 71 | + CFRunLoopGetMain(), |
| 72 | + AXObserverGetRunLoopSource(observer), |
| 73 | + .commonModes |
| 74 | + ) |
| 75 | + } |
| 76 | +} |
0 commit comments