import ApplicationServices import CPrivateAPI import CoreGraphics import Darwin import Foundation import RealityDriverSupport import Synchronization // The condition protects only jobs and lifecycle; AX objects are created and released inside threadMain. final class DriverAppThread: @unchecked Sendable { private typealias Job = @Sendable (Result) -> Void private let condition = NSCondition() private var jobs: [Job] = [] private var stopping = false private let pid: Int32 init(pid: Int32) { self.pid = pid Thread { [self] in threadMain() }.start() } func perform( _ operation: @escaping @Sendable (DriverAXApplication) throws -> Value ) throws -> Value { precondition(!Thread.isMainThread, "The main thread must not wait for AX") let result = Mutex?>(nil) let completion = DispatchSemaphore(value: 0) condition.lock() guard !stopping else { condition.unlock() throw DriverError("AX worker for PID \(pid) is stopped") } jobs.append { application in let outcome: Result do { outcome = .success(try operation(application.get())) } catch { outcome = .failure(DriverError(String(describing: error))) } result.withLock { $0 = outcome } completion.signal() } condition.signal() condition.unlock() guard completion.wait(timeout: .now() + 15) == .success else { shutdown() throw DriverError("AX operation exceeded 15 seconds; PID \(pid) worker retired, effect unverified") } guard let outcome = result.withLock({ $0 }) else { preconditionFailure("AX completion must contain a result") } return try outcome.get() } func shutdown() { condition.lock() stopping = true condition.broadcast() condition.unlock() } private func threadMain() { precondition(!Thread.isMainThread) let application: Result do { application = .success(try DriverAXApplication(pid: pid)) } catch { application = .failure(DriverError(String(describing: error))) } while true { condition.lock() while jobs.isEmpty && !stopping { condition.wait() } if stopping { let cancelled = jobs jobs.removeAll() condition.unlock() for job in cancelled { job(.failure(DriverError("AX worker stopped"))) } return } let job = jobs.removeFirst() condition.unlock() autoreleasepool { job(application) } } } } final class DriverAXApplication { let pid: Int32 let element: DriverAXElement private let getWindow: ParcelAXGetWindowFunction private var registered: [UInt32: DriverAXElement] = [:] init(pid: Int32) throws { precondition(!Thread.isMainThread) self.pid = pid guard let symbol = dlsym(UnsafeMutableRawPointer(bitPattern: -2), "_AXUIElementGetWindow") else { throw DriverError("Required private AX window identification symbol is unavailable") } self.getWindow = unsafeBitCast(symbol, to: ParcelAXGetWindowFunction.self) self.element = try DriverAXElement(AXUIElementCreateApplication(pid)) } func standardWindowIDs(candidates: Set) throws -> (ids: [UInt32], identified: [UInt32], warnings: [String]) { var roles: [DriverWindowRole] = [] var identified: [UInt32] = [] var warnings: [String] = [] for window in try element.elements(kAXWindowsAttribute) { let id: UInt32 do { id = try identify(window) } catch let error as DriverAXError { guard case .failure("_AXUIElementGetWindow", let code) = error, code == AXError.attributeUnsupported.rawValue || code == AXError.illegalArgument.rawValue else { throw error } let role = try window.optionalString(kAXRoleAttribute) ?? "missing" let subrole = try window.optionalString(kAXSubroleAttribute) ?? "missing" warnings.append("\(error); role=\(role) subrole=\(subrole)") continue } guard candidates.contains(id) else { continue } let role = try window.string(kAXRoleAttribute) identified.append(id) guard role == kAXWindowRole else { continue } let subrole = try window.string(kAXSubroleAttribute) if subrole == kAXStandardWindowSubrole { try DriverWindowMetadata.requireOwner(pid: pid, windowID: id) } roles.append(DriverWindowRole(windowID: id, role: role, subrole: subrole)) } return (try DriverWindowSelection.standardWindowIDs(roles), identified.sorted(), warnings) } func register(windowID: UInt32) throws -> [String] { try DriverWindowMetadata.requireOwner(pid: pid, windowID: windowID) if let existing = registered[windowID] { try verify(existing, windowID: windowID) return [] } let windows = try element.elements(kAXWindowsAttribute) let identities = try windows.map { window -> DriverWindowIdentity in do { return .identified(try identify(window)) } catch let error as DriverAXError { guard case .failure("_AXUIElementGetWindow", let code) = error, code == AXError.attributeUnsupported.rawValue || code == AXError.illegalArgument.rawValue else { throw error } return .unsupported(String(describing: error)) } } let selection = try DriverWindowSelection.select(windowID: windowID, candidates: identities) let found = windows[selection.index] try verify(found, windowID: windowID) registered[windowID] = found return selection.warnings } func window(_ windowID: UInt32) throws -> DriverAXElement { guard let window = registered[windowID] else { throw DriverError("Unregistered window: PID \(pid), CGWindowID \(windowID)") } try DriverWindowMetadata.requireOwner(pid: pid, windowID: windowID) try verify(window, windowID: windowID) return window } func inputTarget(fixture: Bool, parcel: Bool) throws -> DriverInputTarget { let focused = try element.element(kAXFocusedWindowAttribute) let id = try identify(focused) try DriverWindowMetadata.requireOwner(pid: pid, windowID: id) let panel = try parcel && focused.string(kAXSubroleAttribute) != kAXStandardWindowSubrole let target = DriverInputTarget(pid: pid, windowID: id, fixture: fixture, panel: panel) try target.requireOwned(registered: Set(registered.keys)) if !panel { _ = try window(id) } return target } func move(windowID: UInt32, target: CGRect, preserveEnhancedUI: Bool) throws -> DriverFrame { let window = try window(windowID) let before = try window.frame if before == target { return DriverFrame(x: before.minX, y: before.minY, width: before.width, height: before.height) } let enhanced: Bool? do { enhanced = try element.boolean("AXEnhancedUserInterface") } catch let error as DriverAXError { switch error { case .failure(_, let code) where code == AXError.attributeUnsupported.rawValue || code == AXError.noValue.rawValue: enhanced = nil default: throw error } } var disable = enhanced == true && !preserveEnhancedUI if disable { do { try element.setBoolean("AXEnhancedUserInterface", false) } catch let error as DriverAXError { guard case .failure(_, let code) = error, code == AXError.attributeUnsupported.rawValue || code == AXError.notImplemented.rawValue else { throw error } if try element.boolean("AXEnhancedUserInterface") { disable = false } } } var writeError: (any Error)? do { let published = try DriverWindowMetadata.frame(pid: pid, windowID: windowID) try DriverFrameWrites.apply( target: target, publishedSize: CGSize(width: published.width, height: published.height), readSize: { try window.size }, readPosition: { try window.frame.origin }, writeSize: { try window.setSize($0) }, writePosition: { try window.setPosition($0) }) _ = try window.frame } catch { writeError = error } if disable { do { try element.setBoolean("AXEnhancedUserInterface", true) } catch { guard let failure = error as? DriverAXError, case .failure(_, let code) = failure, code == AXError.attributeUnsupported.rawValue || code == AXError.notImplemented.rawValue, try element.boolean("AXEnhancedUserInterface") else { throw DriverError( "AXEnhancedUserInterface restoration failed: \(error); write error: \(String(describing: writeError))" ) } } } if let writeError { throw writeError } let actual = try window.frame return DriverFrame(x: actual.minX, y: actual.minY, width: actual.width, height: actual.height) } func requirePickup(windowID: UInt32, point: CGPoint) throws { _ = try window(windowID) let frame = try DriverWindowMetadata.frame(pid: pid, windowID: windowID) guard CGRect(x: frame.x, y: frame.y, width: frame.width, height: frame.height).contains(point) else { throw DriverError("Safety stop: drag pickup is outside its owned CG frame; input withheld") } // System canvases can have full-display bounds without a full-display input region. let system = try DriverAXElement(AXUIElementCreateSystemWide()) var raw: AXUIElement? try system.call("AXUIElementCopyElementAtPosition") { AXUIElementCopyElementAtPosition(system.raw, Float(point.x), Float(point.y), &raw) } guard let raw else { throw DriverError("Safety stop: native drag pickup could not be identified; input withheld") } var hitPID: pid_t = 0 try system.call("AXUIElementGetPid") { AXUIElementGetPid(raw, &hitPID) } guard hitPID == pid else { throw DriverError( "Safety stop: drag pickup is covered by another app (expected PID \(pid), hit PID \(hitPID)); input withheld" ) } let hit = try DriverAXElement(raw) let hitWindow = try hit.string(kAXRoleAttribute) == kAXWindowRole ? hit : hit.element(kAXWindowAttribute) try DriverPickupIdentity.requireOwned( pid: pid, windowID: windowID, hitPID: hitPID, hitWindowID: identify(hitWindow)) } func focus(windowID: UInt32) throws { let window = try window(windowID) try window.setBoolean(kAXMainAttribute, true) try element.setElement(kAXFocusedWindowAttribute, window) guard try DriverReadback.focusAfterRaising( raise: { try window.action(kAXRaiseAction) }, isUnsupported: { error in guard case DriverAXError.failure(let operation, let code) = error else { return false } return operation == kAXRaiseAction && (code == AXError.actionUnsupported.rawValue || code == AXError.attributeUnsupported.rawValue) }, verifyFocus: { try DriverReadback.untilTrue( deadline: ContinuousClock.now.advanced(by: .seconds(3)), now: { .now }, pause: { Thread.sleep(forTimeInterval: 0.025) }, read: { try identify(element.element(kAXFocusedWindowAttribute)) == windowID }) }) else { throw DriverError("AX focus was not observed for CGWindowID \(windowID)") } } func minimize(windowID: UInt32) throws { let window = try window(windowID) try window.setBoolean(kAXMinimizedAttribute, true) let deadline = ContinuousClock.now.advanced(by: .seconds(3)) guard try DriverReadback.untilTrue( deadline: deadline, now: { .now }, pause: { Thread.sleep(forTimeInterval: 0.025) }, read: { try window.boolean(kAXMinimizedAttribute) }) else { throw DriverError("AX minimize was not observed for CGWindowID \(windowID)") } } func close(windowID: UInt32) throws { let window = try window(windowID) let button = try window.element(kAXCloseButtonAttribute) guard try button.boolean(kAXEnabledAttribute) else { throw DriverError("AX close button is disabled") } try button.action(kAXPressAction) registered.removeValue(forKey: windowID) } func pressTourTidy( windowID: UInt32, launchDate: Double, control: DriverTourControl, method: DriverTourInputMethod = .ax, requireLaunch: @Sendable () throws -> Void ) throws -> DriverTourPressReceipt { try requireLaunch() let tourWindow = try window(windowID) try DriverWindowMetadata.requireVisibleOwner(pid: pid, windowID: windowID) guard try tourWindow.string(kAXRoleAttribute) == kAXWindowRole, try !tourWindow.boolean(kAXMinimizedAttribute) else { throw DriverError("Safety stop: the owned tour must be a visible AX window") } let deadline = ContinuousClock.now.advanced(by: .seconds(4)) var pending = [tourWindow] var visited: [DriverAXElement] = [] var buttons: [DriverAXElement] = [] while let node = pending.popLast() { if visited.contains(where: { CFEqual($0.raw, node.raw) }) { continue } guard visited.count < 512, ContinuousClock.now < deadline else { throw DriverError("Tour AX search exceeded 512 nodes or four seconds; Tidy was not pressed") } visited.append(node) if try node.optionalString(kAXIdentifierAttribute) == control.rawValue { buttons.append(node) } pending += try node.optionalElements(kAXChildrenAttribute) } guard buttons.count == 1, let button = buttons.first, try button.string(kAXRoleAttribute) == control.role, try button.boolean(kAXEnabledAttribute) else { throw DriverError("The exact rendered \(control.rawValue) AX button is missing, ambiguous, or disabled") } try requireLaunch() try verify(tourWindow, windowID: windowID) try DriverWindowMetadata.requireVisibleOwner(pid: pid, windowID: windowID) var buttonPID: pid_t = 0 try button.call("AXUIElementGetPid") { AXUIElementGetPid(button.raw, &buttonPID) } guard buttonPID == pid else { throw DriverError("Safety stop: tour.tidy changed AX application ownership") } let clickFrame: DriverFrame? if method == .mouse { guard control == .tidy else { throw DriverError("Mouse tour delivery is limited to Tidy") } let frame = try button.frame let point = CGPoint(x: frame.midX, y: frame.midY) try DriverInput.clickTour(pid: pid, windowID: windowID, point: point) { try requireLaunch() try self.verify(tourWindow, windowID: windowID) try DriverWindowMetadata.requireVisibleOwner(pid: self.pid, windowID: windowID) guard try button.boolean(kAXEnabledAttribute), try button.frame == frame else { throw DriverError("Safety stop: Tidy button moved or became disabled before the click") } try self.requireHit(button: button, at: point) } clickFrame = DriverFrame(x: frame.minX, y: frame.minY, width: frame.width, height: frame.height) } else { try button.action(kAXPressAction) clickFrame = nil } return DriverTourPressReceipt( pid: pid, windowID: windowID, launchDate: launchDate, identifier: control.rawValue, role: control.role, action: method == .ax ? kAXPressAction : "leftMouseDown/leftMouseUp", enabled: true, visitedNodes: visited.count, method: method, clickFrame: clickFrame) } private func requireHit(button: DriverAXElement, at point: CGPoint) throws { let system = try DriverAXElement(AXUIElementCreateSystemWide()) var raw: AXUIElement? try system.call("AXUIElementCopyElementAtPosition") { AXUIElementCopyElementAtPosition(system.raw, Float(point.x), Float(point.y), &raw) } guard let raw else { throw DriverError("Safety stop: Tidy center has no AX hit target") } var hit = try DriverAXElement(raw) for _ in 0..<16 { var owner: pid_t = 0 try hit.call("AXUIElementGetPid") { AXUIElementGetPid(hit.raw, &owner) } guard owner == pid else { throw DriverError("Safety stop: another app covers Tidy's click point") } if CFEqual(hit.raw, button.raw) { return } hit = try hit.element(kAXParentAttribute) } throw DriverError("Safety stop: Tidy's click point does not identify its exact rendered button") } func increments(windowID: UInt32) throws -> DriverIncrements { let value = try window(windowID).sizeValue("AXSizeIncrement") guard value.width.isFinite, value.height.isFinite, value.width > 0, value.height > 0 else { throw DriverError("AXSizeIncrement must contain positive finite dimensions") } return DriverIncrements(width: value.width, height: value.height, source: "AXSizeIncrement") } private func identify(_ element: DriverAXElement) throws -> UInt32 { var id: UInt32 = 0 try element.call("_AXUIElementGetWindow") { getWindow(element.raw, &id) } guard id > 0 else { throw DriverError("AX window identification returned a zero CGWindowID") } return id } private func verify(_ element: DriverAXElement, windowID: UInt32) throws { var owner: pid_t = 0 try element.call("AXUIElementGetPid") { AXUIElementGetPid(element.raw, &owner) } guard owner == pid, try identify(element) == windowID else { throw DriverError("AX identity changed for PID \(pid), CGWindowID \(windowID)") } } } enum DriverAXError: Error, CustomStringConvertible { case failure(String, Int32) case timeout(String) case malformed(String) var description: String { switch self { case .failure(let operation, let code): "\(operation) failed with AX code \(code)" case .timeout(let operation): "\(operation) timed out after \(DriverAXElement.timeout) seconds" case .malformed(let attribute): "AX attribute has no value or an unexpected type: \(attribute)" } } } struct DriverAXElement { let raw: AXUIElement static let timeout: Float = 0.5 init(_ raw: AXUIElement) throws { precondition(!Thread.isMainThread) self.raw = raw try call("AXUIElementSetMessagingTimeout") { AXUIElementSetMessagingTimeout(raw, Self.timeout) } } func call(_ operation: String, _ body: () -> AXError) throws { precondition(!Thread.isMainThread) let start = DispatchTime.now().uptimeNanoseconds let result = body() let elapsed = Double(DispatchTime.now().uptimeNanoseconds - start) / 1_000_000_000 if result == .cannotComplete && elapsed >= Double(Self.timeout) * 0.9 { throw DriverAXError.timeout(operation) } guard result == .success else { throw DriverAXError.failure(operation, result.rawValue) } } func value(_ attribute: String) throws -> CFTypeRef { var value: CFTypeRef? try call(attribute) { AXUIElementCopyAttributeValue(raw, attribute as CFString, &value) } guard let value else { throw DriverAXError.malformed(attribute) } return value } private func checked(_ value: CFTypeRef, type: CFTypeID, attribute: String) throws -> T { guard CFGetTypeID(value) == type else { throw DriverAXError.malformed(attribute) } return Unmanaged.fromOpaque(Unmanaged.passUnretained(value).toOpaque()).takeUnretainedValue() } func string(_ attribute: String) throws -> String { let string: CFString = try checked(value(attribute), type: CFStringGetTypeID(), attribute: attribute) return string as String } func optionalString(_ attribute: String) throws -> String? { do { return try string(attribute) } catch let error as DriverAXError { guard case .failure(_, let code) = error, code == AXError.attributeUnsupported.rawValue || code == AXError.noValue.rawValue else { throw error } return nil } } func optionalElements(_ attribute: String) throws -> [DriverAXElement] { do { return try elements(attribute) } catch let error as DriverAXError { guard case .failure(_, let code) = error, code == AXError.attributeUnsupported.rawValue || code == AXError.noValue.rawValue else { throw error } return [] } } func boolean(_ attribute: String) throws -> Bool { let boolean: CFBoolean = try checked(value(attribute), type: CFBooleanGetTypeID(), attribute: attribute) return CFBooleanGetValue(boolean) } func element(_ attribute: String) throws -> DriverAXElement { let element: AXUIElement = try checked(value(attribute), type: AXUIElementGetTypeID(), attribute: attribute) return try DriverAXElement(element) } func elements(_ attribute: String) throws -> [DriverAXElement] { let array: CFArray = try checked(value(attribute), type: CFArrayGetTypeID(), attribute: attribute) let count = CFArrayGetCount(array) guard count <= 4096 else { throw DriverError("AX child list exceeds 4096 elements") } return try (0...fromOpaque(pointer).takeUnretainedValue() let element: AXUIElement = try checked(object, type: AXUIElementGetTypeID(), attribute: attribute) return try DriverAXElement(element) } } func sizeValue(_ attribute: String) throws -> CGSize { let value: AXValue = try checked(value(attribute), type: AXValueGetTypeID(), attribute: attribute) var size = CGSize.zero guard AXValueGetType(value) == .cgSize, AXValueGetValue(value, .cgSize, &size) else { throw DriverAXError.malformed(attribute) } return size } var size: CGSize { get throws { try sizeValue(kAXSizeAttribute) } } var frame: CGRect { get throws { let value: AXValue = try checked( value(kAXPositionAttribute), type: AXValueGetTypeID(), attribute: kAXPositionAttribute) var point = CGPoint.zero guard AXValueGetType(value) == .cgPoint, AXValueGetValue(value, .cgPoint, &point) else { throw DriverAXError.malformed(kAXPositionAttribute) } return try CGRect(origin: point, size: size) } } func setPosition(_ point: CGPoint) throws { var point = point guard let value = AXValueCreate(.cgPoint, &point) else { throw DriverAXError.malformed(kAXPositionAttribute) } try set(kAXPositionAttribute, value) } func setSize(_ size: CGSize) throws { var size = size guard let value = AXValueCreate(.cgSize, &size) else { throw DriverAXError.malformed(kAXSizeAttribute) } try set(kAXSizeAttribute, value) } func setBoolean(_ attribute: String, _ boolean: Bool) throws { try set(attribute, boolean ? kCFBooleanTrue : kCFBooleanFalse) } func setElement(_ attribute: String, _ element: DriverAXElement) throws { try set(attribute, element.raw) } private func set(_ attribute: String, _ value: CFTypeRef) throws { try call("set \(attribute)") { AXUIElementSetAttributeValue(raw, attribute as CFString, value) } } func action(_ action: String) throws { try call(action) { AXUIElementPerformAction(raw, action as CFString) } } }