import AppKit import ParcelConfig import ParcelCore import ParcelEngine import ParcelIPC import ParcelPlatform import ParcelUI import ServiceManagement @MainActor enum AppTourIntegration { static func isRealDesktopAudit(environment: [String: String] = ProcessInfo.processInfo.environment) -> Bool { #if DEBUG && PARCEL_REALITY environment["PARCEL_REAL_DESKTOP"] == "1" #else false #endif } static func permitsRealDesktopStatus( _ arguments: [String], environment: [String: String] = ProcessInfo.processInfo.environment ) -> Bool { arguments == ["status"] && isRealDesktopAudit(environment: environment) } private static var fixtureTidyFailure = false private static var fixtureLayoutFailureCount = 0 static func ignoresTourDiscovery(bundleID: String, rules: [RuleConfiguration]) -> Bool { for rule in rules.reversed() { guard rule.bundleID == nil || rule.bundleID == bundleID, let action = rule.action else { continue } // Unknown window facts cannot rule out a later placement override. if action != .ignore { return false } if rule.bundleID == bundleID, rule.appName == nil, rule.titleContains == nil, rule.titleRegex == nil, rule.role == nil, rule.subrole == nil { return true } } return false } static func actions( settings: SettingsModel, services: EngineShellServices, permissions: SystemPermissionProvider, defaults: UserDefaults = .standard, targetDisplay: (() -> DisplayID?)? = nil, openShortcuts: @escaping () throws -> Void = { throw TourSetupFailure.unavailable }, openConfigurationSettings: @escaping () throws -> Void = { throw TourSetupFailure.unavailable }, acceptCurrentPlacement: @escaping () throws -> Void = {}, effectiveBindings: @escaping () throws -> [ConfigCommand: KeyChord]? = { nil }, readFrames: @escaping (State, WorkspaceKey) async throws -> [WindowID: Rect] = nativeFrames, readWindowOwners: @escaping () async throws -> Set = nativeWindowOwners, loginStatus: @escaping () throws -> TourLoginStatus = { try AppTourIntegration.systemLoginStatus() }, systemCheck: @escaping () throws -> TourSystemCheck = { try AppTourIntegration.checkSystem() }, waitForManualPermissionDeadline: @escaping @MainActor (Duration) async throws -> Void = { try await Task.sleep(for: $0) } ) -> TourSetupActions { let session = TourActivation( settings: settings, services: services, permissions: permissions, progress: TourSetupProgressStore(defaults: defaults), targetDisplay: targetDisplay, readFrames: readFrames, readWindowOwners: readWindowOwners, systemCheck: systemCheck, acceptCurrentPlacement: acceptCurrentPlacement, waitForManualPermissionDeadline: waitForManualPermissionDeadline, injectFailure: { if fixtureTidyFailure { fixtureLayoutFailureCount += 1 throw TourSetupFailure.tidyFailed } }) return TourSetupActions( checkShortcuts: { let environment = try await settings.shortcutEnvironment() return try TourShortcutCheck( configuration: settings.configuration, environment: environment, effectiveBindings: effectiveBindings()) }, checkSystem: systemCheck, loginStatus: loginStatus, setOpenAtLogin: { enabled in try await applyLoginChoice( enabled, save: { try await settings.setValue(.bool($0), for: .launchAtLogin) }, reload: { try await reload(services) }, status: loginStatus) }, preparePresentation: { services.holdForTour() let epoch = services.tourEpoch try services.persistTourOff() try Task.checkCancellation() do { if let engine = services.engine, engine.isRunning { try await engine.drainTourWriters() } } catch { guard services.tourEpoch == epoch else { throw CancellationError() } if !(error is CancellationError) { try recordUnknownRecovery(defaults: defaults, services: services) } throw error } guard services.tourEpoch == epoch else { throw CancellationError() } try Task.checkCancellation() try acceptCurrentPlacement() }, checkReady: { await session.checkReady($0) }, start: { await session.start($0, attempt: $1) }, deferSetup: { let epoch = services.tourEpoch try services.persistTourOff() do { if let engine = services.engine, engine.isRunning { try await engine.drainTourWriters() } } catch { guard services.tourEpoch == epoch else { throw CancellationError() } if !(error is CancellationError) { try recordUnknownRecovery(defaults: defaults, services: services) } throw error } guard services.tourEpoch == epoch else { throw CancellationError() } try Task.checkCancellation() try acceptCurrentPlacement() let store = TourSetupProgressStore(defaults: defaults) guard var saved = try store.load() else { throw TourProgressFailure.saveFailed } saved.disposition = .deferred if saved.recovery == .interrupted { saved.recovery = .none } try store.save(saved) if saved.recovery == .recoveryRequired { services.setTourRecoveryNotice(saved.recoveryNotice) } else { services.finishTour(automatic: false) } }, keepCurrentArrangement: { let store = TourSetupProgressStore(defaults: defaults) return try await keepCurrentArrangement( services: services, loadProgress: { try store.load() }, saveProgress: { try store.save($0) }, drainWriters: { if let engine = services.engine, engine.isRunning { try await engine.drainTourWriters() } }, acceptCurrentPlacement: acceptCurrentPlacement) }, currentIntent: { services.selectedTourIntent }, openShortcuts: openShortcuts, openConfigurationSettings: openConfigurationSettings, openSystemSettings: { guard let url = URL(string: "x-apple.systempreferences:com.apple.Desktop-Settings.extension"), NSWorkspace.shared.open(url) else { throw TourSetupFailure.unavailable } }, openLoginSettings: { SMAppService.openSystemSettingsLoginItems() }, permissionStatus: { await permissions.refreshPermission() return permissions.status }, openAccessibilitySettings: { try permissions.openAccessibilitySettings() }) } private static func recordUnknownRecovery(defaults: UserDefaults, services: EngineShellServices) throws { let store = TourSetupProgressStore(defaults: defaults) var saved = try store.load() ?? TourSetupProgress() saved.recovery = .recoveryRequired try store.save(saved) services.setTourRecoveryNotice(saved.recoveryNotice) services.composition?.report(AppFailure(message: TourStartResult.recoveryRequired(details: []).title)) } static func keepCurrentArrangement( services: EngineShellServices, loadProgress: () throws -> TourSetupProgress?, saveProgress: (TourSetupProgress) throws -> Void, drainWriters: () async throws -> Void, acceptCurrentPlacement: () throws -> Void ) async throws -> TourSetupProgress { guard let previous = try loadProgress(), previous.recovery == .recoveryRequired else { throw TourSetupFailure.notReady } let epoch = services.tourEpoch try services.persistTourOff() try Task.checkCancellation() try await drainWriters() guard services.tourEpoch == epoch else { throw CancellationError() } try Task.checkCancellation() guard try loadProgress() == previous else { throw TourProgressFailure.saveFailed } try acceptCurrentPlacement() var accepted = previous accepted.recovery = .none accepted.disposition = .inProgress do { try saveProgress(accepted) } catch { // A defaults write can succeed in memory before its durability check fails. do { try saveProgress(previous) } catch let restoration { throw TourSetupFailure.restorationFailed( operation: error.localizedDescription, restoration: restoration.localizedDescription) } throw error } services.setTourRecoveryNotice(nil) return accepted } static func useAlternatePrefix(settings: SettingsModel, services: EngineShellServices) async throws { try await settings.setValue(.string("alt-cmd"), for: .prefix) try await reload(services) } static func applyLoginChoice( _ enabled: Bool, save: (Bool) async throws -> Void, reload: () async throws -> Void, status: () throws -> TourLoginStatus ) async throws -> TourLoginStatus { try Task.checkCancellation() try await save(enabled) try await reload() let result = try status() guard enabled ? result != .disabled : result == .disabled else { throw TourSetupFailure.applyFailed } return result } static func checkSystem() throws -> TourSystemCheck { let preferences = try SystemWindowPreferences() defer { preferences.stop() } preferences.refresh() return TourSystemCheck(preferences.snapshot()) } static func systemLoginStatus() throws -> TourLoginStatus { try loginStatus(for: SMAppService.mainApp.status) } static func loginStatus(for status: SMAppService.Status) throws -> TourLoginStatus { switch status { case .enabled: .enabled case .requiresApproval: .requiresApproval case .notRegistered, .notFound: .disabled @unknown default: throw TourSetupFailure.unavailable } } private static func reload(_ services: EngineShellServices) async throws { guard let composition = services.composition else { throw TourSetupFailure.unavailable } let snapshot = await composition.reload() guard snapshot.loadState != .rejected, composition.configuration == snapshot.activeConfiguration else { throw TourSetupFailure.applyFailed } } @concurrent nonisolated static func nativeWindowOwners() async throws -> Set { try Task.checkCancellation() return windowOwners(try WindowServer().windows()) } /// Include offscreen windows: failed AX discovery cannot prove they are irrelevant. Zero-area /// placeholders (Universal Control keeps one) can never be tiled, so they never block Tidy. nonisolated static func windowOwners(_ windows: [WindowServer.Window]) -> Set { WindowServer.windowOwners(windows) } @concurrent nonisolated static func nativeFrames(_ state: State, _ key: WorkspaceKey) async throws -> [WindowID: Rect] { try Task.checkCancellation() let server = WindowServer() guard try server.currentSpace(displayID: key.display.rawValue) == key.space.rawValue else { throw TourSetupFailure.workspaceUnavailable } let windows = try server.windows() var frames: [WindowID: Rect] = [:] for native in windows { let id = WindowID(rawValue: native.number) guard let managed = state.windows[id], managed.app.pid == native.pid, state.workspace(containing: id) == key, native.isOnscreen else { continue } frames[id] = Rect( x: native.bounds.minX, y: native.bounds.minY, width: native.bounds.width, height: native.bounds.height) } return frames } static func describe(_ error: any Error, state: State) -> any Error { if error is NativeDiscoveryError { return TourSetupFailure.unavailable } if let failure = error as? EngineError, case .stopped = failure { return TourSetupFailure.unavailable } guard let failure = error as? EngineWorkspaceFailure else { return error } switch failure { case .workspaceUnavailable: return TourSetupFailure.workspaceUnavailable case .systemConflict: return TourSetupFailure.systemConflict case .busy: return TourSetupFailure.busy case .automaticTilingDisabled: return TourSetupFailure.tidyFailed case .unsettled(let windows): let detail = TourSetupFailure.unsettledWindows(windows, titles: state.windows.mapValues(\.title)) let recovery = AppText.string( "Check these windows for dialogs, then choose Keep current arrangement in setup. You can then choose Retile from Parcel’s menu." ) return AppFailure(message: "\(detail.localizedDescription) \(recovery)") } } static func verifyArrangement( state: State, workspace: WorkspaceKey, before: [WindowID: Rect], native: [WindowID: Rect], receipts: [WindowID: Rect], exhausted: Set, targets: [WindowID: Rect]? = nil ) throws -> [WindowID] { let windows = state.workspaces[workspace]?.visibleWindows ?? [] guard let display = state.displays[workspace.display] else { throw TourSetupFailure.workspaceUnavailable } var refused: [WindowID] = [] for id in windows { guard let frame = native[id], let original = before[id], let target = (targets ?? state.frames)[id], frame.isValid, frame.size.width > 0, frame.size.height > 0 else { throw EngineWorkspaceFailure.unsettled([id]) } let acknowledged = receipts[id].map { TourFrameReadback.matches($0, frame) } == true guard acknowledged || TourFrameReadback.matches(original, frame) else { throw EngineWorkspaceFailure.unsettled([id]) } if contains(target, frame), TourFrameReadback.matches(frame, target) { continue } if acknowledged, contains(target, frame) { continue } guard acknowledged, exhausted.contains(id), TourFrameReadback.matches(original, frame), contains(display.frame, frame), windows.allSatisfy({ other in guard other != id, let otherFrame = native[other] else { return other == id } return !overlaps(frame, otherFrame) }) else { throw EngineWorkspaceFailure.unsettled([id]) } refused.append(id) } return refused } private static func contains(_ bounds: Rect, _ frame: Rect) -> Bool { frame.minX >= bounds.minX && frame.minY >= bounds.minY && frame.maxX <= bounds.maxX && frame.maxY <= bounds.maxY } private static func overlaps(_ first: Rect, _ second: Rect) -> Bool { first.minX < second.maxX && second.minX < first.maxX && first.minY < second.maxY && second.minY < first.maxY } private static func terminalName(_ result: TourStartResult?) -> String { switch result { case nil: "none" case .success: "success" case .partial: "partial" case .failedBeforeWrite: "failed-before-write" case .restored: "restored" case .recoveryRequired: "recovery-required" case .progressSaveFailed: "progress-save-failed" case .manualSaveFailed: "manual-save-failed" } } static func visibleSetupText(controller: WindowLearningController) throws -> [String] { let application = NSApplication.shared guard let window = controller.visibleSetupWindow, let root = window.contentView else { return [] } let getter = NSSelectorFromString("accessibilityAttributeValue:") let setter = NSSelectorFromString("accessibilitySetValue:forAttribute:") let attribute = "AXEnhancedUserInterface" guard application.responds(to: getter), application.responds(to: setter), let original = application.perform(getter, with: attribute)?.takeUnretainedValue() as? NSNumber else { throw TourSetupFailure.unavailable } _ = application.perform(setter, with: NSNumber(value: true), with: attribute) defer { _ = application.perform(setter, with: original, with: attribute) precondition( (application.perform(getter, with: attribute)?.takeUnretainedValue() as? NSNumber)?.boolValue == original.boolValue, "Restore the owned app’s accessibility readback flag") } guard (application.perform(getter, with: attribute)?.takeUnretainedValue() as? NSNumber)?.boolValue == true else { throw TourSetupFailure.unavailable } root.layoutSubtreeIfNeeded() window.displayIfNeeded() var pending: [NSObject] = [root] var visited: Set = [] var text: [String] = [] while let element = pending.popLast(), visited.count < 4096 { guard visited.insert(ObjectIdentifier(element)).inserted else { continue } for name in ["accessibilityLabel", "accessibilityTitle", "accessibilityValue"] { if element.responds(to: NSSelectorFromString(name)), let value = element.value(forKey: name) as? String { text.append(value) } } if element.responds(to: NSSelectorFromString("accessibilityChildren")), let values = element.value(forKey: "accessibilityChildren") as? [NSObject] { pending += values } } return text } private static func awaitFixtureChecks(_ setup: TourSetupController) async throws { let deadline = ContinuousClock.now.advanced(by: .seconds(4)) while (setup.step == .allow && setup.permission == .checking && setup.checkErrors[.permission] == nil) || (setup.step == .ready && setup.readyCheck == .checking) { guard ContinuousClock.now < deadline else { throw TourSetupFailure.unavailable } try Task.checkCancellation() try await Task.sleep(for: .milliseconds(10)) } } static func fixtureAction( _ arguments: [String], controller: WindowLearningController, notices: AppNotices, noticeIsVisible: @MainActor () -> Bool, currentNotice: @MainActor () -> FeedbackNotice?, skippedApplications: @MainActor () -> [NativeDiscoverySkippedApplication] = { [] } ) async throws -> JSONValue { guard ProcessInfo.processInfo.environment["PARCEL_E2E"] == "1" || permitsRealDesktopStatus(arguments) else { throw TourSetupFailure.unavailable } let setup = controller.setup switch arguments.first { case "status" where arguments.count == 1: break case "appearance" where arguments.count == 2: let name: NSAppearance.Name? switch arguments[1] { case "light": name = .aqua case "dark": name = .darkAqua case "system": name = nil default: throw TourSetupFailure.notReady } if let name { guard let appearance = NSAppearance(named: name) else { throw TourSetupFailure.unavailable } NSApplication.shared.appearance = appearance } else { NSApplication.shared.appearance = nil } case "show", "begin" where arguments.count == 1: controller.present() let deadline = ContinuousClock.now.advanced(by: .seconds(4)) while !setup.isPresented || (setup.step == .ready && setup.readyCheck == .checking) || (setup.step == .allow && setup.permission == .checking) { guard ContinuousClock.now < deadline else { throw TourSetupFailure.unavailable } try await Task.sleep(for: .milliseconds(10)) } case "next" where arguments.count == 1: try await awaitFixtureChecks(setup) try await setup.next() try await awaitFixtureChecks(setup) case "back" where arguments.count == 1: try await setup.back() case "refresh-checks" where arguments.count == 1: try await setup.refreshAllowChecks() case "manual" where arguments.count == 1: setup.intent = .manual case "automatic" where arguments.count == 1: setup.intent = .automatic case "tidy" where arguments.count == 1: try await setup.startSetup() case "tidy-fail-after-layout", "tidy-fail-after-scoped-write" where arguments.count == 1: guard !setup.isBusy else { throw TourSetupFailure.busy } fixtureTidyFailure = true defer { fixtureTidyFailure = false } try await setup.startSetup() case "cancel" where arguments.count == 1: setup.cancelStartup() case "skip-tidy", "defer" where arguments.count == 1: try await setup.deferSetup() case "done" where arguments.count == 1: try await setup.deferSetup() case "key-return", "key-escape" where arguments.count == 1: guard setup.isPresented, let window = NSApplication.shared.keyWindow, let event = NSEvent.keyEvent( with: .keyDown, location: .zero, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: window.windowNumber, context: nil, characters: arguments[0] == "key-return" ? "\r" : "\u{1b}", charactersIgnoringModifiers: arguments[0] == "key-return" ? "\r" : "\u{1b}", isARepeat: false, keyCode: arguments[0] == "key-return" ? 36 : 53) else { throw TourSetupFailure.notReady } window.sendEvent(event) default: throw TourSetupFailure.notReady } if arguments.first != "status", !setup.isPresented { if setup.result?.completed == true { controller.completeTour() } else { controller.closeSetup() } } return .object([ "accepted": .bool(true), "step": .string(setup.step.rawValue), "presented": .bool(setup.isPresented), "failureAfterLayoutCount": .integer(Int64(fixtureLayoutFailureCount)), "failureAfterScopedWriteCount": .integer(Int64(fixtureLayoutFailureCount)), "terminal": .string(terminalName(setup.result)), "visibleSetupText": .array(try visibleSetupText(controller: controller).map { .string($0) }), "isBusy": .bool(setup.isBusy), "didTidy": .bool(setup.didTidy), "intent": .string(setup.intent.rawValue), "skippedApplications": .array( skippedApplications().map { skipped in .object([ "pid": .integer(Int64(skipped.app.pid)), "bundleID": .string(skipped.app.bundleID), "name": .string(skipped.name), "reason": .string(skipped.reason.rawValue), ]) }), "canContinue": .bool(setup.canContinue), "shortcutsChecked": .bool(setup.shortcuts != nil), "shortcutLimitations": .array((setup.shortcuts?.limitations ?? []).map { .string($0) }), "checkErrors": .object( Dictionary( uniqueKeysWithValues: setup.checkErrors.map { ($0.key.rawValue, .string($0.value)) })), "noticeCounts": .object( Dictionary( uniqueKeysWithValues: notices.counts.map { ($0.key.rawValue, .integer(Int64($0.value))) })), "noticeIsVisible": .bool(noticeIsVisible()), "noticeTitle": currentNotice().map { .string($0.title) } ?? .null, "noticeKind": currentNotice().map { .string($0.kind.rawValue) } ?? .null, "noticeMessageKind": currentNotice()?.messageKind.map { .string($0) } ?? .null, "applicationActive": .bool(NSApplication.shared.isActive), "keyWindowNumber": NSApplication.shared.keyWindow.map { .integer(Int64($0.windowNumber)) } ?? .null, "keyWindowFloating": .bool(NSApplication.shared.keyWindow?.level == .floating), "keyWindowTitled": .bool(NSApplication.shared.keyWindow?.styleMask.contains(.titled) == true), "nativeWindows": .array( NSApplication.shared.windows.map { window in .object([ "number": .integer(Int64(window.windowNumber)), "visible": .bool(window.isVisible), "key": .bool(window.isKeyWindow), "canBecomeKey": .bool(window.canBecomeKey), "canBecomeMain": .bool(window.canBecomeMain), "width": .number(window.frame.width), "height": .number(window.frame.height), ]) }), ]) } } @MainActor private final class TourActivation { private let settings: SettingsModel private let services: EngineShellServices private let permissions: SystemPermissionProvider private let progress: TourSetupProgressStore private let targetDisplay: (() -> DisplayID?)? private let readFrames: (State, WorkspaceKey) async throws -> [WindowID: Rect] private let readWindowOwners: () async throws -> Set private let systemCheck: () throws -> TourSystemCheck private let injectFailure: () throws -> Void private let acceptCurrentPlacement: () throws -> Void private let manualPermission = TourCheckOperation() private let waitForManualPermissionDeadline: @MainActor (Duration) async throws -> Void private var target: WorkspaceKey? private var attempt: UUID? init( settings: SettingsModel, services: EngineShellServices, permissions: SystemPermissionProvider, progress: TourSetupProgressStore, targetDisplay: (() -> DisplayID?)?, readFrames: @escaping (State, WorkspaceKey) async throws -> [WindowID: Rect], readWindowOwners: @escaping () async throws -> Set, systemCheck: @escaping () throws -> TourSystemCheck, acceptCurrentPlacement: @escaping () throws -> Void, waitForManualPermissionDeadline: @escaping @MainActor (Duration) async throws -> Void, injectFailure: @escaping () throws -> Void ) { self.settings = settings self.services = services self.permissions = permissions self.progress = progress self.targetDisplay = targetDisplay self.readFrames = readFrames self.readWindowOwners = readWindowOwners self.systemCheck = systemCheck self.acceptCurrentPlacement = acceptCurrentPlacement self.waitForManualPermissionDeadline = waitForManualPermissionDeadline self.injectFailure = injectFailure } func checkReady(_ intent: TourStartIntent) async -> TourReadyCheck { await permissions.refreshPermission() guard permissions.status == .granted else { return permissions.status == .missing ? .permissionMissing : .permissionUnknown } if intent == .manual { return .ready } guard let engine = services.engine, engine.isRunning else { return .unavailable } let snapshot = await settings.store.snapshot guard validConfiguration(snapshot, engine: engine) else { return .configuration } do { let stage = try systemCheck().stageManager if stage == true || engine.systemWindowConflict == .stageManager || engine.systemWindowConflict == .both { return .stageManager } guard stage == false, engine.systemWindowConflict == nil else { return .unavailable } } catch { return .unavailable } guard let key = currentTarget(engine), engine.snapshot.state.isActive(key) else { return .targetChanged } target = key return .ready } func start(_ intent: TourStartIntent, attempt token: UUID) async -> TourStartResult { guard attempt == nil else { return .failedBeforeWrite(details: [TourSetupFailure.busy.localizedDescription]) } attempt = token defer { attempt = nil } let previous: TourSetupProgress do { guard let saved = try progress.load(), saved.intent == intent, saved.recovery == .interrupted, saved.step == .ready else { return .progressSaveFailed } previous = saved services.holdForTour() try services.persistTourOff() } catch { return intent == .manual ? .manualSaveFailed : .progressSaveFailed } let epoch = services.tourEpoch if intent == .manual { do { _ = try await manualPermission.run( operation: { await self.permissions.refreshPermission() return self.permissions.status }, waitForDeadline: waitForManualPermissionDeadline) } catch { return .manualSaveFailed } } guard services.tourEpoch == epoch else { return .failedBeforeWrite(details: []) } guard permissions.status == .granted, !Task.isCancelled else { return finishFailure(previous, details: [TourSetupFailure.accessibilityRequired.localizedDescription]) } if intent == .manual { do { try commit(previous, automatic: false) services.finishTour(automatic: false) let message = AppText.string("Automatic tiling is off. Explicit commands still work.") services.onTransientNotice?(message, message) return .success } catch { return .manualSaveFailed } } guard let engine = services.engine, engine.isRunning, let key = target, currentTarget(engine) == key else { return finishFailure(previous, details: [TourSetupFailure.workspaceUnavailable.localizedDescription]) } var configurationIdentity: TourConfigurationIdentity? var point: EngineWorkspaceRestorePoint? var baseline: [WindowID: Rect] = [:] var capturedApplications: [WindowID: AppID] = [:] let tidyLog = TourTidyLog() let transaction = TourTidyTransaction( operations: .init( checkpoint: { guard self.services.tourEpoch == epoch else { throw CancellationError() } guard try self.progress.load() == previous else { throw TourProgressFailure.saveFailed } }, arrange: { let configuration = await self.settings.store.snapshot guard self.validConfiguration(configuration, engine: engine) else { throw TourSetupFailure.configurationChanged } let identity = TourConfigurationIdentity( fileURL: self.settings.store.fileURL, snapshot: configuration) configurationIdentity = identity try await self.revalidate(engine, key: key, identity: identity, epoch: epoch) try await self.services.awaitTourDiscovery() try await engine.drainTourWriters() let skipped = self.services.tourSkippedApplications().filter { !AppTourIntegration.ignoresTourDiscovery( bundleID: $0.app.bundleID, rules: configuration.activeConfiguration.rules) } let nativeOwners: Set = if skipped.isEmpty { [] } else { try await self.readWindowOwners() } try await self.revalidate(engine, key: key, identity: identity, epoch: epoch) let managedOwners = Set(engine.snapshot.state.windows.values.map(\.app)) let blocking = skipped.filter { managedOwners.contains($0.app) || nativeOwners.contains($0.app.pid) } for app in skipped { tidyLog.skippedApplication( pid: app.app.pid, bundleID: app.app.bundleID, reason: app.reason.rawValue, blocksTidy: blocking.contains(app)) } tidyLog.phase( "discovery-drained", windows: engine.snapshot.state.workspaces[key]?.order.count ?? 0, skipped: skipped.count, blocking: blocking.count) guard blocking.isEmpty else { throw TourSetupFailure.unresponsiveApplications(blocking.map(\.name)) } baseline = try await self.readFrames(engine.snapshot.state, key) try await self.revalidate(engine, key: key, identity: identity, epoch: epoch) let captured = try engine.captureTourRestorePoint(in: key, freshFrames: baseline) point = captured capturedApplications = engine.snapshot.state.windows.mapValues(\.app) tidyLog.phase("capture", windows: baseline.count) let result = try await engine.performTourRetile(captured) try self.injectFailure() guard result.isAccepted else { throw TourSetupFailure.tidyFailed } try await engine.awaitWorkspaceSettled(in: key) try await self.revalidate(engine, key: key, identity: identity, epoch: epoch) let final = try await self.readFrames(engine.snapshot.state, key) let refused = try AppTourIntegration.verifyArrangement( state: engine.snapshot.state, workspace: key, before: baseline, native: final, receipts: engine.snapshot.readbackFrames, exhausted: Set(engine.frameWriteDiagnostics.filter { $0.value.limitReached }.keys), targets: engine.workspacePlacementTargets(in: key)) return refused.map { id in TourSetupFailure.unsettledWindows( [id], titles: engine.snapshot.state.windows.mapValues(\.title) ) .localizedDescription } }, commit: { guard let identity = configurationIdentity else { throw TourSetupFailure.configurationChanged } try await self.revalidate(engine, key: key, identity: identity, epoch: epoch) try self.commit(previous, automatic: true) }, release: { self.services.finishTour(automatic: true) let message = TourStartResult.success.title self.services.onTransientNotice?(message, message) }, drain: { try await engine.drainTourWriters() }, restoreWorkspace: { guard self.services.tourEpoch == epoch else { throw CancellationError() } guard let point else { throw TourSetupFailure.workspaceUnavailable } try await engine.restoreWorkspace( point, restoringModel: engine.configuration == configurationIdentity?.configuration) let restored = try await self.readFrames(engine.snapshot.state, key) for (id, frame) in baseline where engine.snapshot.state.workspace(containing: id) == key && engine.snapshot.state.windows[id]?.app == capturedApplications[id] { guard restored[id].map({ TourFrameReadback.matches($0, frame) }) == true else { throw EngineWorkspaceFailure.unsettled([id]) } } }, hasPotentialWindowMovement: { point.map { engine.workspaceNeedsFrameRestoration($0) } ?? false }, recordRecovery: { required in guard self.services.tourEpoch == epoch else { throw CancellationError() } try self.services.persistTourOff() if !required { try self.acceptCurrentPlacement() } var saved = previous saved.recovery = required ? .recoveryRequired : .none try self.progress.save(saved) self.services.setTourRecoveryNotice(saved.recoveryNotice) }, describeFailure: { AppTourIntegration.describe($0, state: engine.snapshot.state).localizedDescription }), log: tidyLog) let result = await transaction.run() if case .recoveryRequired = result, services.tourEpoch == epoch { services.composition?.report(AppFailure(message: result.title)) } return result } private func finishFailure(_ previous: TourSetupProgress, details: [String]) -> TourStartResult { var saved = previous saved.recovery = .none do { try services.persistTourOff() try progress.save(saved) return .failedBeforeWrite(details: details) } catch { return .progressSaveFailed } } private func commit(_ previous: TourSetupProgress, automatic: Bool) throws { try Task.checkCancellation() guard try progress.load() == previous else { throw TourProgressFailure.saveFailed } try services.persistTourAutomaticChoice(automatic) var saved = previous saved.completed = true saved.disposition = .completed saved.recovery = .none do { try progress.save(saved) } catch { try services.persistTourOff() try progress.save(previous) throw error } } private func currentTarget(_ engine: ParcelEngine) -> WorkspaceKey? { let state = engine.snapshot.state let selected = if let targetDisplay { targetDisplay() } else { state.activeDisplay } guard let display = selected, let space = state.activeSpaces[display] else { return nil } return WorkspaceKey(display: display, space: space) } private func validConfiguration(_ snapshot: ConfigSnapshot, engine: ParcelEngine) -> Bool { (snapshot.loadState == .loaded || snapshot.loadState == .missingFileUsingDefaults) && (snapshot.activeSource == .file(settings.store.fileURL) || snapshot.activeSource == .defaults) && engine.configuration == snapshot.activeConfiguration } private func revalidate( _ engine: ParcelEngine, key: WorkspaceKey, identity: TourConfigurationIdentity, epoch: UUID ) async throws { guard services.tourEpoch == epoch else { throw CancellationError() } try Task.checkCancellation() await permissions.refreshPermission() guard permissions.status == .granted else { throw TourSetupFailure.accessibilityRequired } let snapshot = await settings.store.snapshot guard validConfiguration(snapshot, engine: engine), snapshot.activeConfiguration == identity.configuration, snapshot.lastGoodDocument?.source == identity.source else { throw TourSetupFailure.configurationChanged } try await identity.validate() try Task.checkCancellation() guard services.tourEpoch == epoch else { throw CancellationError() } guard currentTarget(engine) == key, engine.snapshot.state.isActive(key) else { throw TourSetupFailure.workspaceUnavailable } let stage = try systemCheck().stageManager if stage == true || engine.systemWindowConflict == .stageManager || engine.systemWindowConflict == .both { throw TourSetupFailure.systemConflict } guard stage == false, engine.systemWindowConflict == nil else { throw TourSetupFailure.unavailable } } } private enum TourFrameReadback { static func matches(_ frame: Rect, _ other: Rect) -> Bool { abs(frame.minX - other.minX) <= 1 && abs(frame.minY - other.minY) <= 1 && abs(frame.size.width - other.size.width) <= 1 && abs(frame.size.height - other.size.height) <= 1 } } private struct TourConfigurationIdentity: Sendable { let fileURL: URL let target: URL let source: String? let configuration: ParcelConfiguration init(fileURL: URL, snapshot: ConfigSnapshot) { self.fileURL = fileURL target = fileURL.resolvingSymlinksInPath() source = snapshot.lastGoodDocument?.source configuration = snapshot.activeConfiguration } @concurrent func validate() async throws { guard fileURL.resolvingSymlinksInPath() == target else { throw TourSetupFailure.configurationChanged } let contents: Data? do { contents = try Data(contentsOf: target) } catch let error as CocoaError where error.code == .fileReadNoSuchFile { contents = nil } guard contents == source.map({ Data($0.utf8) }) else { throw TourSetupFailure.configurationChanged } } }