Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534import ApplicationServicesimport CPrivateAPIimport CoreGraphicsimport Darwinimport Foundationimport RealityDriverSupportimport 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<DriverAXApplication, DriverError>) -> 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<Value: Sendable>( _ operation: @escaping @Sendable (DriverAXApplication) throws -> Value ) throws -> Value { precondition(!Thread.isMainThread, "The main thread must not wait for AX") let result = Mutex<Result<Value, DriverError>?>(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<Value, DriverError> 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<DriverAXApplication, DriverError> 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<UInt32>) 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<T: AnyObject>(_ value: CFTypeRef, type: CFTypeID, attribute: String) throws -> T { guard CFGetTypeID(value) == type else { throw DriverAXError.malformed(attribute) } return Unmanaged<T>.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..<count).map { index in guard let pointer = CFArrayGetValueAtIndex(array, index) else { throw DriverAXError.malformed(attribute) } let object = Unmanaged<CFTypeRef>.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) } }}