import CoreGraphics import Foundation public actor SpaceController { public struct SwitchPreparation: Equatable, Sendable { public let displayID: String public let source: UInt64 public let destination: UInt64 public init(displayID: String, source: UInt64, destination: UInt64) { self.displayID = displayID self.source = source self.destination = destination } } private let reader: any SpaceReading private let hotKeys: any SpaceHotKeyReading private let poster: any SpaceEventPosting private let wait: @Sendable (Duration) async throws -> Void private var current: [String: UInt64] = [:] private var previous: [String: UInt64] = [:] private var running = false public init( reader: any SpaceReading, hotKeys: any SpaceHotKeyReading = SystemSpaceHotKeys(), poster: any SpaceEventPosting = SystemSpaceEventPoster(), wait: @escaping @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) } ) { self.reader = reader self.hotKeys = hotKeys self.poster = poster self.wait = wait } public func snapshot() async throws -> [NativeDisplaySpaces] { let snapshot = try await reader.snapshot() try observe(snapshot) return snapshot } public func observe(_ snapshot: [NativeDisplaySpaces]) throws { var displayIDs: Set = [] var spaceIDs: Set = [] var numbers: Set = [] for display in snapshot { guard !display.displayID.isEmpty, displayIDs.insert(display.displayID).inserted, display.spaces.contains(where: { $0.id == display.currentSpace }) else { throw SpaceCommandError.malformedSnapshot } for space in display.spaces { guard space.id != 0, spaceIDs.insert(space.id).inserted else { throw SpaceCommandError.malformedSnapshot } guard space.kind != .desktop || space.desktopNumber != nil else { throw SpaceCommandError.malformedSnapshot } if let number = space.desktopNumber { guard space.kind == .desktop, number > 0, numbers.insert(number).inserted else { throw SpaceCommandError.malformedSnapshot } } } } for display in snapshot { if let old = current[display.displayID], old != display.currentSpace { previous[display.displayID] = old } current[display.displayID] = display.currentSpace if !display.spaces.contains(where: { $0.id == previous[display.displayID] }) { previous.removeValue(forKey: display.displayID) } } current = current.filter { displayIDs.contains($0.key) } previous = previous.filter { displayIDs.contains($0.key) } } public func execute( _ destination: SpaceDestination, displayID: String, window: SpaceDragWindow? = nil, follow: Bool = true, prepareSwitch: (@Sendable (SwitchPreparation) async throws -> Void)? = nil ) async throws -> SpaceCommandResult { guard !running else { throw SpaceCommandError.busy } running = true defer { running = false } try Task.checkCancellation() let displays = try await snapshot() guard let display = displays.first(where: { $0.displayID.caseInsensitiveCompare(displayID) == .orderedSame }) ?? (displays.count == 1 && displays.first?.displayID == "Main" ? displays.first : nil), let source = display.spaces.first(where: { $0.id == display.currentSpace }) else { throw SpaceCommandError.displayUnavailable } let (target, action) = try resolve(destination, display: display) if let window { guard !window.isFullscreen, source.kind == .desktop, target.kind == .desktop else { throw SpaceCommandError.fullscreen } guard try await !reader.stageManagerEnabled() else { throw SpaceCommandError.stageManager } guard window.id != 0, try await reader.spaces(for: window.id) == [source.id] else { throw SpaceCommandError.windowUnavailable } } guard source.id != target.id else { return SpaceCommandResult( displayID: display.displayID, source: source.id, destination: target.id, followed: window == nil || follow, verificationSamples: 0) } let entries = try hotKeys.read() let key = try shortcut(action, entries: entries) let returnKey: HotKey? if window != nil && !follow { guard let number = source.desktopNumber else { throw SpaceCommandError.returnNotVerified } returnKey = try shortcut(.desktop(number), entries: entries) } else { returnKey = nil } try poster.prepare() var samples = 0 if let window { try await move( window, key: key, display: display, target: target, prepareSwitch: prepareSwitch, samples: &samples) } else { try await prepare( SwitchPreparation(displayID: display.displayID, source: source.id, destination: target.id), using: prepareSwitch) try poster.hotKey(key) guard try await verifyCurrent(target.id, displayID: display.displayID, samples: &samples) else { throw SpaceCommandError.switchNotVerified } } if let returnKey { try await prepare( SwitchPreparation(displayID: display.displayID, source: target.id, destination: source.id), using: prepareSwitch) try poster.hotKey(returnKey) guard try await verifyCurrent(source.id, displayID: display.displayID, samples: &samples) else { throw SpaceCommandError.returnNotVerified } } return SpaceCommandResult( displayID: display.displayID, source: source.id, destination: target.id, followed: window == nil || follow, verificationSamples: samples) } private func resolve( _ destination: SpaceDestination, display: NativeDisplaySpaces ) throws -> (NativeSpace, SpaceShortcutAction) { switch destination { case .desktop(let number): guard (1...16).contains(number), let space = display.spaces.first(where: { $0.desktopNumber == number }) else { throw SpaceCommandError.desktopUnavailable(number) } return (space, .desktop(number)) case .backAndForth: guard let id = previous[display.displayID], let space = display.spaces.first(where: { $0.id == id }), let number = space.desktopNumber else { throw SpaceCommandError.noPreviousSpace } return (space, .desktop(number)) case .next, .previous: guard let index = display.spaces.firstIndex(where: { $0.id == display.currentSpace }) else { throw SpaceCommandError.displayUnavailable } let target = index + (destination == .next ? 1 : -1) guard display.spaces.indices.contains(target) else { throw SpaceCommandError.noAdjacentSpace } return (display.spaces[target], destination == .next ? .moveRight : .moveLeft) } } private func shortcut(_ action: SpaceShortcutAction, entries: [SymbolicHotKey]) throws -> HotKey { let shortcut = SymbolicHotKeys.spaceShortcut(action, in: entries) guard shortcut.isEnabled else { throw SpaceCommandError.shortcutDisabled(action) } guard let key = shortcut.hotKey else { throw SpaceCommandError.shortcutUnbound(action) } return key } private func prepare( _ preparation: SwitchPreparation, using callback: (@Sendable (SwitchPreparation) async throws -> Void)? ) async throws { try Task.checkCancellation() if let callback { try await callback(preparation) } try Task.checkCancellation() } private func move( _ window: SpaceDragWindow, key: HotKey, display: NativeDisplaySpaces, target: NativeSpace, prepareSwitch: (@Sendable (SwitchPreparation) async throws -> Void)?, samples: inout Int ) async throws { let bar = window.titleBar guard !bar.isNull, !bar.isInfinite, bar.width >= 8, bar.height >= 4, bar.origin.x.isFinite, bar.origin.y.isFinite else { throw SpaceCommandError.titleBarUnavailable } let origin = CGPoint(x: bar.midX, y: bar.midY) let pickup = CGPoint(x: origin.x + 4, y: origin.y) let before = try poster.windowFrame(window.id) guard before.contains(origin), before.contains(pickup) else { throw SpaceCommandError.titleBarUnavailable } try poster.validateTarget(window.id, at: origin) try await prepare( SwitchPreparation(displayID: display.displayID, source: display.currentSpace, destination: target.id), using: prepareSwitch) guard try poster.windowFrame(window.id) == before else { throw SpaceCommandError.windowUnavailable } try poster.validateTarget(window.id, at: origin) try poster.prepare() let originalCursor = try poster.cursorPosition() var held = false do { try Task.checkCancellation() try poster.mouse(.down(origin)) held = true try await wait(.milliseconds(80)) try Task.checkCancellation() try poster.mouse(.drag(pickup)) try await wait(.milliseconds(80)) try Task.checkCancellation() let pickedUp = try poster.windowFrame(window.id) guard abs(pickedUp.minX - before.minX - 4) <= 1, abs(pickedUp.minY - before.minY) <= 1, pickedUp.size == before.size else { throw SpaceCommandError.dragNotVerified } try poster.hotKey(key) guard try await verifyCurrent(target.id, displayID: display.displayID, samples: &samples) else { throw SpaceCommandError.switchNotVerified } try Task.checkCancellation() try poster.mouse(.drag(origin)) try poster.mouse(.up(origin)) held = false guard try await verifyMembership(window.id, target: target.id, samples: &samples) else { throw SpaceCommandError.moveNotVerified } } catch { var failures: [String] = [] if held { do { try poster.mouse(.drag(origin)) } catch { failures.append(String(describing: error)) } do { try poster.mouse(.up(origin)) } catch { failures.append(String(describing: error)) } } do { try poster.restoreCursor(originalCursor) } catch { failures.append(String(describing: error)) } if !failures.isEmpty { throw SpaceCommandError.cleanupFailed( operation: String(describing: error), cleanup: failures.joined(separator: "; ")) } throw error } try poster.restoreCursor(originalCursor) } private func verifyCurrent(_ id: UInt64, displayID: String, samples: inout Int) async throws -> Bool { // The system owns the transition animation; wait for two matching readbacks, not a guessed delay. var consecutive = 0 for _ in 0..<40 { try await wait(.milliseconds(50)) try Task.checkCancellation() let displays = try await snapshot() try Task.checkCancellation() samples += 1 if displays.first(where: { $0.displayID == displayID })?.currentSpace == id { consecutive += 1 if consecutive == 2 { return true } } else { consecutive = 0 } } return false } private func verifyMembership(_ window: CGWindowID, target: UInt64, samples: inout Int) async throws -> Bool { for _ in 0..<40 { try await wait(.milliseconds(50)) try Task.checkCancellation() samples += 1 let membership = try await reader.spaces(for: window) try Task.checkCancellation() if membership == [target] { return true } } return false } }