import Foundation import ParcelCore import ParcelEngine import ParcelPlatform struct AppRestorationFailure: LocalizedError { let message: String let harmfulWindows: Set var errorDescription: String? { message } static func isHarmful(readback: Rect, target: Rect, displayFrames: [Rect]) -> Bool { func valid(_ frame: Rect) -> Bool { frame.minX.isFinite && frame.minY.isFinite && frame.maxX.isFinite && frame.maxY.isFinite && frame.size.width.isFinite && frame.size.height.isFinite && frame.size.width > 0 && frame.size.height > 0 } guard valid(target) else { return false } guard valid(readback) else { return true } // Small rounding differences and app-clamped sizes are not harmful placement. guard abs(readback.minX - target.minX) > 2 || abs(readback.minY - target.minY) > 2 else { return false } let displays = displayFrames.filter(valid) if !displays.isEmpty { let titlebar = Rect(x: readback.minX, y: readback.minY, width: readback.size.width, height: 24) let reachable = displays.contains { min(titlebar.maxX, $0.maxX) - max(titlebar.minX, $0.minX) >= min(80, titlebar.size.width) && min(titlebar.maxY, $0.maxY) - max(titlebar.minY, $0.minY) >= 16 } if !reachable { return true } } return abs(readback.minX - target.minX) > max(80, target.size.width / 2) || abs(readback.minY - target.minY) > max(80, target.size.height / 2) } } @MainActor final class RestoringWindowWorld: EngineWindowWorld, EngineSpaceWorld, EngineWindowInspectionProviding, EngineCommandWindowProviding { // Leave time to report overdue apps, remove the socket, and reply to AppKit. static let restorationBudget = AppTermination.cleanupBudget - 0.15 private let base: any EngineWindowWorld var accessibilityPermissionGranted: Bool? { base.accessibilityPermissionGranted } private let scheduler: any EngineScheduler private let existingWindows: @MainActor () async throws -> Set? private let displayFrames: @MainActor () -> [Rect] private let confirmedFocus: @MainActor (WindowID) -> Void private var originals: [WindowID: (app: AppID, frame: Rect)] = [:] private var modified: Set = [] private var writeWatermarks: [WindowID: UInt64] = [:] private var pending: [AppID: Int] = [:] private var restoration: Restoration? private var generation = 0 private var restoring = false private var started = false init( base: any EngineWindowWorld, scheduler: any EngineScheduler = RunLoopEngineScheduler(), existingWindows: @escaping @MainActor () async throws -> Set? = { nil }, displayFrames: @escaping @MainActor () -> [Rect] = { [] }, confirmedFocus: @escaping @MainActor (WindowID) -> Void = { _ in } ) { self.base = base self.scheduler = scheduler self.existingWindows = existingWindows self.displayFrames = displayFrames self.confirmedFocus = confirmedFocus } func inspectionWindow(_ id: WindowID) -> ManagedWindow? { (base as? any EngineWindowInspectionProviding)?.inspectionWindow(id) } func focusedInspectionWindow(pid: Int32) async throws -> ManagedWindow? { try await (base as? any EngineWindowInspectionProviding)?.focusedInspectionWindow(pid: pid) } func focusedCommandWindow() async throws -> ManagedWindow? { guard !restoring else { throw EngineError.stopped } guard let provider = base as? any EngineCommandWindowProviding else { return nil } return try await provider.focusedCommandWindow() } func close(_ window: WindowID) async throws { guard !restoring else { throw EngineError.stopped } try await base.close(window) } func toggleFullscreen(_ window: WindowID) async throws { guard !restoring else { throw EngineError.stopped } try await base.toggleFullscreen(window) } func setDetectionTracing(_ source: (any DetectionTraceSource)?) { base.setDetectionTracing(source) } func start(receive: @escaping @MainActor (EnginePlatformEvent) -> Void) throws { originals.removeAll() modified.removeAll() pending.removeAll() writeWatermarks.removeAll() generation += 1 restoring = false try base.start { [weak self] event in guard let self else { event.dropDetectionTracing() return } let observation = event.untraced if case .observed(.windowAppeared(let window, _, let frame)) = observation, self.originals[window.id] == nil { self.originals[window.id] = (window.app, frame) } else if case .appExited(let app) = observation { for id in self.originals.keys where self.originals[id]?.app == app { self.originals[id] = nil self.modified.remove(id) self.writeWatermarks[id] = nil } } if !self.restoring { if case .observed(.focusChanged(let window)) = observation, let window { self.confirmedFocus(window) } receive(event) } else { event.dropDetectionTracing() } } started = true } func write( _ frames: [EngineFrameWrite], for app: AppID, completion: @escaping @MainActor (EngineWriteReceipt) -> Void ) { precondition(!restoring, "The engine must stop writing before restoration begins.") for frame in frames { if originals[frame.window]?.frame != frame.frame { modified.insert(frame.window) } writeWatermarks[frame.window] = max(writeWatermarks[frame.window, default: 0], frame.generation) } pending[app, default: 0] += 1 let generation = generation base.write(frames, for: app) { [weak self] receipt in if let self, self.generation == generation { let count = self.pending[app, default: 0] precondition(count > 0, "A window write replied more than once.") self.pending[app] = count == 1 ? nil : count - 1 if let restoration = self.restoration { self.restoreReadyApps(restoration) } } completion(receipt) } } func focus(_ window: WindowID, completion: @escaping @MainActor (EnginePlatformFailure?) -> Void) { let generation = generation base.focus(window) { [weak self] failure in if let self, self.generation == generation, self.started, !self.restoring, failure == nil { self.confirmedFocus(window) } completion(failure) } } func raise(_ window: WindowID, completion: @escaping @MainActor (EnginePlatformFailure?) -> Void) { base.raise(window, completion: completion) } func reconcile(_ apps: Set) { base.reconcile(apps) } func spaceSnapshot() async throws -> [NativeDisplaySpaces] { guard let spaces = base as? any EngineSpaceWorld else { throw SpaceCommandError.displayUnavailable } return try await spaces.spaceSnapshot() } func executeSpaceCommand( _ destination: SpaceDestination, display: DisplayID, window: WindowID?, follow: Bool ) async throws -> SpaceCommandResult { guard !restoring, let spaces = base as? any EngineSpaceWorld else { throw SpaceCommandError.displayUnavailable } return try await spaces.executeSpaceCommand(destination, display: display, window: window, follow: follow) } func cancelFrameWrites(_ window: WindowID, for app: AppID, throughGeneration: UInt64) { writeWatermarks[window] = max(writeWatermarks[window, default: 0], throughGeneration) base.cancelFrameWrites(window, for: app, throughGeneration: throughGeneration) } func acceptCurrentPlacement() throws { guard started, !restoring, pending.isEmpty else { throw EngineWorkspaceFailure.busy } // Deferred setup must not inherit shutdown writes from tiling before the tour hold. modified.removeAll() } // The engine stops first so nothing can overwrite the restored frames. func beginRestoration() { restoring = true } func stop() { if !restoring { base.stop() started = false } } func restoreAndStop() async throws { guard started else { return } precondition(restoration == nil, "Window restoration is already running.") restoring = true let groups = Dictionary( grouping: modified.compactMap { id in originals[id].map { (id, $0) } }, by: { $0.1.app }) let restoration = Restoration( frames: groups.mapValues { windows in windows.map { id, original in let watermark = writeWatermarks[id, default: 0] precondition(watermark < .max, "Restoration write generation exhausted") return EngineFrameWrite( window: id, frame: original.frame, transaction: 0, generation: watermark + 1) } }, pendingApps: Set(pending.keys)) self.restoration = restoration defer { self.restoration = nil base.stop() started = false restoring = false originals.removeAll() modified.removeAll() writeWatermarks.removeAll() } try await restoration.wait(scheduler: scheduler) { restoration.inventory = Task { @MainActor [weak self, weak restoration] in guard let self, let restoration else { return } do { let existing = try await self.existingWindows() guard restoration.isActive else { return } restoration.prepare(existing: existing) self.restoreReadyApps(restoration) } catch { restoration.finish(.failure(error)) } } } } private func restoreReadyApps(_ restoration: Restoration) { guard restoration.isActive, restoration.prepared else { return } for app in restoration.awaiting where pending[app] == nil && !restoration.writing.contains(app) { let frames = restoration.frames[app] ?? [] guard !frames.isEmpty else { restoration.complete(app, failures: []) continue } restoration.writing.insert(app) base.write(frames, for: app) { [weak self, weak restoration] receipt in guard let self, let restoration, restoration.isActive else { return } var failures = receipt.failures for frame in frames { guard let readback = receipt.frames.first(where: { $0.window == frame.window })?.frame else { restoration.unverifiedWindows.insert(frame.window) continue } if AppRestorationFailure.isHarmful( readback: readback, target: frame.frame, displayFrames: self.displayFrames()) { restoration.harmfulWindows.insert(frame.window) } if readback != frame.frame { failures.append( .unexpected( EngineUnexpectedFailure( cause: AppText.failure("A window did not return to its original frame.")))) } } restoration.complete(app, failures: failures) } } restoration.finishIfComplete() } @MainActor private final class Restoration { var frames: [AppID: [EngineFrameWrite]] private(set) var awaiting: Set var writing: Set = [] private(set) var prepared = false var inventory: Task? private var failures: [EnginePlatformFailure] = [] var harmfulWindows: Set = [] var unverifiedWindows: Set = [] private var continuation: CheckedContinuation? private var timeout: (any EngineCancellation)? var isActive: Bool { continuation != nil } init(frames: [AppID: [EngineFrameWrite]], pendingApps: Set) { self.frames = frames awaiting = Set(frames.keys).union(pendingApps) } func wait(scheduler: any EngineScheduler, operation: () -> Void) async throws { try await withCheckedThrowingContinuation { continuation in self.continuation = continuation timeout = scheduler.schedule(after: RestoringWindowWorld.restorationBudget) { [weak self] in guard let self else { return } let identities = self.awaiting.sorted { ($0.bundleID, $0.pid) < ($1.bundleID, $1.pid) }.map { "\($0.bundleID) (pid \($0.pid))" }.joined(separator: ", ") var detail = AppText.string("Window writes did not finish before shutdown.") + " " + identities if !self.failures.isEmpty { detail += " " + String(describing: self.failures) } self.finish(.failure(self.failure(detail: detail))) } operation() } } func prepare(existing: Set?) { frames = frames.mapValues { $0.filter { existing?.contains($0.window) != false } } prepared = true } func complete(_ app: AppID, failures: [EnginePlatformFailure]) { guard isActive, awaiting.remove(app) != nil else { return } self.failures += failures finishIfComplete() } func finishIfComplete() { guard awaiting.isEmpty else { return } if failures.isEmpty && unverifiedWindows.isEmpty && harmfulWindows.isEmpty { finish(.success(())) } else { finish(.failure(failure(detail: String(describing: failures)))) } } private func failure(detail: String) -> AppRestorationFailure { let unverified = unverifiedWindows.sorted().map { String($0.rawValue) }.joined(separator: ", ") let detail = detail + (unverified.isEmpty ? "" : " Unverified window readback: " + unverified) return AppRestorationFailure( message: AppText.detail("Some windows could not be restored: %@", detail).message, harmfulWindows: harmfulWindows) } func finish(_ result: Result) { timeout?.cancel() timeout = nil inventory?.cancel() inventory = nil let previous = continuation continuation = nil previous?.resume(with: result) } } }