Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345import Foundationimport ParcelCoreimport ParcelEngineimport ParcelPlatform
struct AppRestorationFailure: LocalizedError { let message: String let harmfulWindows: Set<WindowID> 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) }}
@MainActorfinal 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<WindowID>? private let displayFrames: @MainActor () -> [Rect] private let confirmedFocus: @MainActor (WindowID) -> Void private var originals: [WindowID: (app: AppID, frame: Rect)] = [:] private var modified: Set<WindowID> = [] 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<WindowID>? = { 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<AppID>) { 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<AppID> var writing: Set<AppID> = [] private(set) var prepared = false var inventory: Task<Void, Never>? private var failures: [EnginePlatformFailure] = [] var harmfulWindows: Set<WindowID> = [] var unverifiedWindows: Set<WindowID> = [] private var continuation: CheckedContinuation<Void, any Error>? private var timeout: (any EngineCancellation)? var isActive: Bool { continuation != nil }
init(frames: [AppID: [EngineFrameWrite]], pendingApps: Set<AppID>) { 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<WindowID>?) { 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<Void, any Error>) { timeout?.cancel() timeout = nil inventory?.cancel() inventory = nil let previous = continuation continuation = nil previous?.resume(with: result) } }}