import CoreFoundation public import CoreGraphics import Darwin import Foundation public struct NativeSpaceReader: SpaceReading { public init() {} public func snapshot() async throws -> [NativeDisplaySpaces] { try await Task.detached { try Self.readSnapshot() }.value } public func spaces(for window: CGWindowID) async throws -> [UInt64] { try await Task.detached { let interval = ParcelSignposts.beginIfEnabled(.spaceRead, detail: 2) defer { ParcelSignposts.endIfStarted(.spaceRead, interval) } let symbols = SpaceSymbols.shared let connection = try symbols.connection() let copy = try symbols.function("SLSCopySpacesForWindows", as: CopyWindowSpaces.self) guard let result = copy(connection, 7, [NSNumber(value: window)] as CFArray)?.takeRetainedValue() else { throw SpaceCommandError.windowUnavailable } let data = try PropertyListSerialization.data(fromPropertyList: result, format: .binary, options: 0) let ids = try PropertyListDecoder().decode([UInt64].self, from: data) guard ids.allSatisfy({ $0 != 0 }) else { throw SpaceCommandError.malformedSnapshot } return ids }.value } public func stageManagerEnabled() async throws -> Bool { try await Task.detached { guard let value = UserDefaults.standard.persistentDomain(forName: "com.apple.WindowManager")?[ "GloballyEnabled"] else { return false } guard let number = value as? NSNumber, CFGetTypeID(number) == CFBooleanGetTypeID() else { throw SpaceCommandError.malformedSnapshot } return number.boolValue }.value } private static func readSnapshot() throws -> [NativeDisplaySpaces] { let interval = ParcelSignposts.beginIfEnabled(.spaceRead, detail: 0) defer { ParcelSignposts.endIfStarted(.spaceRead, interval) } let symbols = SpaceSymbols.shared let connection = try symbols.connection() let copy = try symbols.function("SLSCopyManagedDisplaySpaces", as: CopyDisplaySpaces.self) guard let result = copy(connection)?.takeRetainedValue() else { throw SpaceCommandError.malformedSnapshot } let data = try PropertyListSerialization.data(fromPropertyList: result, format: .binary, options: 0) return try decode(data) } static func decode(_ data: Data) throws -> [NativeDisplaySpaces] { let records = try PropertyListDecoder().decode([DisplayRecord].self, from: data) var number = 0 return try records.map { display in let spaces = try display.spaces.map { space in guard let kind = SpaceKind(rawValue: space.type), space.id != 0 else { throw SpaceCommandError.malformedSnapshot } if kind == .desktop { number += 1 } return NativeSpace(id: space.id, kind: kind, desktopNumber: kind == .desktop ? number : nil) } guard !display.identifier.isEmpty, spaces.contains(where: { $0.id == display.current.id }) else { throw SpaceCommandError.malformedSnapshot } return NativeDisplaySpaces(displayID: display.identifier, currentSpace: display.current.id, spaces: spaces) } } } private struct DisplayRecord: Decodable { let identifier: String let current: SpaceRecord let spaces: [SpaceRecord] enum CodingKeys: String, CodingKey { case identifier = "Display Identifier" case current = "Current Space" case spaces = "Spaces" } } private struct SpaceRecord: Decodable { let id: UInt64 let type: Int enum CodingKeys: String, CodingKey { case id = "ManagedSpaceID" case type } } private typealias Connection = @convention(c) () -> UInt32 private typealias CopyDisplaySpaces = @convention(c) (UInt32) -> Unmanaged? private typealias CopyWindowSpaces = @convention(c) (UInt32, Int32, CFArray) -> Unmanaged? private final class SpaceSymbols: @unchecked Sendable { static let shared = SpaceSymbols() private let handle: UnsafeMutableRawPointer? private init() { handle = dlopen("/System/Library/PrivateFrameworks/SkyLight.framework/SkyLight", RTLD_LAZY | RTLD_LOCAL) } func function(_ name: String, as type: T.Type) throws -> T { guard let handle, let symbol = dlsym(handle, name) else { throw SpaceCommandError.symbolUnavailable(name) } return unsafeBitCast(symbol, to: type) } func connection() throws -> UInt32 { let get = try function("SLSMainConnectionID", as: Connection.self) return get() } }