Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536public import ApplicationServicesimport CPrivateAPIpublic import CoreGraphicsimport Darwinimport Foundationimport ParcelCoreimport Synchronization
public enum AXPlatformError: Error, Equatable, Sendable { case notPermitted case timedOut case messagingFailure case attributeUnsupported case elementInvalid case noValue case unexpectedValue(String) case unavailable(String) case other(Int32)
public init(_ error: AXError) { switch error { case .apiDisabled: self = .notPermitted case .cannotComplete: self = .messagingFailure case .attributeUnsupported: self = .attributeUnsupported case .invalidUIElement: self = .elementInvalid case .noValue: self = .noValue default: self = .other(error.rawValue) } }}
func checkAX(_ error: AXError) throws { guard error == .success else { throw AXPlatformError(error) }}
final class AXCallWatchdog: Sendable { typealias Cancellation = @Sendable () -> Void
private struct State { var next: UInt64 = 0 var active: UInt64? var cancellation: Cancellation? var stopped = false } private let state = Mutex(State()) private let schedule: @Sendable (@escaping @Sendable () -> Void) -> Cancellation private let overdue: @Sendable () -> Void
convenience init( deadline: Double, queue: DispatchQueue = .global(qos: .utility), overdue: @escaping @Sendable () -> Void ) { precondition(deadline.isFinite && deadline > 0) self.init( schedule: { action in let timer = AXWatchdogDeadline(deadline: deadline, queue: queue, action: action) return { timer.cancel() } }, overdue: overdue) }
init( schedule: @escaping @Sendable (@escaping @Sendable () -> Void) -> Cancellation, overdue: @escaping @Sendable () -> Void ) { self.schedule = schedule self.overdue = overdue }
func begin() -> UInt64 { let (token, previous, stopped) = state.withLock { state in state.next &+= 1 let previous = state.cancellation state.cancellation = nil state.active = state.stopped ? nil : state.next return (state.next, previous, state.stopped) } previous?() guard !stopped else { return token } let cancellation = schedule { [weak self] in self?.expire(token) } let installed = state.withLock { state in guard state.active == token else { return false } state.cancellation = cancellation return true } if !installed { cancellation() } return token }
func end(_ token: UInt64) { let cancellation = state.withLock { state -> Cancellation? in guard state.active == token else { return nil } state.active = nil let cancellation = state.cancellation state.cancellation = nil return cancellation } cancellation?() }
func stop() { let cancellation = state.withLock { state -> Cancellation? in state.stopped = true state.active = nil let cancellation = state.cancellation state.cancellation = nil return cancellation } cancellation?() }
private func expire(_ token: UInt64) { let (expired, cancellation) = state.withLock { state -> (Bool, Cancellation?) in guard state.active == token else { return (false, nil) } state.active = nil let cancellation = state.cancellation state.cancellation = nil return (true, cancellation) } cancellation?() if expired { overdue() } }
deinit { stop() }}
final class AXWatchdogDeadline: @unchecked Sendable { private let source: any DispatchSourceTimer
init(deadline: Double, queue: DispatchQueue, action: @escaping @Sendable () -> Void) { source = DispatchSource.makeTimerSource(queue: queue) source.setEventHandler(handler: action) source.schedule(deadline: .now() + deadline, repeating: .never) source.resume() }
func cancel() { source.cancel() }
deinit { source.cancel() }}
final class AXCallActivity { private(set) var results: [AXPlatformError?] = [] let validity: AppThreadOperationValidity?
init(validity: AppThreadOperationValidity? = nil) { self.validity = validity }
func record(_ error: AXPlatformError?) { results.append(error) }
func recordBatchFailure(_ error: AXPlatformError) { precondition(!results.isEmpty) results[results.count - 1] = error }}
enum AXAttributeArrayReader { static func read( name: String, limit: Int?, count: () throws -> Int, values: () throws -> CFArray ) throws -> CFArray { if let limit { precondition(limit >= 0) let count = try count() guard count >= 0 else { throw AXPlatformError.unexpectedValue(name) } guard count <= limit else { throw NativeTabScanError.limitExceeded } } let array = try values() if let limit, CFArrayGetCount(array) > limit { throw NativeTabScanError.limitExceeded } return array }}
struct AXAttributeValues { private let values: [String: CFTypeRef] private let errors: [String: AXPlatformError] let callFailure: AXPlatformError?
init(names: [String], values array: CFArray, elapsed: Double = 0, timeout: Float = 0.35) throws { guard CFArrayGetCount(array) == names.count, Set(names).count == names.count else { throw AXPlatformError.unexpectedValue("AX attribute batch count") } var values: [String: CFTypeRef] = [:] var errors: [String: AXPlatformError] = [:] var callFailure: AXPlatformError? for (index, name) in names.enumerated() { guard let pointer = CFArrayGetValueAtIndex(array, index) else { throw AXPlatformError.unexpectedValue(name) } let value = Unmanaged<CFTypeRef>.fromOpaque(pointer).takeUnretainedValue() values[name] = value if let error = try Self.error(value, name: name, elapsed: elapsed, timeout: timeout) { errors[name] = error if error != .attributeUnsupported && error != .noValue && callFailure == nil { callFailure = error } } } self.values = values self.errors = errors self.callFailure = callFailure }
func contains(_ name: String) -> Bool { values[name] != nil }
func value(_ name: String) throws -> CFTypeRef? { if let error = errors[name] { throw error } return values[name] }
private static func error( _ value: CFTypeRef, name: String, elapsed: Double, timeout: Float ) throws -> AXPlatformError? { if CFGetTypeID(value) == CFNullGetTypeID() { return .noValue } guard CFGetTypeID(value) == AXValueGetTypeID() else { return nil } let axValue = Unmanaged<AXValue>.fromOpaque(Unmanaged.passUnretained(value).toOpaque()).takeUnretainedValue() guard AXValueGetType(axValue) == .axError else { return nil } var error = AXError.success guard AXValueGetValue(axValue, .axError, &error), error != .success else { throw AXPlatformError.unexpectedValue(name) } do { try AXElement.checkCall(error, elapsed: elapsed, timeout: timeout) return nil } catch let error as AXPlatformError { return error } }}
public struct AXElement: NativeTabAccess { let raw: AXUIElement let timeout: Float private let activity: AXCallActivity? private let watchdog: AXCallWatchdog? private let cachedAttributes: AXAttributeValues?
init(applicationPID: pid_t, timeout: Float = 0.35, watchdog: AXCallWatchdog? = nil) throws { try self.init(raw: AXUIElementCreateApplication(applicationPID), timeout: timeout, watchdog: watchdog) }
init(raw: AXUIElement, timeout: Float = 0.35, watchdog: AXCallWatchdog? = nil) throws { guard timeout.isFinite, timeout > 0 else { throw AXPlatformError.other(AXError.illegalArgument.rawValue) } try checkAX(AXUIElementSetMessagingTimeout(raw, timeout)) self.raw = raw self.timeout = timeout self.activity = nil self.watchdog = watchdog self.cachedAttributes = nil }
private init( raw: AXUIElement, timeout: Float, activity: AXCallActivity?, watchdog: AXCallWatchdog?, cachedAttributes: AXAttributeValues? = nil ) { self.raw = raw self.timeout = timeout self.activity = activity self.watchdog = watchdog self.cachedAttributes = cachedAttributes }
var operationValidity: AppThreadOperationValidity? { activity?.validity }
func tracking(_ activity: AXCallActivity) -> AXElement { AXElement( raw: raw, timeout: timeout, activity: activity, watchdog: watchdog, cachedAttributes: cachedAttributes) }
func trackingCalls(of element: AXElement) -> AXElement { AXElement( raw: raw, timeout: timeout, activity: element.activity, watchdog: watchdog, cachedAttributes: cachedAttributes) }
// Attribute batches belong to one read snapshot, never to the worker's long-lived window cache. func cachingAttributes(_ names: [String]) throws -> AXElement { var array: CFArray? let start = DispatchTime.now().uptimeNanoseconds try callAX { AXUIElementCopyMultipleAttributeValues(raw, names as CFArray, [], &array) } guard let array else { throw AXPlatformError.noValue } let elapsed = Double(DispatchTime.now().uptimeNanoseconds - start) / 1_000_000_000 let values = try AXAttributeValues(names: names, values: array, elapsed: elapsed, timeout: timeout) if let error = values.callFailure { activity?.recordBatchFailure(error) } return AXElement(raw: raw, timeout: timeout, activity: activity, watchdog: watchdog, cachedAttributes: values) }
func withoutCallTracking() -> AXElement { AXElement(raw: raw, timeout: timeout, activity: nil, watchdog: watchdog) }
static func checkCall(_ error: AXError, elapsed: Double, timeout: Float) throws { // AX uses the same error for timeouts and immediate messaging failures. if error == .cannotComplete && elapsed >= Double(timeout) * 0.9 { throw AXPlatformError.timedOut } try checkAX(error) }
private func callAX(_ operation: () -> AXError) throws { try activity?.validity?.check() let token = watchdog?.begin() defer { if let token { watchdog?.end(token) } } let start = DispatchTime.now().uptimeNanoseconds let error = operation() try activity?.validity?.check() let elapsed = Double(DispatchTime.now().uptimeNanoseconds - start) / 1_000_000_000 do { try Self.checkCall(error, elapsed: elapsed, timeout: timeout) activity?.record(nil) } catch let error as AXPlatformError { activity?.record(error) throw error } }
private func value(_ name: String) throws -> CFTypeRef { if let value = try cachedAttributes?.value(name) { return value } var result: CFTypeRef? try callAX { AXUIElementCopyAttributeValue(raw, name as CFString, &result) } guard let result else { throw AXPlatformError.noValue } return result }
private func checkedCF<T: AnyObject>(_ result: CFTypeRef, type: CFTypeID, name: String) throws -> T { guard CFGetTypeID(result) == type else { throw AXPlatformError.unexpectedValue(name) } return Unmanaged<T>.fromOpaque(Unmanaged.passUnretained(result).toOpaque()).takeUnretainedValue() }
private func string(_ name: String) throws -> String { let result: CFString = try checkedCF(value(name), type: CFStringGetTypeID(), name: name) return result as String }
private func boolean(_ name: String) throws -> Bool { let result: CFBoolean = try checkedCF(value(name), type: CFBooleanGetTypeID(), name: name) return CFBooleanGetValue(result) }
private func point(_ name: String) throws -> CGPoint { let axValue: AXValue = try checkedCF(value(name), type: AXValueGetTypeID(), name: name) var point = CGPoint.zero guard AXValueGetType(axValue) == .cgPoint, AXValueGetValue(axValue, .cgPoint, &point) else { throw AXPlatformError.unexpectedValue(name) } return point }
private func sizeValue(_ name: String) throws -> CGSize { let axValue: AXValue = try checkedCF(value(name), type: AXValueGetTypeID(), name: name) var size = CGSize.zero guard AXValueGetType(axValue) == .cgSize, AXValueGetValue(axValue, .cgSize, &size) else { throw AXPlatformError.unexpectedValue(name) } return size }
private func element(_ name: String) throws -> AXElement { let result: AXUIElement = try checkedCF(value(name), type: AXUIElementGetTypeID(), name: name) let element = try AXElement(raw: result, timeout: timeout, watchdog: watchdog) return AXElement(raw: element.raw, timeout: timeout, activity: activity, watchdog: watchdog) }
func factString(_ name: String) throws -> String { try string(name) } func factBoolean(_ name: String) throws -> Bool { try boolean(name) } func factSize(_ name: String) throws -> CGSize { try sizeValue(name) } func factParentRole() throws -> String { try element(kAXParentAttribute).role }
func factParentWindow() throws -> WindowParentObservation { try WindowParentReader.read( window: self, parent: { node in try optionalWindowFact { try node.element(kAXParentAttribute) } }, containingWindow: { node in try optionalWindowFact { try node.element(kAXWindowAttribute) } }, role: { node in try optionalWindowFact { try node.role } }, same: { CFEqual($0.raw, $1.raw) }, identify: { node in try optionalWindowFact { try node.windowID() } }) }
func factElementPresent(_ name: String) throws -> Bool { let _: AXUIElement = try checkedCF(value(name), type: AXUIElementGetTypeID(), name: name) return true }
func factSizeSettable() throws -> Bool { var settable = DarwinBoolean(false) try callAX { AXUIElementIsAttributeSettable(raw, kAXSizeAttribute as CFString, &settable) } return settable.boolValue }
func factChildRoles() throws -> [String?] { try elements(kAXChildrenAttribute, limit: NativeTabChrome.elementLimit).map { child in try optionalWindowFact { try child.role } } }
func inventoryChildren() throws -> [AXElement] { try optionalWindowFact { try elements(kAXChildrenAttribute, limit: NativeTabChrome.elementLimit) } ?? [] }
func factNativeTabs() throws -> NativeTabObservation { try NativeTabChrome.scan(window: self) }
var nativeTabRole: String { get throws { try role } } var nativeTabTitle: String { get throws { try title } } var nativeTabFrame: CGRect { get throws { try frame } } func nativeTabElements(_ attribute: String, limit: Int) throws -> [AXElement] { try elements(attribute, limit: limit) } func nativeTabWindowID() throws -> WindowID { guard try role == kAXWindowRole else { throw AXPlatformError.attributeUnsupported } return WindowID(rawValue: try windowID()) }
private func elements(_ name: String, limit: Int? = nil) throws -> [AXElement] { let array = try AXAttributeArrayReader.read( name: name, limit: limit, count: { var count = 0 try callAX { AXUIElementGetAttributeValueCount(raw, name as CFString, &count) } return count }, values: { try checkedCF(value(name), type: CFArrayGetTypeID(), name: name) }) let count = CFArrayGetCount(array) return try (0..<count).map { index in guard let pointer = CFArrayGetValueAtIndex(array, index) else { throw AXPlatformError.unexpectedValue(name) } let object = Unmanaged<CFTypeRef>.fromOpaque(pointer).takeUnretainedValue() let rawChild: AXUIElement = try checkedCF(object, type: AXUIElementGetTypeID(), name: name) return try AXElement(raw: rawChild, timeout: timeout, watchdog: watchdog).trackingIfPresent(activity) } }
private func trackingIfPresent(_ activity: AXCallActivity?) -> AXElement { AXElement(raw: raw, timeout: timeout, activity: activity, watchdog: watchdog) }
private func set(_ name: String, value: CFTypeRef) throws { try callAX { AXUIElementSetAttributeValue(raw, name as CFString, value) } }
public var position: CGPoint { get throws { try point(kAXPositionAttribute) } } public var size: CGSize { get throws { try sizeValue(kAXSizeAttribute) } } public var frame: CGRect { get throws { try CGRect(origin: position, size: size) } } public var title: String { get throws { try string(kAXTitleAttribute) } } public var role: String { get throws { try string(kAXRoleAttribute) } } public var subrole: String { get throws { try string(kAXSubroleAttribute) } } public var edited: Bool { get throws { try boolean("AXEdited") } }
public func closeWindow() throws { let button = try element(kAXCloseButtonAttribute) guard try button.boolean(kAXEnabledAttribute) else { throw AXPlatformError.unavailable("AXCloseButton") } try button.callAX { AXUIElementPerformAction(button.raw, kAXPressAction as CFString) } }
public var minimized: Bool { get throws { try boolean(kAXMinimizedAttribute) } } public var fullscreen: Bool { get throws { try boolean("AXFullScreen") } } public var main: Bool { get throws { try boolean(kAXMainAttribute) } } public var focused: Bool { get throws { try boolean(kAXFocusedAttribute) } } public var enhancedUI: Bool { get throws { try boolean("AXEnhancedUserInterface") } } public var focusedWindow: AXElement { get throws { try element(kAXFocusedWindowAttribute) } } public var titleBarFrame: CGRect { get throws { try element("AXTitleUIElement").frame } }
func focusedWindowIDForCallback() throws -> CGWindowID? { try AppThreadFocusReader.read( focusedWindow: { let focused: AXUIElement = try checkedCF( value(kAXFocusedWindowAttribute), type: AXUIElementGetTypeID(), name: kAXFocusedWindowAttribute) // Child elements inherit the application's timeout; this hot read needs no timeout reset. return AXElement(raw: focused, timeout: timeout, activity: activity, watchdog: watchdog) }, identify: { try $0.windowID() }) }
public var windows: [AXElement] { get throws { let name = kAXWindowsAttribute let array: CFArray = try checkedCF(value(name), type: CFArrayGetTypeID(), name: name) return try (0..<CFArrayGetCount(array)).map { index in guard let pointer = CFArrayGetValueAtIndex(array, index) else { throw AXPlatformError.unexpectedValue(name) } let object = Unmanaged<CFTypeRef>.fromOpaque(pointer).takeUnretainedValue() let element: AXUIElement = try checkedCF(object, type: AXUIElementGetTypeID(), name: name) let wrapped = try AXElement(raw: element, timeout: timeout, watchdog: watchdog) return AXElement(raw: wrapped.raw, timeout: timeout, activity: activity, watchdog: watchdog) } } }
public func setPosition(_ point: CGPoint) throws { var point = point guard let result = AXValueCreate(.cgPoint, &point) else { throw AXPlatformError.unexpectedValue(kAXPositionAttribute) } try set(kAXPositionAttribute, value: result) }
public func setSize(_ size: CGSize) throws { var size = size guard let result = AXValueCreate(.cgSize, &size) else { throw AXPlatformError.unexpectedValue(kAXSizeAttribute) } try set(kAXSizeAttribute, value: result) }
public func setMinimized(_ value: Bool) throws { try set(kAXMinimizedAttribute, value: value ? kCFBooleanTrue : kCFBooleanFalse) } public func setFullscreen(_ value: Bool) throws { try set("AXFullScreen", value: value ? kCFBooleanTrue : kCFBooleanFalse) } public func setMain(_ value: Bool) throws { try set(kAXMainAttribute, value: value ? kCFBooleanTrue : kCFBooleanFalse) } public func setFocused(_ value: Bool) throws { try set(kAXFocusedAttribute, value: value ? kCFBooleanTrue : kCFBooleanFalse) } public func setEnhancedUI(_ value: Bool) throws { try set("AXEnhancedUserInterface", value: value ? kCFBooleanTrue : kCFBooleanFalse) AppThreadWriteTrace.toggled(value) } public func setTitle(_ value: String) throws { try set(kAXTitleAttribute, value: value as CFString) } public func setFocusedWindow(_ window: AXElement) throws { try set(kAXFocusedWindowAttribute, value: window.raw) } public func raise() throws { try callAX { AXUIElementPerformAction(raw, kAXRaiseAction as CFString) } }
public func windowID() throws -> CGWindowID { guard let symbol = dlsym(UnsafeMutableRawPointer(bitPattern: -2), "_AXUIElementGetWindow") else { throw AXPlatformError.unavailable("_AXUIElementGetWindow") } let getWindow = unsafeBitCast(symbol, to: ParcelAXGetWindowFunction.self) var window: CGWindowID = 0 try callAX { getWindow(raw, &window) } guard window != 0 else { throw AXPlatformError.noValue } return window }}