import Foundation public import ParcelCore import os public enum EngineWorkspaceFailure: Error, Sendable, Equatable { case workspaceUnavailable case automaticTilingDisabled case systemConflict case busy case unsettled([WindowID]) } public struct EngineWorkspaceRestorePoint: Sendable { public let workspace: WorkspaceKey public let isAutomaticTilingEnabled: Bool fileprivate let owner: UUID fileprivate let lifetime: UInt64 fileprivate let model: Workspace fileprivate let modes: FocusModes fileprivate let windows: [WindowID: ManagedWindow] fileprivate let frames: [WindowID: Rect] fileprivate let writeAttempts: [WindowID: UInt64] } extension ParcelEngine { public func workspacePlacementTargets(in key: WorkspaceKey) -> [WindowID: Rect] { Dictionary( uniqueKeysWithValues: (snapshot.state.workspaces[key]?.visibleWindows ?? []).compactMap { id in guard let requested = snapshot.state.frames[id], let target = targetAvoidingAcceptedFrames(requested, for: id, in: key) else { return nil } return (id, target) }) } struct TourFrameScope { let workspace: WorkspaceKey let applications: [WindowID: AppID] init(_ point: EngineWorkspaceRestorePoint) { workspace = point.workspace applications = point.windows.filter { point.frames[$0.key] != nil }.mapValues(\.app) } } func tourAllowsFrame(_ window: WindowID, in workspace: WorkspaceKey) -> Bool { !isWaitingForTour || (tourFrameScope?.workspace == workspace && tourFrameScope?.applications[window] == snapshot.state.windows[window]?.app) } struct WorkspaceWaiter { let workspace: WorkspaceKey let excludedApplications: Set let reply: CheckedContinuation let timeout: any EngineCancellation } public func flushTourDiscovery() throws { guard isRunning else { throw EngineError.stopped } guard isWaitingForTour else { throw EngineWorkspaceFailure.busy } while !queue.isEmpty || needsRetile { turn?.cancel() turn = nil flush() } } public func drainTourWriters(timeout: Duration = .seconds(2)) async throws { guard isWaitingForTour else { throw EngineWorkspaceFailure.busy } suspendMotion() let deadline = ContinuousClock.now.advanced(by: timeout) while !busyApps.isEmpty || focusOperations > 0 || !windowOperations.isEmpty { guard ContinuousClock.now < deadline else { throw EngineWorkspaceFailure.busy } try Task.checkCancellation() try await Task.sleep(for: .milliseconds(10)) } try Task.checkCancellation() try flushTourDiscovery() } public func captureTourRestorePoint(in key: WorkspaceKey, freshFrames: [WindowID: Rect]) throws -> EngineWorkspaceRestorePoint { guard isWaitingForTour, busyApps.isEmpty else { throw EngineWorkspaceFailure.busy } try validateWorkspace(key) let visible = snapshot.state.workspaces[key]?.visibleWindows ?? [] guard visible.allSatisfy({ freshFrames[$0] != nil }) else { throw EngineWorkspaceFailure.unsettled(visible.filter { freshFrames[$0] == nil }) } for (id, frame) in freshFrames where snapshot.state.workspace(containing: id) == key { actualFrames[id] = frame } let point = try captureWorkspaceRestorePoint(in: key) return EngineWorkspaceRestorePoint( workspace: point.workspace, isAutomaticTilingEnabled: point.isAutomaticTilingEnabled, owner: point.owner, lifetime: point.lifetime, model: point.model, modes: point.modes, windows: point.windows, frames: freshFrames.filter { point.windows[$0.key] != nil }, writeAttempts: point.writeAttempts) } public func performTourRetile(_ point: EngineWorkspaceRestorePoint) async throws -> EngineCommandResult { let key = point.workspace guard isWaitingForTour, busyApps.isEmpty, tourFrameScope == nil else { throw EngineWorkspaceFailure.busy } try validateWorkspace(key) guard point.owner == workspaceTransactionOwner, point.lifetime == lifetime, (snapshot.state.workspaces[key]?.visibleWindows ?? []).allSatisfy({ id in point.frames[id] != nil && point.windows[id]?.app == snapshot.state.windows[id]?.app }) else { throw EngineWorkspaceFailure.workspaceUnavailable } try requireCommandDisplay(.retile, display: key.display) try Task.checkCancellation() // Minimum learning can change the layout after the first write receipt. tourFrameScope = TourFrameScope(point) defer { tourFrameScope = nil } let (state, effects) = reduce(snapshot.state, .workspaceCommandIssued(.retile, workspace: key)) revision += 1 snapshot = EngineSnapshot( revision: revision, state: state, readbackFrames: snapshot.readbackFrames, displaySuspensions: displaySuspensions) let windows = Set(state.workspaces[key]?.visibleWindows ?? []) let id = UUID() let result: EngineCommandResult = try await withTaskCancellationHandler { try await withCheckedThrowingContinuation { reply in let pending = Pending( event: .workspaceCommandIssued(.retile, workspace: key), reply: reply, commandID: id) finishCommand(pending, effects: effects) planFrames(manualWindows: windows) for subscriber in subscribers.values { subscriber.yield(snapshot) } settleIfIdle() } } onCancel: { Task { @MainActor [weak self] in self?.cancelCommand(id) } } try await awaitWorkspaceSettled(in: key) return result } public func captureWorkspaceRestorePoint(in key: WorkspaceKey) throws -> EngineWorkspaceRestorePoint { try validateWorkspace(key) guard let workspace = snapshot.state.workspaces[key] else { throw EngineWorkspaceFailure.workspaceUnavailable } let members = Set(workspace.order) return EngineWorkspaceRestorePoint( workspace: key, isAutomaticTilingEnabled: isAutomaticTilingEnabled, owner: workspaceTransactionOwner, lifetime: lifetime, model: workspace, modes: snapshot.state.modes(for: key), windows: snapshot.state.windows.filter { members.contains($0.key) }, frames: actualFrames.filter { members.contains($0.key) }, writeAttempts: workspaceWriteAttempts.filter { members.contains($0.key) }) } public func workspaceNeedsFrameRestoration(_ point: EngineWorkspaceRestorePoint) -> Bool { let ids = Set(point.frames.keys) // A failed readback cannot prove that a dispatched write left the window unchanged. if ids.contains(where: { workspaceWriteAttempts[$0, default: 0] != point.writeAttempts[$0, default: 0] && snapshot.readbackFrames[$0] != point.frames[$0] }) { return true } if ids.contains(where: { actualFrames[$0] != point.frames[$0] }) { return true } if ids.contains(where: { motionPlans[$0] != nil || pendingFrames[$0.motionID] != nil }) { return true } let apps = Set(ids.compactMap { snapshot.state.windows[$0]?.app.motionID }) return !busyApps.isDisjoint(with: apps) } public func workspaceUnmovedApplications( _ point: EngineWorkspaceRestorePoint, among applications: Set ) -> Set { guard point.owner == workspaceTransactionOwner, point.lifetime == lifetime else { return [] } let windows = snapshot.state.workspaces[point.workspace]?.order ?? [] return Set( applications.filter { app in let ids = windows.filter { snapshot.state.windows[$0]?.app == app } return !ids.isEmpty && ids.allSatisfy { id in guard point.windows[id]?.app == app, let frame = point.frames[id], actualFrames[id] == frame else { return false } return workspaceWriteAttempts[id, default: 0] == point.writeAttempts[id, default: 0] || snapshot.readbackFrames[id] == frame } }) } public func restoreWorkspace(_ point: EngineWorkspaceRestorePoint, restoringModel: Bool = true) async throws { try Task.checkCancellation() try validateWorkspace(point.workspace) guard point.owner == workspaceTransactionOwner, point.lifetime == lifetime else { throw EngineWorkspaceFailure.workspaceUnavailable } guard manualWorkspaceRestoration == nil, tourFrameScope == nil else { throw EngineWorkspaceFailure.busy } var needsFrames = workspaceNeedsFrameRestoration(point) // A manually arranged workspace may contain hand-placed windows, not its layout's calculated slots. if !point.isAutomaticTilingEnabled { setAutomaticTilingEnabled(false) } while !queue.isEmpty || needsRetile { turn?.cancel() turn = nil flush() } needsFrames = needsFrames || workspaceNeedsFrameRestoration(point) let current = snapshot.state guard let currentWorkspace = current.workspaces[point.workspace] else { throw EngineWorkspaceFailure.workspaceUnavailable } let model = restoringModel ? point.model : currentWorkspace var restored = current restored.workspaces[point.workspace] = model restored.windows = point.windows.merging(current.windows) { _, current in current } let retained = Set( currentWorkspace.order.filter { id in guard let previous = point.windows[id], let window = current.windows[id] else { return false } return previous.app == window.app }) var events: [Event] = model.order.filter { !retained.contains($0) }.map(Event.windowDisappeared) events += currentWorkspace.order.compactMap { id in guard let window = current.windows[id], !retained.contains(id) || point.windows[id]?.isFloating != window.isFloating else { return nil } return .windowAppeared( window, workspace: point.workspace, frame: actualFrames[id] ?? current.frames[id] ?? Rect()) } if events.isEmpty { events = [.relayout] } let (reconciled, _) = reduce(restored, events) restored = current restored.workspaces[point.workspace] = reconciled.workspaces[point.workspace] var modes = restoringModel ? point.modes : current.modes(for: point.workspace) if let focused = modes.focusedWindow, !retained.contains(focused) || current.windows[focused]?.isFloating != false { modes.focusedWindow = nil } if restored.focusModes == nil { restored.focusModes = [:] } restored.focusModes?[point.workspace] = modes let members = Set(currentWorkspace.order) for id in members { cancelMotion(id, remove: false) manualCommandFrames[id] = nil frameAdjustments[id] = nil if isWaitingForTour && retained.contains(id) { blockedWindows.remove(id) exhaustedProtrusionTargets[id] = nil protrusionAttempts[id] = nil } } let (arranged, _) = reduce(restored, .relayout) restored = arranged if !point.isAutomaticTilingEnabled { manualWorkspaceRestoration = point.workspace manualRestorationFrames = point.frames.filter { retained.contains($0.key) } for (id, frame) in manualRestorationFrames { restored.frames[id] = frame } } let readbacks = snapshot.readbackFrames.filter { id, _ in snapshot.state.windows[id]?.app == restored.windows[id]?.app } revision += 1 snapshot = EngineSnapshot( revision: revision, state: restored, readbackFrames: readbacks, displaySuspensions: displaySuspensions) defer { tourFrameScope = nil manualWorkspaceRestoration = nil manualRestorationFrames.removeAll() setAutomaticTilingEnabled(point.isAutomaticTilingEnabled) } if point.isAutomaticTilingEnabled { setAutomaticTilingEnabled(true) } // A cancelled write may still finish after our last readback; restoration needs a fresh receipt. if needsFrames { let allowed = isWaitingForTour ? Set(point.frames.keys).intersection(retained) : members if isWaitingForTour { tourFrameScope = TourFrameScope(point) } planFrames(manualWindows: allowed) } for subscriber in subscribers.values { subscriber.yield(snapshot) } if needsFrames { let unchangedUnresponsive = workspaceUnmovedApplications(point, among: wedgedApps) try await awaitWorkspaceSettled(in: point.workspace, excludingApplications: unchangedUnresponsive) } } public func awaitWorkspaceSettled( in key: WorkspaceKey, timeout: Duration = .seconds(15), excludingApplications: Set = [] ) async throws { try Task.checkCancellation() if let result = workspaceSettleResult(in: key, excludingApplications: excludingApplications) { return try result.get() } let components = timeout.components let delay = max(0, Double(components.seconds) + Double(components.attoseconds) / 1e18) let id = UUID() try await withTaskCancellationHandler { try await withCheckedThrowingContinuation { (reply: CheckedContinuation) in guard !Task.isCancelled else { reply.resume(throwing: CancellationError()) return } let cancellation = scheduler.schedule(after: delay) { [weak self] in guard let self else { return } let windows = self.unsettledWindows(in: key, excludingApplications: excludingApplications) if self.isWaitingForTour { let idle = self.animators[key.display]?.isIdle != false let logger = Logger(subsystem: "dev.vinnymac.parcel", category: "tour-tidy") logger.error( "Settlement timeout unsettled=\(windows.count) animator-idle=\(idle) link-running=\(self.links[key.display]?.isRunning == true) pending=\(self.pendingFrames.count) busy-apps=\(self.busyApps.count) queue=\(self.queue.count) retile=\(self.needsRetile)" ) logger.error( "Settlement input pointer-down=\(self.pointerIsDown) dragging=\(self.dragging.count) mouse-samples=\(self.usesMouseSamples) live-resize=\(self.liveResizeWindows.count)" ) for window in windows { let detail = "window=\(window.rawValue) " + "target=\(String(describing: self.manualRestorationFrames[window] ?? self.snapshot.state.frames[window])) " + "actual=\(String(describing: self.actualFrames[window])) " + "readback=\(String(describing: self.snapshot.readbackFrames[window])) " + "adjustment=\(String(describing: self.frameAdjustments[window])) " + "attempts=\(self.workspaceWriteAttempts[window, default: 0]) " + "blocked=\(self.blockedWindows.contains(window)) " + "pending=\(self.pendingFrames[window.motionID] != nil) " + "motion=\(self.motionPlans[window] != nil)" logger.error("Settlement window: \(detail, privacy: .public)") } } self.finishWorkspaceWaiter(id, result: .failure(EngineWorkspaceFailure.unsettled(windows))) } workspaceWaiters[id] = WorkspaceWaiter( workspace: key, excludedApplications: excludingApplications, reply: reply, timeout: cancellation) } } onCancel: { Task { @MainActor [weak self] in self?.finishWorkspaceWaiter(id, result: .failure(CancellationError())) } } } func resolveWorkspaceWaiters() { for (id, waiter) in workspaceWaiters { if let result = workspaceSettleResult( in: waiter.workspace, excludingApplications: waiter.excludedApplications) { finishWorkspaceWaiter(id, result: result) } } } func finishWorkspaceWaiter(_ id: UUID, result: Result) { guard let waiter = workspaceWaiters.removeValue(forKey: id) else { return } waiter.timeout.cancel() waiter.reply.resume(with: result) } private func validateWorkspace(_ key: WorkspaceKey) throws { guard isRunning else { throw EngineError.stopped } guard snapshot.state.isActive(key), snapshot.state.workspaces[key] != nil else { throw EngineWorkspaceFailure.workspaceUnavailable } } private func workspaceSettleResult(in key: WorkspaceKey, excludingApplications: Set) -> Result< Void, any Error >? { do { try validateWorkspace(key) } catch { return .failure(error) } if systemWindowConflict != nil { return .failure(EngineWorkspaceFailure.systemConflict) } if suspendedDisplays.contains(key.display) { return .failure(EngineWorkspaceFailure.workspaceUnavailable) } if !isAutomaticTilingEnabled && manualWorkspaceRestoration != key && tourFrameScope?.workspace != key, animators[key.display]?.isIdle != false, !unsettledWindows(in: key, excludingApplications: excludingApplications).isEmpty { return .failure(EngineWorkspaceFailure.automaticTilingDisabled) } guard !isFlushing, !pumping, queue.isEmpty, turn == nil, !needsRetile, !spaceCommandRunning, focusOperations == 0, animators[key.display]?.isIdle != false else { return nil } let ids = Set( (snapshot.state.workspaces[key]?.order ?? []).filter { id in guard let app = snapshot.state.windows[id]?.app else { return true } return !excludingApplications.contains(app) }) let apps = Set(ids.compactMap { snapshot.state.windows[$0]?.app.motionID }) let motionIDs = Set(ids.map(\.motionID)) guard !pendingFrames.values.contains(where: { motionIDs.contains($0.windowID) }), busyApps.isDisjoint(with: apps), operatingWindows.isDisjoint(with: ids), dragging.isDisjoint(with: ids) else { return nil } let windows = unsettledWindows(in: key, excludingApplications: excludingApplications) // A timed-out app has an event-driven recovery probe. Idle writers do not mean it refused the layout. if windows.contains(where: { id in snapshot.state.windows[id].map { wedgedApps.contains($0.app) } == true }) { return nil } return windows.isEmpty ? .success(()) : .failure(EngineWorkspaceFailure.unsettled(windows)) } private func unsettledWindows(in key: WorkspaceKey, excludingApplications: Set) -> [WindowID] { let ids = manualWorkspaceRestoration == key ? Array(manualRestorationFrames.keys) : snapshot.state.workspaces[key]?.tree?.windows ?? [] return ids.filter { id in if let app = snapshot.state.windows[id]?.app, excludingApplications.contains(app) { return false } if workspaceWriteAttempts[id, default: 0] > 0, snapshot.readbackFrames[id] == nil { return true } guard let requested = manualRestorationFrames[id] ?? snapshot.state.frames[id], let actual = actualFrames[id] else { return true } let restoring = manualWorkspaceRestoration == key && manualRestorationFrames[id] != nil guard let target = restoring ? requested : targetAvoidingAcceptedFrames(requested, for: id, in: key) else { return true } // Settlement must validate the same allocation the writer used, including obstacle clipping. guard restoring || actual.fitsInside(target) else { return true } if actual.matches(target) { return false } guard let adjustment = frameAdjustments[id], adjustment.requested == target else { return true } return !actual.matches(adjustment.accepted) }.sorted() } }