import Foundation import AppKit import ApplicationServices // ObserverContext carries the data for one AX observer. The C callback reads // the context from the refcon pointer. The registry keeps the context alive. final class ObserverContext { let pid: pid_t let handler: (pid_t, String, AXUIElement) -> Void init(pid: pid_t, handler: @escaping (pid_t, String, AXUIElement) -> Void) { self.pid = pid self.handler = handler } } // observerCallback is the C callback for every AX observer. The callback has // no captured state. The callback reads the context from the refcon pointer. // The callback hops to the main actor and calls the handler. private let observerCallback: AXObserverCallback = { _, element, notification, refcon in guard let refcon = refcon else { return } let context = Unmanaged.fromOpaque(refcon).takeUnretainedValue() let name = notification as String let pid = context.pid let handler = context.handler DispatchQueue.main.async { handler(pid, name, element) } } // AppObserverRegistry holds one AXObserver per regular application. The // registry registers the notifications of spec section 7.4. The registry // removes the observer when the application terminates. The registry is // main-actor isolated. @MainActor final class AppObserverRegistry { // Entry holds the state of one application observer. private final class Entry { let observer: AXObserver let appElement: AXUIElement let context: ObserverContext var windowElements: [AXUIElement] = [] init(observer: AXObserver, appElement: AXUIElement, context: ObserverContext) { self.observer = observer self.appElement = appElement self.context = context } } private var entries: [pid_t: Entry] = [:] // The application element gets these notifications. private let appNotifications = [ kAXWindowCreatedNotification, kAXFocusedWindowChangedNotification, kAXMainWindowChangedNotification, kAXWindowMiniaturizedNotification, kAXWindowDeminiaturizedNotification ] // Each window element gets these notifications. private let windowNotifications = [ kAXUIElementDestroyedNotification, kAXTitleChangedNotification, kAXMovedNotification, kAXResizedNotification ] // addApp creates the observer for one application. The handler runs on the // main actor. The function registers the application notifications. func addApp(pid: pid_t, handler: @escaping (pid_t, String, AXUIElement) -> Void) { guard entries[pid] == nil else { return } var observer: AXObserver? let error = AXObserverCreate(pid, observerCallback, &observer) guard error == .success, let observer = observer else { Log.tracking.error("AXObserverCreate failed for pid \(pid): \(error.rawValue)") return } let appElement = AXUIElementCreateApplication(pid) let context = ObserverContext(pid: pid, handler: handler) let entry = Entry(observer: observer, appElement: appElement, context: context) let refcon = Unmanaged.passUnretained(context).toOpaque() for name in appNotifications { AXObserverAddNotification(observer, appElement, name as CFString, refcon) } CFRunLoopAddSource(CFRunLoopGetMain(), AXObserverGetRunLoopSource(observer), .defaultMode) entries[pid] = entry } // setWindowElements registers the per-window notifications. The function // removes the notifications of the old window elements first. The caller // passes the current window elements after each enumeration. func setWindowElements(pid: pid_t, windows: [AXUIElement]) { guard let entry = entries[pid] else { return } let refcon = Unmanaged.passUnretained(entry.context).toOpaque() for element in entry.windowElements { for name in windowNotifications { AXObserverRemoveNotification(entry.observer, element, name as CFString) } } for element in windows { for name in windowNotifications { AXObserverAddNotification(entry.observer, element, name as CFString, refcon) } } entry.windowElements = windows } // removeApp removes the observer of one application. The function runs when // the application terminates. func removeApp(pid: pid_t) { guard let entry = entries[pid] else { return } CFRunLoopRemoveSource(CFRunLoopGetMain(), AXObserverGetRunLoopSource(entry.observer), .defaultMode) entries[pid] = nil } // removeAll removes all observers. The function runs on stop and on an // Accessibility loss. func removeAll() { for pid in Array(entries.keys) { removeApp(pid: pid) } } }