public import Foundation import Observation public import ParcelConfig public import ParcelCore public import ParcelPlatform public enum TourLoginStatus: Equatable, Sendable { case disabled, enabled, requiresApproval } public enum TourSetupCheck: String, CaseIterable, Sendable { case permission, system, shortcuts, login } public struct TourSystemCheck: Equatable, Sendable { public let stageManager: Bool? public let nativeTiling: Bool? public init(stageManager: Bool?, nativeTiling: Bool?) { self.stageManager = stageManager self.nativeTiling = nativeTiling } public init(_ snapshot: SystemWindowPreferencesSnapshot) { stageManager = snapshot.stageManagerGloballyEnabled.confirmedBoolOrNil let values = [ snapshot.edgeDragTilingEnabled, snapshot.topDragTilingEnabled, snapshot.optionKeyTilingAcceleratorEnabled, ].map(\.confirmedBoolOrNil) nativeTiling = values.contains(true) ? true : (values.allSatisfy { $0 == false } ? false : nil) } public var isClear: Bool { stageManager == false } } public struct TourShortcutReference: Equatable, Sendable, Identifiable { public let command: ConfigCommand public let chord: KeyChord public var id: ConfigCommand { command } public init(command: ConfigCommand, chord: KeyChord) { self.command = command; self.chord = chord } } public struct TourShortcutCheck: Equatable, Sendable { public let warnings: [SettingsShortcutWarning] public let modeNotices: [String] let modeNoticeAccessibilityLabels: [String] public let limitations: [String] public let reference: [TourShortcutReference] public init( warnings: [SettingsShortcutWarning], modeNotices: [String] = [], limitations: [String] = [], reference: [TourShortcutReference] = [] ) { self.warnings = warnings self.modeNotices = modeNotices modeNoticeAccessibilityLabels = modeNotices self.limitations = limitations self.reference = reference } @MainActor public init( configuration: ParcelConfiguration, environment: SettingsShortcutEnvironment, effectiveBindings: [ConfigCommand: KeyChord]? = nil ) { let activeBindings = configuration.general.shortcutsEnabled ? configuration.keybindings : [:] var activeWarnings = SettingsShortcutChecker.warnings( bindings: activeBindings, environment: environment, additionalBindings: Array(configuration.defaultModeEntries.values)) if environment.voiceOverEnabled { for command in ConfigCommand.allCases { guard let chord = activeBindings[command], SettingsShortcutChecker.hotkey(chord).conflictsWithVoiceOver, !activeWarnings.contains(where: { $0.command == command }) else { continue } activeWarnings.append( SettingsShortcutWarning( command: command, chord: chord, messages: [TourText.text("A Parcel shortcut is already in use.")], suggestions: [])) } } warnings = activeWarnings let notices = configuration.general.shortcutsEnabled ? SettingsShortcutChecker.modeNoticeDetails(configuration: configuration, environment: environment) : [] modeNotices = notices.map(\.display) modeNoticeAccessibilityLabels = notices.map(\.accessibilityLabel) limitations = environment.limitations let referenceBindings = configuration.general.shortcutsEnabled ? (effectiveBindings ?? activeBindings) : [:] let additionalBindings = effectiveBindings == nil ? Array(configuration.defaultModeEntries.values) : [] func usable(_ command: ConfigCommand) -> KeyChord? { guard let chord = referenceBindings[command], !SettingsShortcutChecker.isLeftToMacOS(chord, environment: environment), SettingsShortcutChecker.warning( for: chord, command: command, bindings: referenceBindings, environment: environment, additionalBindings: additionalBindings) == nil else { return nil } return chord } let layout = [ ConfigCommand.layoutGrid, .layoutColumns, .layoutRows, .layoutSide, .layoutTree, .layoutBSP, .layoutAccordion, ].first { usable($0) != nil } let commands: [ConfigCommand?] = [.retile, .windowNext, layout, .floatToggle] reference = commands.compactMap { candidate in guard let command = candidate, let chord = usable(command) else { return nil } return TourShortcutReference(command: command, chord: chord) } } } @MainActor public struct TourSetupActions { public var checkShortcuts: () async throws -> TourShortcutCheck public var checkSystem: () async throws -> TourSystemCheck public var loginStatus: () throws -> TourLoginStatus public var setOpenAtLogin: (Bool) async throws -> TourLoginStatus public var preparePresentation: () async throws -> Void public var checkReady: (TourStartIntent) async -> TourReadyCheck public var start: (TourStartIntent, UUID) async -> TourStartResult public var deferSetup: () async throws -> Void public var keepCurrentArrangement: () async throws -> TourSetupProgress public var currentIntent: () -> TourStartIntent public var openShortcuts: () throws -> Void public var openConfigurationSettings: () throws -> Void public var openSystemSettings: () throws -> Void public var openLoginSettings: () throws -> Void public var permissionStatus: () async -> PermissionStatus public var openAccessibilitySettings: () throws -> Void public init( checkShortcuts: @escaping () async throws -> TourShortcutCheck, checkSystem: @escaping () async throws -> TourSystemCheck, loginStatus: @escaping () throws -> TourLoginStatus, setOpenAtLogin: @escaping (Bool) async throws -> TourLoginStatus, preparePresentation: @escaping () async throws -> Void = {}, checkReady: @escaping (TourStartIntent) async -> TourReadyCheck, start: @escaping (TourStartIntent, UUID) async -> TourStartResult, deferSetup: @escaping () async throws -> Void, keepCurrentArrangement: @escaping () async throws -> TourSetupProgress = { throw TourSetupFailure.unavailable }, currentIntent: @escaping () -> TourStartIntent = { .automatic }, openShortcuts: @escaping () throws -> Void, openConfigurationSettings: @escaping () throws -> Void = { throw TourSetupFailure.unavailable }, openSystemSettings: @escaping () throws -> Void, openLoginSettings: @escaping () throws -> Void, permissionStatus: @escaping () async -> PermissionStatus, openAccessibilitySettings: @escaping () throws -> Void = { throw TourSetupFailure.unavailable } ) { self.checkShortcuts = checkShortcuts; self.checkSystem = checkSystem self.loginStatus = loginStatus; self.setOpenAtLogin = setOpenAtLogin self.preparePresentation = preparePresentation self.checkReady = checkReady; self.start = start; self.deferSetup = deferSetup self.keepCurrentArrangement = keepCurrentArrangement self.currentIntent = currentIntent self.openShortcuts = openShortcuts; self.openConfigurationSettings = openConfigurationSettings self.openSystemSettings = openSystemSettings self.openLoginSettings = openLoginSettings; self.permissionStatus = permissionStatus self.openAccessibilitySettings = openAccessibilitySettings } } @MainActor @Observable public final class TourSetupController { public private(set) var isPresented = false public private(set) var step = TourSetupStep.welcome public private(set) var progress = TourSetupProgress() public private(set) var permission = PermissionStatus.checking public private(set) var readyCheck = TourReadyCheck.checking public private(set) var result: TourStartResult? public private(set) var errorMessage: String? public private(set) var isBusy = false public private(set) var isUpdatingLogin = false public private(set) var login: TourLoginStatus? public private(set) var loginRequest: Bool? public private(set) var checkErrors: [TourSetupCheck: String] = [:] public private(set) var checkingChecks: Set = [] public private(set) var shortcuts: TourShortcutCheck? public private(set) var system: TourSystemCheck? public private(set) var isReplay = false public private(set) var wasInterrupted = false public var modeExpanded = false public var referenceExpanded = false public var detailsExpanded = false public private(set) var voiceOverEnabled = false public private(set) var didTidy = false private var session = UUID() public var sessionID: UUID { session } private var revision = 0 private var loginDraftPending = false private var attemptedLogin = false private var defaultLogin = false private var hasAppliedLoginDefault: Bool private var loginSelection = false private var progressStateValid = true private var presentationPrepared = true public var openAtLogin: Bool { get { loginSelection } set { guard step == .allow, !isBusy, !isUpdatingLogin, newValue != loginSelection else { return } loginSelection = newValue; loginRequest = newValue; loginDraftPending = true attemptedLogin = false defaultLogin = false progress.loginDesired = newValue; persistDraft() } } public var intent: TourStartIntent { get { progress.intent } set { guard !isBusy else { return } progress.intent = newValue if newValue == .manual { modeExpanded = true } result = nil revision += 1 persistDraft() } } public var demoPaused: Bool { get { progress.demoPaused } set { progress.demoPaused = newValue; persistDraft() } } public var hasShortcutClash: Bool { shortcuts.map { !$0.warnings.isEmpty || !$0.modeNotices.isEmpty } == true } var hasPendingLoginWriter: Bool { loginAttempt.isRunning } var hasPendingReadinessCheck: Bool { readyOperation.isRunning } public var needsLoginApproval: Bool { login == .requiresApproval } public var loginWasNotChanged: Bool { checkErrors[.login] != nil } public var tidySummary: String? { result?.message } @ObservationIgnored public var actions: TourSetupActions? @ObservationIgnored private var attemptTask: Task? @ObservationIgnored private var recoveryTask: Task? @ObservationIgnored private var recoveryOperation: UUID? @ObservationIgnored private let loginAttempt = TourCheckOperation() @ObservationIgnored private let permissionCheck = TourCheckOperation() @ObservationIgnored private let readyOperation = TourCheckOperation() @ObservationIgnored private let shortcutCheck = TourCheckOperation() @ObservationIgnored var waitForCheckDeadline: @MainActor (Duration) async throws -> Void = { try await Task.sleep(for: $0) } @ObservationIgnored var waitForLoginDeadline: @MainActor (Duration) async throws -> Void = { try await Task.sleep(for: $0) } @ObservationIgnored private let saveProgress: (TourSetupProgress) throws -> Void @ObservationIgnored private let onLoginDefaultApplied: () -> Void public init( loginDefaultApplied: Bool = false, onLoginDefaultApplied: @escaping () -> Void = {}, saveProgress: @escaping (TourSetupProgress) throws -> Void = { _ in } ) { hasAppliedLoginDefault = loginDefaultApplied self.onLoginDefaultApplied = onLoginDefaultApplied self.saveProgress = saveProgress } public func begin( progress: TourSetupProgress = TourSetupProgress(), replay: Bool = false, currentIntent: TourStartIntent? = nil, defaultOpenAtLogin: Bool = false, progressError: String? = nil, wasInterrupted: Bool? = nil, progressIsValid: Bool? = nil, presentationPrepared: Bool? = nil ) { guard !isBusy else { return } cancelChecks() session = UUID(); revision += 1 self.progress = progress self.progress.disposition = .inProgress isReplay = progress.completed self.wasInterrupted = wasInterrupted ?? (progress.recovery != .none) if replay && isReplay { self.progress.step = .welcome self.progress.intent = currentIntent ?? progress.intent } step = self.progress.step defaultLogin = defaultOpenAtLogin && !hasAppliedLoginDefault && !progress.completed if defaultLogin && self.progress.loginDesired == nil { self.progress.loginDesired = true } loginSelection = self.progress.loginDesired ?? false loginDraftPending = self.progress.loginDesired != nil loginRequest = self.progress.loginDesired attemptedLogin = false modeExpanded = self.progress.intent == .manual permission = .checking; readyCheck = .checking result = nil; didTidy = false; isUpdatingLogin = false shortcuts = nil; system = nil; login = nil checkErrors.removeAll(); checkingChecks.removeAll() errorMessage = progressError progressStateValid = (progressIsValid ?? (progressError == nil)) && progress.isValid if !progress.isValid && errorMessage == nil { errorMessage = TourProgressFailure.invalid.localizedDescription } self.presentationPrepared = presentationPrepared ?? (progressError == nil) if progressStateValid && self.progress.recovery == .recoveryRequired { result = .recoveryRequired(details: self.progress.recoveryNotice.map { [$0] } ?? []) } isPresented = true } public var canContinue: Bool { guard !isBusy, progressStateValid, presentationPrepared else { return false } return switch step { case .welcome: true case .allow: permission == .granted && !isUpdatingLogin case .ready: readyCheck == .ready && errorMessage == nil && progress.recovery != .recoveryRequired } } public func chooseMode(_ intent: TourStartIntent) async throws { try Task.checkCancellation() guard isPresented, step == .welcome, canContinue, result == nil else { throw TourSetupFailure.notReady } try navigate(.allow, intent: intent) try await checkCurrentStep() } public func next() async throws { guard canContinue else { throw TourSetupFailure.notReady } switch step { case .welcome: try navigate(.allow) case .allow: let expected = session if !attemptedLogin { try await applyLoginDraft() } guard valid(expected), step == .allow else { return } try navigate(.ready) case .ready: throw TourSetupFailure.notReady } try await checkCurrentStep() } public func back() async throws { guard isPresented, !isBusy, result?.completed != true, step != .welcome else { throw TourSetupFailure.notReady } try navigate(step == .ready ? .allow : .welcome) try await checkCurrentStep() } private func navigate(_ step: TourSetupStep, intent: TourStartIntent? = nil) throws { guard progressStateValid else { throw TourProgressFailure.invalid } var next = progress if let intent { next.intent = intent } next.step = step next.disposition = .inProgress try saveProgress(next) progress = next; self.step = step; revision += 1 result = nil; errorMessage = nil } public func checkCurrentStep() async throws { guard isPresented, !isBusy else { return } switch step { case .welcome: break case .allow: try await refreshAllowChecks() case .ready: try await refreshReady() } } public func refreshAllowChecks() async throws { guard isPresented, !isBusy else { return } if step == .ready { try await refreshReady(); return } guard step == .allow else { return } let expected = session; let expectedRevision = revision try await runCheck(.permission) guard valid(expected, revision: expectedRevision), step == .allow else { return } try await runCheck(.login) guard valid(expected, revision: expectedRevision), step == .allow else { return } try await runCheck(.shortcuts) } public func refreshPermission() async throws { guard isPresented, !isBusy, step != .welcome else { return } let expected = session; let expectedRevision = revision try await runCheck(.permission) guard valid(expected, revision: expectedRevision) else { return } if step == .ready { try await refreshReady() } } public func retryCheck(_ check: TourSetupCheck) async throws { guard isPresented, !isBusy else { return } if check == .login { try await applyLoginDraft(force: true) } else { try await runCheck(check) } } private func runCheck(_ check: TourSetupCheck) async throws { guard isPresented, !checkingChecks.contains(check), let actions else { return } let expected = session; let expectedRevision = revision checkingChecks.insert(check) defer { if expected == session { checkingChecks.remove(check) } } do { switch check { case .permission: let value = try await permissionCheck.run( operation: { await actions.permissionStatus() }, waitForDeadline: waitForCheckDeadline) guard valid(expected, revision: expectedRevision) else { return } permission = value if value == .checking { checkErrors[.permission] = TourText.text("Parcel couldn’t check Accessibility access.") return } case .system: let value = try await actions.checkSystem() guard valid(expected, revision: expectedRevision) else { return } system = value case .shortcuts: let value = try await shortcutCheck.run( operation: { try await actions.checkShortcuts() }, waitForDeadline: waitForCheckDeadline) guard valid(expected, revision: expectedRevision) else { return } shortcuts = value case .login: let value = try actions.loginStatus() guard valid(expected, revision: expectedRevision) else { return } login = value if !loginDraftPending && !attemptedLogin { loginSelection = defaultLogin || value != .disabled loginDraftPending = defaultLogin && value == .disabled } if attemptedLogin && checkErrors[.login] != nil { return } } checkErrors.removeValue(forKey: check) } catch is CancellationError { throw CancellationError() } catch { guard valid(expected, revision: expectedRevision) else { return } if check == .permission { permission = .checking checkErrors[check] = TourText.text("Parcel couldn’t check Accessibility access.") } else if check == .shortcuts { checkErrors[check] = TourText.text("Shortcuts couldn’t be loaded. You can use the Parcel menu.") } else { checkErrors[check] = error.localizedDescription } } } private func refreshReady() async throws { guard isPresented, step == .ready, !isBusy, let actions else { return } let expected = session; let expectedRevision = revision readyCheck = .checking let mode = intent let value: TourReadyCheck do { value = try await readyOperation.run( operation: { await actions.checkReady(mode) }, waitForDeadline: waitForCheckDeadline) } catch is CancellationError { throw CancellationError() } catch { value = .unavailable } guard valid(expected, revision: expectedRevision) else { return } readyCheck = value if value == .permissionMissing { permission = .missing } else if value == .permissionUnknown { permission = .checking } else if value == .ready { permission = .granted } if referenceExpanded { try await runCheck(.shortcuts) } } private func applyLoginDraft(force: Bool = false) async throws { guard !isUpdatingLogin, let actions else { return } guard loginDraftPending || (force && loginRequest != nil) else { return } attemptedLogin = true isUpdatingLogin = true let expected = session let desired = loginSelection defer { if expected == session { isUpdatingLogin = false } } if defaultLogin, desired, let login, login != .disabled { loginDraftPending = false; loginRequest = nil; progress.loginDesired = nil hasAppliedLoginDefault = true onLoginDefaultApplied() checkErrors.removeValue(forKey: .login) persistDraft() return } do { let acknowledged = try await loginAttempt.run( operation: { try await actions.setOpenAtLogin(desired) }, waitForDeadline: waitForLoginDeadline) guard valid(expected) else { return } login = acknowledged loginDraftPending = false; loginRequest = nil; progress.loginDesired = nil hasAppliedLoginDefault = true onLoginDefaultApplied() checkErrors.removeValue(forKey: .login) persistDraft() } catch is CancellationError { throw CancellationError() } catch { guard valid(expected) else { return } loginRequest = desired checkErrors[.login] = TourText.text("Open at login couldn’t be changed. You can set it later in Settings.") } } public func setOpenAtLogin(_ enabled: Bool) async throws { guard step == .allow, !isUpdatingLogin else { throw TourSetupFailure.notReady } openAtLogin = enabled attemptedLogin = false } public func updateVoiceOver(_ enabled: Bool) { voiceOverEnabled = enabled } public func startSetup() async throws { guard isPresented, step == .ready, !isBusy, canContinue, let actions else { throw TourSetupFailure.notReady } let expected = session let mode = intent var checkpoint = progress checkpoint.recovery = .interrupted checkpoint.disposition = .inProgress do { try saveProgress(checkpoint) } catch { result = .progressSaveFailed errorMessage = TourText.text("Parcel couldn’t save setup progress.") return } progress = checkpoint isBusy = true; result = nil let attempt = UUID() let task = Task { await actions.start(mode, attempt) } attemptTask = task var terminal = await task.value guard isPresented, session == expected else { return } if mode == .manual { if case .failedBeforeWrite = terminal { terminal = .manualSaveFailed } if terminal == .manualSaveFailed { let currentPermission: PermissionStatus do { currentPermission = try await permissionCheck.run( operation: { await actions.permissionStatus() }, waitForDeadline: waitForCheckDeadline) } catch { currentPermission = .checking } guard isPresented, session == expected else { return } if currentPermission != .granted { permission = currentPermission readyCheck = currentPermission == .missing ? .permissionMissing : .permissionUnknown result = nil attemptTask = nil; isBusy = false return } } } attemptTask = nil; isBusy = false result = terminal didTidy = mode == .automatic && terminal.completed progress.recovery = terminal == .progressSaveFailed ? .interrupted : .none if case .recoveryRequired = terminal { progress.recovery = .recoveryRequired } if terminal.completed { progress.completed = true; progress.disposition = .completed } if terminal == .success { isPresented = false } } public func retryStartup() async throws { guard result?.permitsRetry == true else { throw TourSetupFailure.notReady } let expected = session; let expectedRevision = revision errorMessage = nil result = nil readyCheck = .checking try await requireActions().preparePresentation() guard valid(expected, revision: expectedRevision) else { return } try await refreshReady() guard valid(expected, revision: expectedRevision), canContinue else { return } try await startSetup() } public func tidyWorkspace() async throws { guard intent == .automatic else { throw TourSetupFailure.notReady } try await startSetup() } public func cancelStartup() { attemptTask?.cancel(); recoveryTask?.cancel() } public var canKeepCurrentArrangement: Bool { isPresented && !isBusy && progressStateValid && presentationPrepared && progress.recovery == .recoveryRequired } public func keepCurrentArrangement() async throws { guard canKeepCurrentArrangement else { throw TourSetupFailure.notReady } let actions = try requireActions() let expected = session let operation = UUID() errorMessage = nil isBusy = true let task = Task { @MainActor in try await actions.keepCurrentArrangement() } recoveryTask = task recoveryOperation = operation defer { if recoveryOperation == operation { recoveryTask = nil; recoveryOperation = nil; isBusy = false } } do { let accepted = try await withTaskCancellationHandler { try await task.value } onCancel: { task.cancel() } guard isPresented, session == expected else { return } progress = accepted result = nil isBusy = false try await refreshReady() } catch { guard isPresented, session == expected else { throw error } errorMessage = error.localizedDescription throw error } } public func deferSetup() async throws { guard isPresented, !isBusy else { cancelStartup(); return } if result?.completed == true { dismiss(); return } guard progressStateValid else { throw TourProgressFailure.invalid } var deferred = progress deferred.disposition = .deferred if deferred.recovery == .none { deferred.recovery = .interrupted } try saveProgress(deferred) progress = deferred let expected = session try await requireActions().deferSetup() guard valid(expected) else { return } if deferred.recovery == .interrupted { deferred.recovery = .none } progress = deferred dismiss() } public func dismiss() { guard !isBusy else { cancelStartup(); return } cancelChecks() isPresented = false; session = UUID(); revision += 1 } private func cancelChecks() { loginAttempt.cancel() permissionCheck.cancel() readyOperation.cancel() shortcutCheck.cancel() } public func openAccessibilitySettings() throws { do { try requireActions().openAccessibilitySettings() checkErrors.removeValue(forKey: .permission) } catch { checkErrors[.permission] = TourText.text("Open System Settings and turn on Accessibility for Parcel.") throw error } } public func openSettings(for step: TourSetupStep) throws { let actions = try requireActions() if step == .allow { try actions.openLoginSettings() } else if step == .welcome { try actions.openShortcuts() } else { try actions.openSystemSettings() } } public func openShortcuts() throws { try requireActions().openShortcuts() } public func reviewConfiguration() throws { try requireActions().openConfigurationSettings() } public func loadShortcuts() async throws { try await runCheck(.shortcuts) } public func report(_ error: any Error) { errorMessage = error.localizedDescription } private func valid(_ expected: UUID, revision expectedRevision: Int? = nil) -> Bool { isPresented && session == expected && (expectedRevision == nil || revision == expectedRevision) && !Task.isCancelled } private func requireActions() throws -> TourSetupActions { guard let actions else { throw TourSetupFailure.unavailable } return actions } private func persistDraft() { guard progressStateValid else { return } do { try saveProgress(progress); errorMessage = nil } catch { errorMessage = error.localizedDescription } } } public enum TourSetupFailure: LocalizedError { case unavailable, notReady, invalidDraft, busy, systemConflict, workspaceUnavailable, applyFailed, tidyFailed case accessibilityRequired case configurationChanged case unsettledWindows([WindowID], titles: [WindowID: String]) case restorationFailed(operation: String, restoration: String) case restorationIncomplete(String) case settingsRecoveryRequired(String) case unresponsiveApplications([String]) case unresponsiveDuringTidy([String]) public var errorDescription: String? { switch self { case .unavailable: TourText.text("Parcel couldn’t check setup. Try again.") case .accessibilityRequired: TourText.text("Accessibility is off.") case .notReady: TourText.text("Complete this step before continuing.") case .invalidDraft, .applyFailed: TourText.text("Parcel couldn’t load your settings.") case .busy: TourText.text("Wait for the current tour action to finish.") case .systemConflict: TourText.text("Turn off Stage Manager to arrange this screen.") case .workspaceUnavailable: TourText.text("Your screen changed. Check setup and try again.") case .tidyFailed: TourText.text("Parcel couldn’t arrange your windows.") case .configurationChanged: TourText.text("Parcel couldn’t load your settings.") case .unsettledWindows(let windows, let titles): String( format: TourText.text("Review Parcel’s notice for windows that could not settle: %@."), windows.map { titles[$0].flatMap { $0.isEmpty ? nil : $0 } ?? String.localizedStringWithFormat(TourText.text("Window %lld"), Int64($0.rawValue)) }.formatted(.list(type: .and))) case .unresponsiveApplications(let names), .unresponsiveDuringTidy(let names): String( format: TourText.text("These apps did not respond: %@. Check them before trying again."), names.formatted(.list(type: .and))) case .settingsRecoveryRequired(let reason), .restorationIncomplete(let reason): reason case .restorationFailed(let operation, let restoration): String( format: TourText.text("Check your windows and settings: %1$@. Recovery: %2$@."), operation, restoration) } } } enum TourText { static func text(_ key: String) -> String { Bundle.module.localizedString(forKey: key, value: nil, table: "TourSetup") } }