Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320import CoreFoundationpublic import CoreGraphicsimport Darwinimport Foundation
public struct WindowServer: Sendable { public struct Window: Equatable, Sendable { public let number: CGWindowID public let pid: pid_t public let bounds: CGRect public let layer: Int32 public let isOnscreen: Bool }
public struct DisplaySpaces: Equatable, Sendable { public let displayID: String public let spaces: [UInt64] }
public struct Capabilities: Equatable, Sendable { public let mainConnection: Bool public let managedDisplaySpaces: Bool public let currentSpace: Bool public let windowListBrightness: Bool public let brightnessConnection: Bool public let axWindowID: Bool
public var canReadDisplaySpaces: Bool { mainConnection && managedDisplaySpaces } public var canReadCurrentSpace: Bool { mainConnection && currentSpace } public var experimentalBrightness: Bool { brightnessConnection && windowListBrightness }
init(probe: (String) -> Bool) { mainConnection = probe("SLSMainConnectionID") brightnessConnection = mainConnection || probe("CGSMainConnectionID") managedDisplaySpaces = probe("SLSCopyManagedDisplaySpaces") currentSpace = probe("SLSManagedDisplayGetCurrentSpace") windowListBrightness = probe("CGSSetWindowListBrightness") axWindowID = probe("_AXUIElementGetWindow") } }
public enum DataProblem: Equatable, Sendable { case missing case malformed }
public enum ReadError: Error, Equatable, Sendable, CustomStringConvertible { case windowListUnavailable case malformedWindowList case displaySpacesUnavailable case malformedDisplaySpacesList case symbolUnavailable(String) case currentSpaceUnavailable(displayID: String) case invalidWindow(index: Int, field: String, problem: DataProblem) case invalidDisplaySpaces(index: Int, field: String, problem: DataProblem)
public var description: String { switch self { case .windowListUnavailable: return "The window server did not return a window list." case .malformedWindowList: return "The window server returned a malformed window list." case .displaySpacesUnavailable: return "The window server did not return display spaces." case .malformedDisplaySpacesList: return "The window server returned a malformed display spaces list." case .symbolUnavailable(let symbol): return "The window server symbol \(symbol) is unavailable." case .currentSpaceUnavailable(let displayID): return "The current space is unavailable for display \(displayID)." case .invalidWindow(let index, let field, let problem): return "Window \(index) has \(problem) data for \(field)." case .invalidDisplaySpaces(let index, let field, let problem): return "Display spaces entry \(index) has \(problem) data for \(field)." } } }
public init() {}
public var capabilities: Capabilities { RuntimeSymbols.shared.capabilities }
/// Includes offscreen windows, but not zero-area placeholders or non-document layers. package static func windowOwners(_ windows: [Window]) -> Set<Int32> { Set(windows.filter { $0.layer == 0 && $0.bounds.width > 0 && $0.bounds.height > 0 }.map(\.pid)) }
public func windows( options: CGWindowListOption = .optionAll, relativeTo: CGWindowID = kCGNullWindowID ) throws -> [Window] { let interval = ParcelSignposts.beginIfEnabled(.windowListRead) var count: UInt64 = 0 var outcome: UInt64 = 1 defer { ParcelSignposts.endIfStarted(.windowListRead, interval, value: count, detail: outcome) } guard let records = CGWindowListCopyWindowInfo(options, relativeTo) else { throw ReadError.windowListUnavailable } guard CFGetTypeID(records) == CFArrayGetTypeID() else { throw ReadError.malformedWindowList } let windows = try Self.decodeWindows(records as NSArray) count = UInt64(windows.count) outcome = 0 return windows }
@concurrent package func frameReadbackWindows( windowID: CGWindowID, read: @Sendable (CGWindowListOption, CGWindowID) throws -> [Window] = { options, id in try WindowServer().windows(options: options, relativeTo: id) } ) async throws -> [Window] { try Task.checkCancellation() return try read(.optionIncludingWindow, windowID) }
public func isOnScreen(windowID: CGWindowID) throws -> Bool { try Self.isOnScreen(windowID: windowID) { options, id in try windows(options: options, relativeTo: id) } }
static func isOnScreen( windowID: CGWindowID, read: (CGWindowListOption, CGWindowID) throws -> [Window] ) throws -> Bool { precondition(windowID != kCGNullWindowID) let windows = try read(.optionIncludingWindow, windowID) guard windows.count <= 1, windows.allSatisfy({ $0.number == windowID }) else { throw ReadError.malformedWindowList } return windows.first?.isOnscreen ?? false }
public func displaySpaces() throws -> [DisplaySpaces] { let interval = ParcelSignposts.beginIfEnabled(.spaceRead, detail: 0) defer { ParcelSignposts.endIfStarted(.spaceRead, interval) } let symbols = RuntimeSymbols.shared guard let connectionPointer = symbols.mainConnection else { throw ReadError.symbolUnavailable("SLSMainConnectionID") } guard let spacesPointer = symbols.managedDisplaySpaces else { throw ReadError.symbolUnavailable("SLSCopyManagedDisplaySpaces") } let connection = unsafeBitCast(connectionPointer, to: MainConnection.self) let copySpaces = unsafeBitCast(spacesPointer, to: CopyManagedDisplaySpaces.self) guard let records = copySpaces(connection())?.takeRetainedValue() else { throw ReadError.displaySpacesUnavailable } guard CFGetTypeID(records) == CFArrayGetTypeID() else { throw ReadError.malformedDisplaySpacesList } return try Self.decodeDisplaySpaces(records as NSArray) }
public func currentSpace(displayID: String) throws -> UInt64 { let interval = ParcelSignposts.beginIfEnabled(.spaceRead, detail: 1) defer { ParcelSignposts.endIfStarted(.spaceRead, interval) } guard !displayID.isEmpty else { throw ReadError.currentSpaceUnavailable(displayID: displayID) } let symbols = RuntimeSymbols.shared guard let connectionPointer = symbols.mainConnection else { throw ReadError.symbolUnavailable("SLSMainConnectionID") } guard let spacePointer = symbols.currentSpace else { throw ReadError.symbolUnavailable("SLSManagedDisplayGetCurrentSpace") } let connection = unsafeBitCast(connectionPointer, to: MainConnection.self) let getCurrentSpace = unsafeBitCast(spacePointer, to: GetCurrentSpace.self) let space = getCurrentSpace(connection(), displayID as CFString) guard space != 0 else { throw ReadError.currentSpaceUnavailable(displayID: displayID) } return space }
static func decodeWindows(_ value: Any) throws -> [Window] { guard let records = value as? [Any] else { throw ReadError.malformedWindowList } return try records.enumerated().map { index, record in func error(_ field: String, _ problem: DataProblem) -> ReadError { .invalidWindow(index: index, field: field, problem: problem) } guard let fields = record as? [String: Any] else { throw error("record", .malformed) } func required(_ key: String) throws -> Any { guard let value = fields[key] else { throw error(key, .missing) } return value } let numberKey = kCGWindowNumber as String let pidKey = kCGWindowOwnerPID as String let boundsKey = kCGWindowBounds as String let layerKey = kCGWindowLayer as String let onscreenKey = kCGWindowIsOnscreen as String
guard let number = unsignedInteger(try required(numberKey), as: UInt32.self), number != 0 else { throw error(numberKey, .malformed) } guard let pid = signedInteger(try required(pidKey), as: Int32.self), pid >= 0 else { throw error(pidKey, .malformed) } guard let layer = signedInteger(try required(layerKey), as: Int32.self) else { throw error(layerKey, .malformed) } guard let boundsFields = try required(boundsKey) as? [String: Any] else { throw error(boundsKey, .malformed) } func coordinate(_ key: String) throws -> Double { guard let value = boundsFields[key] else { throw error("\(boundsKey).\(key)", .missing) } guard let number = numericValue(value), number.doubleValue.isFinite else { throw error("\(boundsKey).\(key)", .malformed) } return number.doubleValue } let originX = try coordinate("X") let originY = try coordinate("Y") let width = try coordinate("Width") let height = try coordinate("Height") guard width >= 0, height >= 0 else { throw error(boundsKey, .malformed) } let onscreen: Bool if let value = fields[onscreenKey] { guard let boolean = value as? NSNumber, CFGetTypeID(boolean) == CFBooleanGetTypeID() else { throw error(onscreenKey, .malformed) } onscreen = boolean.boolValue } else { // Core Graphics omits this key for windows not ordered onscreen. onscreen = false } return Window( number: number, pid: pid, bounds: CGRect(x: originX, y: originY, width: width, height: height), layer: layer, isOnscreen: onscreen ) } }
static func decodeDisplaySpaces(_ value: Any) throws -> [DisplaySpaces] { guard let records = value as? [Any] else { throw ReadError.malformedDisplaySpacesList } return try records.enumerated().map { index, record in func error(_ field: String, _ problem: DataProblem) -> ReadError { .invalidDisplaySpaces(index: index, field: field, problem: problem) } guard let fields = record as? [String: Any] else { throw error("record", .malformed) } guard let rawDisplayID = fields["Display Identifier"] else { throw error("Display Identifier", .missing) } guard let displayID = rawDisplayID as? String, !displayID.isEmpty else { throw error("Display Identifier", .malformed) } guard let rawSpaces = fields["Spaces"] else { throw error("Spaces", .missing) } guard let spaces = rawSpaces as? [Any] else { throw error("Spaces", .malformed) } let identifiers: [UInt64] = try spaces.enumerated().map { spaceIndex, space in let field = "Spaces[\(spaceIndex)].ManagedSpaceID" guard let entry = space as? [String: Any] else { throw error("Spaces[\(spaceIndex)]", .malformed) } guard let rawID = entry["ManagedSpaceID"] else { throw error(field, .missing) } guard let identifier = unsignedInteger(rawID, as: UInt64.self), identifier != 0 else { throw error(field, .malformed) } return identifier } return DisplaySpaces(displayID: displayID, spaces: identifiers) } }}
private func numericValue(_ value: Any) -> NSNumber? { guard let number = value as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID() else { return nil } return number}
private func signedInteger<T: FixedWidthInteger & SignedInteger>(_ value: Any, as: T.Type) -> T? { guard let number = numericValue(value) else { return nil } return T(number.stringValue)}
private func unsignedInteger<T: FixedWidthInteger & UnsignedInteger>(_ value: Any, as: T.Type) -> T? { guard let number = numericValue(value) else { return nil } return T(number.stringValue)}
private typealias MainConnection = @convention(c) () -> UInt32private typealias CopyManagedDisplaySpaces = @convention(c) (UInt32) -> Unmanaged<CFArray>?private typealias GetCurrentSpace = @convention(c) (UInt32, CFString) -> UInt64
private final class RuntimeSymbols: @unchecked Sendable { static let shared = RuntimeSymbols()
let mainConnection: UnsafeMutableRawPointer? let managedDisplaySpaces: UnsafeMutableRawPointer? let currentSpace: UnsafeMutableRawPointer? let capabilities: WindowServer.Capabilities
private init() { // Keep handles open for the lifetime of the function pointers. let skyLight = dlopen("/System/Library/PrivateFrameworks/SkyLight.framework/SkyLight", RTLD_LAZY | RTLD_LOCAL) func lookup(_ handle: UnsafeMutableRawPointer?, _ name: String) -> UnsafeMutableRawPointer? { guard let handle else { return nil } return dlsym(handle, name) } let connection = lookup(skyLight, "SLSMainConnectionID") let brightnessConnection = lookup(skyLight, "CGSMainConnectionID") let spaces = lookup(skyLight, "SLSCopyManagedDisplaySpaces") let current = lookup(skyLight, "SLSManagedDisplayGetCurrentSpace") let brightness = lookup(skyLight, "CGSSetWindowListBrightness") let axWindowID = dlsym(UnsafeMutableRawPointer(bitPattern: -2), "_AXUIElementGetWindow") mainConnection = connection managedDisplaySpaces = spaces currentSpace = current capabilities = WindowServer.Capabilities { name in switch name { case "SLSMainConnectionID": connection != nil case "CGSMainConnectionID": brightnessConnection != nil case "SLSCopyManagedDisplaySpaces": spaces != nil case "SLSManagedDisplayGetCurrentSpace": current != nil case "CGSSetWindowListBrightness": brightness != nil case "_AXUIElementGetWindow": axWindowID != nil default: false } } }}