import Foundation import ApplicationServices import CoreGraphics // PrivateAPI loads all private symbols at runtime with dlsym. If a symbol is // missing, the loader logs the problem and the feature is disabled. The app // never crashes because of a missing private symbol (spec section 7.5). // // Signature sources: // - _AXUIElementGetWindow: AltTab (PrivateApis.swift), yabai. // - CGSMainConnectionID: common CGS use (yabai, Hammerspoon). // - CGSCopyManagedDisplaySpaces: yabai, AltTab. // - CGSCopySpacesForWindows: AltTab, yabai. // - _AXUIElementCreateWithRemoteToken: AltTab. // // UNCERTAIN: The remote-token layout for _AXUIElementCreateWithRemoteToken is // not documented. The layout below follows AltTab. The constraint and the // cross-Space activation have a fallback if this call returns nil. // // PrivateAPI is nonisolated. The stored function pointers are immutable (let). // The caller runs the AX wrappers on the serial AX queue (spec sections 7.4, // 7.15). The CGS wrappers are also safe off the main thread. final class PrivateAPI { static let shared = PrivateAPI() // Function pointer typealiases (C calling convention). private typealias GetWindowFn = @convention(c) (AXUIElement, UnsafeMutablePointer) -> AXError private typealias MainConnFn = @convention(c) () -> Int32 private typealias CopyManagedDisplaySpacesFn = @convention(c) (Int32) -> Unmanaged? private typealias CopySpacesForWindowsFn = @convention(c) (Int32, Int32, CFArray) -> Unmanaged? private typealias CreateWithRemoteTokenFn = @convention(c) (CFData) -> Unmanaged? private let getWindowFn: GetWindowFn? private let mainConnFn: MainConnFn? private let copyManagedDisplaySpacesFn: CopyManagedDisplaySpacesFn? private let copySpacesForWindowsFn: CopySpacesForWindowsFn? private let createWithRemoteTokenFn: CreateWithRemoteTokenFn? // spacesAvailable is true if the Space symbols loaded. let spacesAvailable: Bool private init() { // SkyLight holds the CGS symbols on current macOS. The AX symbols live // in ApplicationServices (already loaded). RTLD_DEFAULT finds a symbol // in any loaded image. The loader opens SkyLight as a fallback. let skyLight = dlopen( "/System/Library/PrivateFrameworks/SkyLight.framework/SkyLight", RTLD_NOW) func load(_ name: String, _ type: T.Type) -> T? { // PRIVATE API var pointer = dlsym(UnsafeMutableRawPointer(bitPattern: -2), name) // RTLD_DEFAULT if pointer == nil, let skyLight = skyLight { pointer = dlsym(skyLight, name) } guard let pointer = pointer else { Log.privateAPI.error("Private symbol missing: \(name, privacy: .public)") return nil } return unsafeBitCast(pointer, to: T.self) } getWindowFn = load("_AXUIElementGetWindow", GetWindowFn.self) mainConnFn = load("CGSMainConnectionID", MainConnFn.self) copyManagedDisplaySpacesFn = load("CGSCopyManagedDisplaySpaces", CopyManagedDisplaySpacesFn.self) copySpacesForWindowsFn = load("CGSCopySpacesForWindows", CopySpacesForWindowsFn.self) createWithRemoteTokenFn = load("_AXUIElementCreateWithRemoteToken", CreateWithRemoteTokenFn.self) spacesAvailable = mainConnFn != nil && copySpacesForWindowsFn != nil } // windowID returns the CGWindowID of an AX window element. // Fallback if missing: the caller matches by PID, frame, and title. func windowID(for element: AXUIElement) -> CGWindowID? { guard let getWindowFn = getWindowFn else { return nil } var id: CGWindowID = 0 let error = getWindowFn(element, &id) // PRIVATE API if error != .success { return nil } return id } // mainConnectionID returns the CGS connection ID for this process. func mainConnectionID() -> Int32? { guard let mainConnFn = mainConnFn else { return nil } return mainConnFn() // PRIVATE API } // managedDisplaySpaces returns the raw Space list per display. The caller // parses the dictionaries. Fallback if missing: nil (treat all windows as // current Space). func managedDisplaySpaces() -> [[String: Any]]? { guard let copyFn = copyManagedDisplaySpacesFn, let cid = mainConnectionID() else { return nil } guard let array = copyFn(cid)?.takeRetainedValue() as? [[String: Any]] else { // PRIVATE API return nil } return array } // spaces returns the Space IDs for the given window IDs. The mask 7 selects // all Space types. Fallback if missing: nil. func spaces(forWindows windowIDs: [CGWindowID]) -> [UInt64]? { guard let copyFn = copySpacesForWindowsFn, let cid = mainConnectionID() else { return nil } let numbers = windowIDs.map { NSNumber(value: $0) } as CFArray let mask: Int32 = 7 // kCGSAllSpacesMask (all Space types) guard let result = copyFn(cid, mask, numbers)?.takeRetainedValue() as? [NSNumber] else { // PRIVATE API return nil } return result.map { $0.uint64Value } } // remoteElement returns an AX element for a window on another Space. The // function builds the remote token from the PID and the window ID. The // layout follows AltTab. Fallback if missing or nil: activate the // application only (spec section 7.6, Method B). func remoteElement(pid: pid_t, windowID: CGWindowID) -> AXUIElement? { guard let createFn = createWithRemoteTokenFn else { return nil } // UNCERTAIN LAYOUT (source: AltTab). The token is 20 bytes: // - bytes 0..<4: pid (little endian Int32) // - bytes 4..<8: 0 // - bytes 8..<12: magic 'coco' (0x636f636f) // - bytes 12..<20: window ID (UInt64 little endian) var token = Data(count: 20) token.withUnsafeMutableBytes { raw in let base = raw.baseAddress! base.storeBytes(of: Int32(pid).littleEndian, toByteOffset: 0, as: Int32.self) base.storeBytes(of: Int32(0).littleEndian, toByteOffset: 4, as: Int32.self) base.storeBytes(of: UInt32(0x636f636f).littleEndian, toByteOffset: 8, as: UInt32.self) base.storeBytes(of: UInt64(windowID).littleEndian, toByteOffset: 12, as: UInt64.self) } guard let element = createFn(token as CFData)?.takeRetainedValue() else { // PRIVATE API return nil } return element } }