import Foundation import ParcelCore import ParcelPlatform struct RuleLayoutAssignment: Equatable { let workspace: WorkspaceKey let layout: Layout } struct RuleSpaceAssignment: Equatable { let display: DisplayID let desktop: Int } extension ParcelEngine { func scheduleRuleSpaceAssignments() { guard isRunning, writesPermitted, isAutomaticTilingEnabled, ruleSpaceOperation == nil, ruleSpaceRetry == nil, !spaceCommandRunning else { return } var pending: [(WindowID, RuleSpaceAssignment)] = [] for window in dirtyRuleSpaceWindows.sorted() { guard eligibleRuleSpaceWindows.contains(window), let assignment = currentRuleSpaceAssignment(for: window), attemptedRuleSpaces[window] != assignment, !ruleSpaceMoveHistory.contains(moveRecord(window, assignment: assignment)) else { dirtyRuleSpaceWindows.remove(window) continue } if canAssignRuleSpace(window, assignment: assignment) { pending.append((window, assignment)) } } guard !pending.isEmpty else { return } let generation = lifetime ruleSpaceOperation = Task { @MainActor [weak self] in guard let self else { return } defer { self.ruleSpaceOperation = nil self.scheduleRuleSpaceAssignments() } for (window, assignment) in pending { guard self.isRunning, self.lifetime == generation, !Task.isCancelled else { return } guard self.canAssignRuleSpace(window, assignment: assignment) else { continue } do { if try await self.assignRuleSpace(window, assignment: assignment, generation: generation) { self.attemptedRuleSpaces[window] = assignment self.dirtyRuleSpaceWindows.remove(window) try await self.persistRuleSpaceMove(window, assignment: assignment) } } catch is CancellationError { return } catch { guard self.isRunning, self.lifetime == generation else { return } if let failure = error as? SpaceCommandError, failure == .inputBusy || failure == .pointerBusy { self.ruleSpaceRetry = self.scheduler.schedule(after: 0.35) { [weak self] in self?.ruleSpaceRetry = nil self?.scheduleRuleSpaceAssignments() } return } guard self.canAssignRuleSpace(window, assignment: assignment) else { continue } self.attemptedRuleSpaces[window] = assignment self.dirtyRuleSpaceWindows.remove(window) let failure = self.spaceFailure(error) self.log.record(.internalFailure(failure)) self.onFailure?(failure) } } } } private func moveRecord(_ window: WindowID, assignment: RuleSpaceAssignment) -> RuleSpaceMoveRecord { let app = observations[window]?.window.app return RuleSpaceMoveRecord( window: window.rawValue, pid: app?.pid ?? 0, bundleID: app?.bundleID ?? "", display: assignment.display.rawValue, desktop: assignment.desktop) } private func persistRuleSpaceMove(_ window: WindowID, assignment: RuleSpaceAssignment) async throws { let record = moveRecord(window, assignment: assignment) guard !ruleSpaceMoveHistory.contains(record) else { return } let updated = ruleSpaceMoveHistory + [record] if let ruleSpaceMoveStore { try await Task.detached { try ruleSpaceMoveStore.save(updated) }.value } ruleSpaceMoveHistory = updated } private func currentRuleSpaceAssignment(for window: WindowID) -> RuleSpaceAssignment? { guard let observation = observations[window], snapshot.state.windows[window] != nil, let key = snapshot.state.workspace(containing: window) else { return nil } let classification = classify(observation.window) guard classification.disposition != .ignore, classification.moveToSpace, let desktop = classification.space else { return nil } if let requested = classification.display { guard let actual = snapshot.state.activeSpaces.keys.first(where: { $0.rawValue.caseInsensitiveCompare(requested.rawValue) == .orderedSame }), actual == key.display else { return nil } } return RuleSpaceAssignment(display: key.display, desktop: desktop) } private func canAssignRuleSpace(_ window: WindowID, assignment: RuleSpaceAssignment) -> Bool { isRunning && writesPermitted && eligibleRuleSpaceWindows.contains(window) && isAutomaticTilingEnabled && !suspendedDisplays.contains(assignment.display) && currentRuleSpaceAssignment(for: window) == assignment } private func assignRuleSpace(_ window: WindowID, assignment: RuleSpaceAssignment, generation: UInt64) async throws -> Bool { guard let spaceWorld else { throw SpaceCommandError.displayUnavailable } let native = try await spaceWorld.spaceSnapshot() try Task.checkCancellation() guard isRunning, lifetime == generation else { throw EngineError.stopped } guard canAssignRuleSpace(window, assignment: assignment) else { return false } guard let display = native.first(where: { $0.displayID.caseInsensitiveCompare(assignment.display.rawValue) == .orderedSame || (native.count == 1 && $0.displayID == "Main") }), let target = display.spaces.first(where: { $0.kind == .desktop && $0.desktopNumber == assignment.desktop }) else { throw SpaceCommandError.desktopUnavailable(assignment.desktop) } guard let current = snapshot.state.workspace(containing: window) else { return false } let destination = WorkspaceKey(display: assignment.display, space: SpaceID(rawValue: target.id)) guard current != destination else { return true } guard !spaceCommandRunning else { throw SpaceCommandError.busy } beginSpaceOperation() defer { endSpaceOperation() } let deadline = ContinuousClock.now.advanced(by: .milliseconds(750)) while !busyApps.isEmpty || focusOperations > 0 || !windowOperations.isEmpty { guard canAssignRuleSpace(window, assignment: assignment) else { return false } guard ContinuousClock.now < deadline else { throw SpaceCommandError.busy } try await Task.sleep(for: .milliseconds(10)) } try Task.checkCancellation() guard isRunning, lifetime == generation else { throw EngineError.stopped } guard canAssignRuleSpace(window, assignment: assignment) else { return false } let result = try await spaceWorld.executeSpaceCommand( .desktop(assignment.desktop), display: assignment.display, window: window, follow: false) guard result.displayID.caseInsensitiveCompare(display.displayID) == .orderedSame, result.destination == target.id, result.verificationSamples > 0, !result.followed else { throw SpaceCommandError.moveNotVerified } try Task.checkCancellation() guard isRunning, lifetime == generation else { throw EngineError.stopped } guard canAssignRuleSpace(window, assignment: assignment) else { world.reconcile(Set(snapshot.state.windows.values.map(\.app))) return false } if let observation = observations[window] { enqueue( .windowAppeared( observation.window, workspace: destination, frame: actualFrames[window] ?? observation.frame)) } if snapshot.focusedWindow == window { enqueue(.focusChanged(nil)) } world.reconcile(Set(snapshot.state.windows.values.map(\.app))) return true } }