From 5a00a5d7a203903155f3b53b8ff05a2bbbc677f0 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sun, 1 Nov 2026 02:00:42 -0500 Subject: [PATCH] Make tour checks calm and accessible Signed-off-by: Vincent Taverna --- Sources/ParcelApp/Resources/App.xcstrings | 1 + .../ParcelUI/Resources/TourDemos.xcstrings | 10 + .../ParcelUI/Resources/TourSetup.xcstrings | 53 +++- Sources/ParcelUI/Tour/LearningPanel.swift | 30 +- Sources/ParcelUI/Tour/TourAllowView.swift | 89 ++++-- Sources/ParcelUI/Tour/TourCheckRow.swift | 45 ++- .../Tour/TourPersonalizationView.swift | 66 ++-- Sources/ParcelUI/Tour/TourSetup.swift | 228 +++++++++++--- Sources/ParcelUI/Tour/TourSetupView.swift | 48 ++- Sources/ParcelUI/Tour/TourTrackPicker.swift | 8 +- Sources/ParcelUI/Tour/TourView.swift | 8 +- .../Tour/WindowLearningController.swift | 135 ++++++++- .../SettingsShortcutConflictTests.swift | 23 +- Tests/ParcelUITests/Tour/TourDemoTests.swift | 6 +- Tests/ParcelUITests/Tour/TourSetupTests.swift | 283 ++++++++++++++---- .../Tour/WindowLearningControllerTests.swift | 8 +- 16 files changed, 795 insertions(+), 246 deletions(-) diff --git a/Sources/ParcelApp/Resources/App.xcstrings b/Sources/ParcelApp/Resources/App.xcstrings index 19c9bcc7..70beff71 100644 --- a/Sources/ParcelApp/Resources/App.xcstrings +++ b/Sources/ParcelApp/Resources/App.xcstrings @@ -1,6 +1,7 @@ { "sourceLanguage" : "en", "strings" : { + "Shortcuts start after you tidy." : {"comment": "First-install shortcut hold, released by tour consent; never used for replay or upgrades.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Shortcuts start after you tidy."}}}}, "Mouse controls stopped after an input timeout. Restart Parcel when it is responsive." : {"localizations": {"en": {"stringUnit": {"state": "translated", "value": "Mouse controls stopped after an input timeout. Restart Parcel when it is responsive."}}}}, "Fixture hover input requires a visible managed fixture window in e2e mode." : {"localizations": {"en": {"stringUnit": {"state": "translated", "value": "Fixture hover input requires a visible managed fixture window in e2e mode."}}}}, "The fixture hover action is invalid." : {"localizations": {"en": {"stringUnit": {"state": "translated", "value": "The fixture hover action is invalid."}}}}, diff --git a/Sources/ParcelUI/Resources/TourDemos.xcstrings b/Sources/ParcelUI/Resources/TourDemos.xcstrings index 94452fe4..06037908 100644 --- a/Sources/ParcelUI/Resources/TourDemos.xcstrings +++ b/Sources/ParcelUI/Resources/TourDemos.xcstrings @@ -1,6 +1,16 @@ { "sourceLanguage": "en", "strings": { + "Switch to %@": { + "comment": "Demo card title; placeholder is the destination layout name.", + "extractionState": "manual", + "localizations": { "en": { "stringUnit": { "state": "translated", "value": "Switch to %@" } } } + }, + "demo.layoutShortcutDescription": { + "comment": "VoiceOver layout instruction; first placeholder is destination layout, second is the spoken shortcut.", + "extractionState": "manual", + "localizations": { "en": { "stringUnit": { "state": "translated", "value": "%1$@: %2$@. Choose Layout in the menu bar" } } } + }, "%@ · %@": { "comment": "Shortcut and destination layout shown in the Change layout demo card. First placeholder is the user's configured shortcut glyphs; second is the localized layout name.", "extractionState": "manual", diff --git a/Sources/ParcelUI/Resources/TourSetup.xcstrings b/Sources/ParcelUI/Resources/TourSetup.xcstrings index de1c3cab..c4f4c3fd 100644 --- a/Sources/ParcelUI/Resources/TourSetup.xcstrings +++ b/Sources/ParcelUI/Resources/TourSetup.xcstrings @@ -1,38 +1,61 @@ { "sourceLanguage": "en", "strings": { + "You’re All Set": {"comment": "Completion title after the tour; no terminal punctuation.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "You’re All Set"}}}}, + "Accessibility": {"comment": "Status row for the macOS permission.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Accessibility"}}}}, + "Allowed": {"comment": "Accessibility permission is granted.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Allowed"}}}}, + "Not allowed": {"comment": "Accessibility permission has not been granted.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Not allowed"}}}}, + "Checking…": {"comment": "A status check has not completed yet.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Checking…"}}}}, + "Off": {"comment": "Conflicting system window features are disabled.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Off"}}}}, + "On": {"comment": "A conflicting system window feature is enabled.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "On"}}}}, + "No conflicts": {"comment": "Configured shortcuts have no detected conflicts.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "No conflicts"}}}}, + "⌃⌥ is also VoiceOver’s key. Use ⌥⌘ instead?": {"comment": "Offer an alternate shortcut prefix while VoiceOver is running; glyphs are Control Option and Option Command.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "⌃⌥ is also VoiceOver’s key. Use ⌥⌘ instead?"}}}}, + "Use ⌥⌘": {"comment": "Choose Option Command as the inherited shortcut prefix.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Use ⌥⌘"}}}}, + "Keep ⌃⌥": {"comment": "Keep the existing Control Option prefix.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Keep ⌃⌥"}}}}, + "Use Option Command": {"comment": "Spoken label for the alternate prefix button.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Use Option Command"}}}}, + "Keep Control Option": {"comment": "Spoken label for retaining the default prefix.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Keep Control Option"}}}}, + "Border on active window": {"comment": "Highlight only the focused window.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Border on active window"}}}}, + "Allow Accessibility before tidying your windows.": {"comment": "Skip Tidy routes to the Allow screen when permission is missing.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Allow Accessibility before tidying your windows."}}}}, + "Reopen the tour to try setup again.": {"comment": "Recover from unavailable tour services.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Reopen the tour to try setup again."}}}}, + "Restart setup to choose an available screen or Space.": {"comment": "The selected display or native Space disappeared.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Restart setup to choose an available screen or Space."}}}}, + "Review Settings before applying your choices again.": {"comment": "Configuration application failed.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Review Settings before applying your choices again."}}}}, + "Review Parcel’s notice before tidying again.": {"comment": "Real-window arrangement failed.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Review Parcel’s notice before tidying again."}}}}, + "Review your newer configuration in Settings before tidying again.": {"comment": "Concurrent edits were retained rather than overwritten by rollback.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Review your newer configuration in Settings before tidying again."}}}}, + "Review Parcel’s notice for windows that could not settle: %@.": {"comment": "Placeholder is a localized list of window titles or IDs that failed readback.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Review Parcel’s notice for windows that could not settle: %@."}}}}, + "Review Settings and your windows after incomplete restoration: %@.": {"comment": "Placeholder explains the incomplete rollback.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Review Settings and your windows after incomplete restoration: %@."}}}}, + "Review Settings after setup failed (%1$@) and restoration failed (%2$@).": {"comment": "First placeholder is the original error, second is the rollback error; translators may reorder them.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Review Settings after setup failed (%1$@) and restoration failed (%2$@)."}}}}, "%@ Restoring your previous setup also failed: %@. Review Settings and your windows before trying again.": {"comment": "Tidy rollback error. First placeholder is the original error; second is the restoration error.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "%@ Restoring your previous setup also failed: %@. Review Settings and your windows before trying again."}}}}, - "%@ · %@": {"comment": "Shortcut summary: action name followed by its configured shortcut glyphs or spoken equivalent.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "%@ · %@"}}}}, - "%@: %@": {"comment": "Accessibility status: setting name followed by Ready, Needs attention, or Not verified.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "%@: %@"}}}}, + "%1$@ · %2$@": {"comment": "Shortcut summary: action name followed by its configured shortcut glyphs or spoken equivalent.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "%1$@ · %2$@"}}}}, + "%1$@: %2$@": {"comment": "Accessibility status: setting name followed by Ready, Needs attention, or Not verified.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "%1$@: %2$@"}}}}, "%g points": {"comment": "Highlight width in points; placeholder is a fractional number.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "%g points"}}}}, "%lld points": {"comment": "Highlight width in points; placeholder is an integer.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "%#@points@"}, "substitutions": {"points": {"argNum": 1, "formatSpecifier": "lld", "variations": {"plural": {"one": {"stringUnit": {"state": "translated", "value": "%lld point"}}, "other": {"stringUnit": {"state": "translated", "value": "%lld points"}}}}}}}}}, - "Welcome.": {"comment": "Title of tour screen one.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Welcome."}}}}, - "Allow Parcel.": {"comment": "Title of tour screen two, which requests Accessibility access.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Allow Parcel."}}}}, - "The basics.": {"comment": "Title of tour screen three, introducing everyday window actions.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "The basics."}}}}, - "Power moves.": {"comment": "Title of tour screen four, introducing advanced window actions.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Power moves."}}}}, - "Make it yours.": {"comment": "Title of tour screen five, with draft preferences.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Make it yours."}}}}, - "Tidy.": {"comment": "Title of tour screen six, arranging windows only after confirmation.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Tidy."}}}}, + "Welcome to Parcel": {"comment": "Title of tour screen one.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Welcome to Parcel"}}}}, + "Allow Parcel": {"comment": "Title of tour screen two, which requests Accessibility access.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Allow Parcel"}}}}, + "The Basics": {"comment": "Title of tour screen three, introducing everyday window actions.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "The Basics"}}}}, + "Power Moves": {"comment": "Title of tour screen four, introducing advanced window actions.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Power Moves"}}}}, + "Make It Yours": {"comment": "Title of tour screen five, with draft preferences.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Make It Yours"}}}}, + "Tidy Up": {"comment": "Title of tour screen six, arranging windows only after confirmation.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Tidy Up"}}}}, "Windows that find their place.": {"comment": "Welcome tagline, approved short copy.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Windows that find their place."}}}}, "Parcel needs Accessibility to move your windows.": {"comment": "Permission explanation; Accessibility is the name of the macOS permission.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Parcel needs Accessibility to move your windows."}}}}, - "Choose your style; save it when you tidy.": {"comment": "Personalization is a draft until the final Tidy action.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Choose your style; save it when you tidy."}}}}, + "Pick a style. Tidy saves it.": {"comment": "Personalization is a draft until the final Tidy action.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Pick a style. Tidy saves it."}}}}, "Ready to tidy this screen?": {"comment": "Question before arranging real windows on the selected display.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Ready to tidy this screen?"}}}}, - "Find Parcel in your menu bar anytime.": {"comment": "Completion copy after successful Tidy.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Find Parcel in your menu bar anytime."}}}}, - "Get Started": {"comment": "Primary action on Welcome.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Get Started"}}}}, + "Find Parcel in your menu bar anytime.": {"comment": "Completion copy after successful Tidy Up", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Find Parcel in your menu bar anytime."}}}}, + "Get Started": {"comment": "Primary action on Welcome to Parcel", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Get Started"}}}}, "Open Settings": {"comment": "Primary action opening macOS Accessibility settings.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Open Settings"}}}}, "Continue": {"comment": "Primary action advancing one tour screen.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Continue"}}}}, "Back": {"comment": "Navigate to the previous tour screen.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Back"}}}}, "Skip tour": {"comment": "Skip action; always asks whether to tidy before closing.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Skip tour"}}}}, "Tidy My Workspace": {"comment": "Primary action saving draft preferences and arranging real windows.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Tidy My Workspace"}}}}, "Done": {"comment": "Close the completed tour.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Done"}}}}, - "Practice": {"comment": "Optional link from completion to hands-on learning with real windows.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Practice"}}}}, + "Practice with your windows": {"comment": "Optional link from completion to hands-on learning with real windows.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Practice with your windows"}}}}, "Try shortcuts with your own windows.": {"comment": "VoiceOver hint for the optional Practice link.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Try shortcuts with your own windows."}}}}, "Tidy now?": {"comment": "Title of the confirmation shown when skipping the tour.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Tidy now?"}}}}, "Tidy": {"comment": "Confirm starting automatic tiling with defaults, discarding the tour draft.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Tidy"}}}}, "Not Yet": {"comment": "Dismiss the tour and leave automatic tiling off.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Not Yet"}}}}, - "Start automatic tiling with defaults, or leave it off.": {"comment": "Skip confirmation explaining the two possible outcomes.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Start automatic tiling with defaults, or leave it off."}}}}, + "Start automatic tiling, or leave it off.": {"comment": "Skip confirmation explaining the two possible outcomes.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Start automatic tiling, or leave it off."}}}}, "Tour progress": {"comment": "VoiceOver label for the six progress dots.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Tour progress"}}}}, - "Screen %lld of 6": {"comment": "VoiceOver progress value; placeholder is the current tour screen, 1 through 6.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Screen %lld of 6"}}}}, - "Stage Manager / macOS tiling": {"comment": "Single compatibility row for built-in window arranging features.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Stage Manager / macOS tiling"}}}}, + "Screen %1$lld of %2$lld": {"comment": "VoiceOver progress value; placeholder is the current tour screen, 1 through 6.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Screen %1$lld of %2$lld"}}}}, + "Stage Manager and tiling": {"comment": "Single compatibility row for built-in window arranging features.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Stage Manager and tiling"}}}}, "Shortcuts": {"comment": "Compatibility row checking configured keyboard shortcuts.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Shortcuts"}}}}, "Turn Off…": {"comment": "Open Desktop & Dock settings to disable conflicting system window features.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Turn Off…"}}}}, "Choose Another Prefix": {"comment": "Open shortcut preferences to fix a shortcut clash.", "localizations": {"en": {"stringUnit": {"state": "translated", "value": "Choose Another Prefix"}}}}, diff --git a/Sources/ParcelUI/Tour/LearningPanel.swift b/Sources/ParcelUI/Tour/LearningPanel.swift index 90dcb3a6..f03fd871 100644 --- a/Sources/ParcelUI/Tour/LearningPanel.swift +++ b/Sources/ParcelUI/Tour/LearningPanel.swift @@ -7,20 +7,25 @@ import QuartzCore final class LearningPanel: NSPanel { let interactive: Bool - init(title: String, interactive: Bool) { + init(title: String, interactive: Bool, setupWindow: Bool = false) { self.interactive = interactive - super.init(contentRect: .zero, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false) + super.init( + contentRect: .zero, + styleMask: setupWindow ? [.titled, .fullSizeContentView] : [.borderless, .nonactivatingPanel], + backing: .buffered, defer: false) self.title = title isReleasedWhenClosed = false isOpaque = false backgroundColor = .clear - hasShadow = false + hasShadow = setupWindow + titlebarAppearsTransparent = setupWindow + titleVisibility = setupWindow ? .hidden : .visible ignoresMouseEvents = !interactive - isFloatingPanel = true - becomesKeyOnlyIfNeeded = true + isFloatingPanel = !setupWindow + becomesKeyOnlyIfNeeded = !setupWindow hidesOnDeactivate = false animationBehavior = .none - level = .floating + level = setupWindow ? .normal : .floating collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .stationary] collectionBehavior.insert(interactive ? .participatesInCycle : .ignoresCycle) setAccessibilityLabel(title) @@ -39,6 +44,19 @@ final class LearningPanel: NSPanel { @MainActor enum LearningMotion { + static func resize(_ panel: NSPanel, to frame: CGRect, configuration: MotionConfiguration) { + let motion = OverlayMotion(configuration: configuration, accessibility: .system) + guard panel.isVisible, motion.behavior == .animate else { + panel.setFrame(frame, display: true) + return + } + NSAnimationContext.runAnimationGroup { context in + context.duration = motion.spec(.drop).duration + context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) + panel.animator().setFrame(frame, display: true) + } + } + static func show(_ layer: CALayer, token: MotionToken, configuration: MotionConfiguration) { layer.removeAllAnimations() let motion = OverlayMotion(configuration: configuration, accessibility: .system) diff --git a/Sources/ParcelUI/Tour/TourAllowView.swift b/Sources/ParcelUI/Tour/TourAllowView.swift index 7676594f..f9a03aaa 100644 --- a/Sources/ParcelUI/Tour/TourAllowView.swift +++ b/Sources/ParcelUI/Tour/TourAllowView.swift @@ -2,36 +2,81 @@ import SwiftUI struct TourAllowView: View { let controller: WindowLearningController - private var setup: TourSetupController { controller.setup } + @Bindable private var setup: TourSetupController + + init(controller: WindowLearningController) { + self.controller = controller + setup = controller.setup + } var body: some View { - VStack(alignment: .leading, spacing: 18) { - Image(systemName: "hand.raised.fill") - .font(.largeTitle) - .accessibilityHidden(true) - Text(TourText.text("Parcel needs Accessibility to move your windows.")) + VStack(alignment: .leading, spacing: 16) { + Label(TourText.text("Parcel needs Accessibility to move your windows."), systemImage: "accessibility") .fixedSize(horizontal: false, vertical: true) - TourCheckRow( - title: "Stage Manager / macOS tiling", ready: setup.system?.isClear == true, known: setup.system != nil, - fix: "Turn Off…", action: openSystem) - TourCheckRow( - title: "Shortcuts", - ready: setup.shortcuts != nil && !setup.hasShortcutClash - && setup.shortcuts?.limitations.isEmpty == true, known: setup.shortcuts != nil, - fix: "Choose Another Prefix", action: openShortcuts) - Toggle(TourText.text("Open at login"), isOn: loginBinding) - .disabled(setup.login == nil || setup.isBusy) - .accessibilityIdentifier("tour.login") - if setup.login == .requiresApproval { - Button(TourText.text("Approve in Login Items"), action: openLogin) + Form { + TourCheckRow( + title: "Accessibility", + status: TourText.text(setup.permission == .granted ? "Allowed" : "Not allowed"), + ready: setup.permission == .granted, known: setup.permission != .checking, + fix: "Open Settings", action: openAccessibility) + TourCheckRow( + title: "Stage Manager and tiling", status: systemStatus, + ready: setup.system?.isClear == true, known: setup.system != nil, + fix: "Turn Off…", action: openSystem) + TourCheckRow( + title: "Shortcuts", status: shortcutStatus, + ready: setup.shortcuts != nil && !setup.hasShortcutClash + && setup.shortcuts?.limitations.isEmpty == true, + known: setup.shortcuts != nil, fix: "Choose Another Prefix", action: openShortcuts) + if setup.showsVoiceOverChoice { + VStack(alignment: .leading, spacing: 8) { + Text(TourText.text("⌃⌥ is also VoiceOver’s key. Use ⌥⌘ instead?")) + .fixedSize(horizontal: false, vertical: true) + HStack { + Button(TourText.text("Use ⌥⌘")) { choosePrefix(true) } + .accessibilityLabel(TourText.text("Use Option Command")) + .accessibilityIdentifier("tour.voiceOver.alternate") + Button(TourText.text("Keep ⌃⌥")) { choosePrefix(false) } + .accessibilityLabel(TourText.text("Keep Control Option")) + .accessibilityIdentifier("tour.voiceOver.keep") + } + } + } + Toggle(TourText.text("Open at login"), isOn: $setup.openAtLogin) + .onChange(of: setup.loginRequest) { _, enabled in + guard let enabled else { return } + controller.runSetup { try await setup.setOpenAtLogin(enabled) } + } + .accessibilityIdentifier("tour.login") + if setup.login == .requiresApproval { + Button(TourText.text("Approve in Login Items"), action: openLogin) + } } + .formStyle(.grouped) + .fixedSize(horizontal: false, vertical: true) + } + } + + private var systemStatus: String { + guard let system = setup.system else { return TourText.text("Checking…") } + if system.isClear { return TourText.text("Off") } + return TourText.text(system.stageManager == true || system.nativeTiling == true ? "On" : "Not verified") + } + + private var shortcutStatus: String { + guard let shortcuts = setup.shortcuts else { return TourText.text("Checking…") } + if let warning = shortcuts.warnings.first { + return warning.messages.first ?? TourShortcutWarningPresentation(warning: warning).title } + if let notice = shortcuts.modeNotices.first { return notice } + if let limitation = shortcuts.limitations.first { return limitation } + return TourText.text("No conflicts") } - private var loginBinding: Binding { - Binding(get: { setup.login == .enabled || setup.login == .requiresApproval }, set: { setLogin($0) }) + private func choosePrefix(_ alternate: Bool) { + controller.runSetup { try await setup.chooseVoiceOverPrefix(useAlternate: alternate) } } - private func setLogin(_ enabled: Bool) { controller.runSetup { try await setup.setOpenAtLogin(enabled) } } + private func openAccessibility() { controller.changeSetup { try setup.openAccessibilitySettings() } } private func openSystem() { controller.changeSetup { try setup.openSettings(for: .personalize) } } private func openShortcuts() { controller.changeSetup { try setup.openSettings(for: .basics) } } private func openLogin() { controller.changeSetup { try setup.openSettings(for: .allow) } } diff --git a/Sources/ParcelUI/Tour/TourCheckRow.swift b/Sources/ParcelUI/Tour/TourCheckRow.swift index 6e101373..98ed05fb 100644 --- a/Sources/ParcelUI/Tour/TourCheckRow.swift +++ b/Sources/ParcelUI/Tour/TourCheckRow.swift @@ -2,30 +2,45 @@ import SwiftUI struct TourCheckRow: View { let title: String + let status: String let ready: Bool let known: Bool - let fix: String - let action: () -> Void + var fix: String? + var action: () -> Void = {} var body: some View { - ViewThatFits(in: .horizontal) { - HStack { - label - Spacer() - if !ready { Button(TourText.text(fix), action: action) } + VStack(alignment: .leading, spacing: 6) { + ViewThatFits(in: .horizontal) { + HStack(alignment: .firstTextBaseline) { + label + Spacer(minLength: 12) + stateText + } + VStack(alignment: .leading, spacing: 4) { + label + stateText + } } - VStack(alignment: .leading, spacing: 8) { - label - if !ready { Button(TourText.text(fix), action: action) } + if let fix, known && !ready { + Button(TourText.text(fix), action: action) + .padding(.leading, 24) } } } + private var stateText: some View { + Text(status) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + private var label: some View { - Label(TourText.text(title), systemImage: ready ? "checkmark.circle.fill" : "exclamationmark.circle") - .accessibilityLabel( - String( - format: TourText.text("%@: %@"), TourText.text(title), - TourText.text(ready ? "Ready" : known ? "Needs attention" : "Not verified"))) + Label { + Text(TourText.text(title)) + } icon: { + Image(systemName: ready ? "checkmark.circle.fill" : known ? "exclamationmark.triangle.fill" : "clock") + .foregroundStyle(ready ? Color.green : known ? Color.orange : Color.secondary) + .accessibilityHidden(true) + } } } diff --git a/Sources/ParcelUI/Tour/TourPersonalizationView.swift b/Sources/ParcelUI/Tour/TourPersonalizationView.swift index a36bebf9..6e1fc343 100644 --- a/Sources/ParcelUI/Tour/TourPersonalizationView.swift +++ b/Sources/ParcelUI/Tour/TourPersonalizationView.swift @@ -3,50 +3,50 @@ import SwiftUI struct TourPersonalizationView: View { let controller: WindowLearningController - private var setup: TourSetupController { controller.setup } + @Bindable private var setup: TourSetupController + + init(controller: WindowLearningController) { + self.controller = controller + setup = controller.setup + } var body: some View { if let draft = setup.draft { - VStack(alignment: .leading, spacing: 18) { + VStack(alignment: .leading, spacing: 16) { TourMiniature( configuration: controller.configuration, layout: draft.layout, windowCount: draft.windowCount, kind: .layout ) - .frame(height: 160) - .accessibilityLabel(TourText.text("Draft layout preview")) - Text(TourText.text("Choose your style; save it when you tidy.")) - Picker(TourText.text("Layout"), selection: binding(\.layout, value: draft.layout)) { - ForEach(ConfigLayout.allCases, id: \.self) { Text($0.settingsTitle).tag($0) } - } - .accessibilityIdentifier("tour.layout") - Picker(TourText.text("Windows per screen"), selection: binding(\.windowCount, value: draft.windowCount)) - { - ForEach(1...5, id: \.self) { Text($0.formatted()).tag($0) } + .frame(height: TourSetupView.miniatureHeight) + .frame(maxWidth: .infinity) + Text(TourText.text("Pick a style. Tidy saves it.")) + Form { + Picker(TourText.text("Layout"), selection: $setup.draftLayout) { + ForEach(ConfigLayout.allCases, id: \.self) { Text($0.settingsTitle).tag($0) } + } + .accessibilityIdentifier("tour.layout") + Stepper(value: $setup.draftWindowCount, in: 1...5) { + LabeledContent(TourText.text("Windows per screen"), value: draft.windowCount.formatted()) + } + .accessibilityIdentifier("tour.count") + Picker(TourText.text("Highlight style"), selection: $setup.draftHighlight) { + ForEach(ConfigHighlight.allCases, id: \.self) { Text(highlightTitle($0)).tag($0) } + } + .accessibilityIdentifier("tour.highlight") + Picker(TourText.text("When full"), selection: $setup.draftWhenFull) { + Text(TourText.text("Stack")).tag(ConfigWhenFull.stack) + Text(TourText.text("Float")).tag(ConfigWhenFull.float) + } + .pickerStyle(.segmented) + .accessibilityIdentifier("tour.overflow") } - .accessibilityIdentifier("tour.count") - Picker(TourText.text("Highlight style"), selection: binding(\.highlight, value: draft.highlight)) { - ForEach(ConfigHighlight.allCases, id: \.self) { Text($0.label).tag($0) } - } - .accessibilityIdentifier("tour.highlight") - Picker(TourText.text("When full"), selection: binding(\.whenFull, value: draft.whenFull)) { - Text(TourText.text("Stack")).tag(ConfigWhenFull.stack) - Text(TourText.text("Float")).tag(ConfigWhenFull.float) - } - .pickerStyle(.segmented) - .accessibilityIdentifier("tour.overflow") + .formStyle(.grouped) + .fixedSize(horizontal: false, vertical: true) } } } - private func binding(_ path: WritableKeyPath, value: Value) -> Binding { - Binding( - get: { setup.draft?[keyPath: path] ?? value }, - set: { value in - controller.changeSetup { - guard var draft = setup.draft else { throw TourSetupFailure.notReady } - draft[keyPath: path] = value - try setup.updateDraft(draft) - } - }) + private func highlightTitle(_ highlight: ConfigHighlight) -> String { + highlight == .active ? TourText.text("Border on active window") : highlight.label } } diff --git a/Sources/ParcelUI/Tour/TourSetup.swift b/Sources/ParcelUI/Tour/TourSetup.swift index 46a9e850..f96c9e17 100644 --- a/Sources/ParcelUI/Tour/TourSetup.swift +++ b/Sources/ParcelUI/Tour/TourSetup.swift @@ -8,7 +8,16 @@ public enum TourSetupStep: String, CaseIterable, Sendable { case welcome, allow, basics, powerMoves, personalize, tidy, complete public static let screens: [Self] = [.welcome, .allow, .basics, .powerMoves, .personalize, .tidy] - public var screenIndex: Int { Self.screens.firstIndex(of: self) ?? 5 } + public var screenIndex: Int { + switch self { + case .welcome: 0 + case .allow: 1 + case .basics: 2 + case .powerMoves: 3 + case .personalize: 4 + case .tidy, .complete: 5 + } + } } public enum TourLoginStatus: Equatable, Sendable { @@ -109,6 +118,7 @@ public struct TourSetupActions { public var permissionStatus: () async -> PermissionStatus public var openAccessibilitySettings: () throws -> Void public var skip: (Bool) async throws -> Void + public var useAlternatePrefix: () async throws -> Void public init( checkShortcuts: @escaping () async throws -> TourShortcutCheck, @@ -122,7 +132,8 @@ public struct TourSetupActions { openLoginSettings: @escaping () throws -> Void, permissionStatus: @escaping () async -> PermissionStatus, openAccessibilitySettings: @escaping () throws -> Void = { throw TourSetupFailure.unavailable }, - skip: @escaping (Bool) async throws -> Void = { _ in throw TourSetupFailure.unavailable } + skip: @escaping (Bool) async throws -> Void = { _ in throw TourSetupFailure.unavailable }, + useAlternatePrefix: @escaping () async throws -> Void = { throw TourSetupFailure.unavailable } ) { self.checkShortcuts = checkShortcuts self.checkSystem = checkSystem @@ -136,6 +147,7 @@ public struct TourSetupActions { self.permissionStatus = permissionStatus self.openAccessibilitySettings = openAccessibilitySettings self.skip = skip + self.useAlternatePrefix = useAlternatePrefix } } @@ -147,11 +159,26 @@ public final class TourSetupController { public var isSkipConfirmationPresented = false private var skipWasRequested = false private var confirmedSkipChoice: Bool? + private var startsAtWelcome = false private var enableLoginByDefault = false private var autoAdvancePermission = true private var hasAppliedLoginDefault: Bool @ObservationIgnored private let onLoginDefaultApplied: @MainActor () -> Void - public private(set) var track = TourTrack.keyboard + public var track = TourTrack.keyboard + private var loginSelection = false + public private(set) var loginRequest: Bool? + public var openAtLogin: Bool { + get { loginSelection } + set { + loginSelection = newValue + loginRequest = newValue + } + } + public private(set) var voiceOverEnabled = false + public private(set) var voiceOverChoiceMade = false + private var loginDraftPending = false + private var isRefreshingAllow = false + public var showsVoiceOverChoice: Bool { voiceOverEnabled && !voiceOverChoiceMade } public private(set) var shortcuts: TourShortcutCheck? public private(set) var system: TourSystemCheck? public private(set) var login: TourLoginStatus? @@ -171,9 +198,10 @@ public final class TourSetupController { self.onLoginDefaultApplied = onLoginDefaultApplied } - public func begin(_ track: TourTrack, firstRun: Bool = false) { + public func begin(_ track: TourTrack, firstRun: Bool = false, defaultOpenAtLogin: Bool = false) { guard !isBusy else { return } self.track = track + startsAtWelcome = firstRun step = firstRun ? .welcome : .basics shortcuts = nil system = nil @@ -181,7 +209,11 @@ public final class TourSetupController { draft = nil didTidy = false undo = nil - enableLoginByDefault = firstRun + enableLoginByDefault = defaultOpenAtLogin && !hasAppliedLoginDefault + loginDraftPending = false + loginSelection = false + loginRequest = nil + voiceOverChoiceMade = false autoAdvancePermission = true isSkipConfirmationPresented = false skipWasRequested = false @@ -207,7 +239,18 @@ public final class TourSetupController { public func resolveSkip(tidyNow: Bool) async throws { guard isSkipConfirmationPresented || confirmedSkipChoice == tidyNow else { throw TourSetupFailure.notReady } + if tidyNow, try await requireActions().permissionStatus() != .granted { + step = .allow + autoAdvancePermission = false + isSkipConfirmationPresented = false + skipWasRequested = false + confirmedSkipChoice = nil + try await checkCurrentStep() + errorMessage = TourSetupFailure.accessibilityRequired.localizedDescription + throw TourSetupFailure.accessibilityRequired + } try await perform { + if tidyNow { try await commitLoginDraft() } try await requireActions().skip(tidyNow) draft = nil didTidy = tidyNow @@ -220,7 +263,7 @@ public final class TourSetupController { public func restart() async throws { guard !isBusy else { throw TourSetupFailure.busy } - step = enableLoginByDefault ? .welcome : .basics + step = startsAtWelcome ? .welcome : .basics shortcuts = nil system = nil login = nil @@ -239,10 +282,7 @@ public final class TourSetupController { try await checkCurrentStep() } - public func dismiss() { - guard !isBusy else { return } - isPresented = false - } + public func dismiss() { isPresented = false } public var canContinue: Bool { guard !isBusy else { return false } @@ -256,38 +296,97 @@ public final class TourSetupController { } public func checkCurrentStep() async throws { - guard step == .allow || step == .personalize else { return } - try await perform { + switch step { + case .allow: try await refreshAllowChecks() + case .personalize: + if draft == nil { + var values = try requireActions().personalization() + values.windowCount = min(5, max(1, values.windowCount)) + draft = values + } + case .welcome, .basics, .powerMoves, .tidy, .complete: break + } + } + + public func refreshAllowChecks() async throws { + guard isPresented, step == .allow, !isRefreshingAllow else { return } + isRefreshingAllow = true + defer { isRefreshingAllow = false } + do { let actions = try requireActions() - switch step { - case .allow: - permission = await actions.permissionStatus() - system = nil - system = try await actions.checkSystem() - shortcuts = nil - shortcuts = try await actions.checkShortcuts() - login = try actions.loginStatus() - if enableLoginByDefault && !hasAppliedLoginDefault { - if login == .disabled { login = try await actions.setOpenAtLogin(true) } - hasAppliedLoginDefault = true - onLoginDefaultApplied() - } - if permission == .granted && autoAdvancePermission { step = .basics } - case .personalize: - if draft == nil { - var values = try actions.personalization() - values.windowCount = min(5, max(1, values.windowCount)) - draft = values + let permission = await actions.permissionStatus() + try Task.checkCancellation() + guard isPresented, step == .allow else { return } + self.permission = permission + let system = try await actions.checkSystem() + try Task.checkCancellation() + guard isPresented, step == .allow else { return } + self.system = system + let shortcuts = try await actions.checkShortcuts() + try Task.checkCancellation() + guard isPresented, step == .allow else { return } + self.shortcuts = shortcuts + login = try actions.loginStatus() + if !loginDraftPending { + loginSelection = login != .disabled + if login != .disabled { enableLoginByDefault = false } + if enableLoginByDefault && !hasAppliedLoginDefault && login == .disabled { + loginSelection = true + loginDraftPending = true } - case .welcome, .basics, .powerMoves, .tidy, .complete: break } + errorMessage = nil + if self.permission == .granted && autoAdvancePermission && !isBusy && !showsVoiceOverChoice { + try await leaveAllow() + } + } catch is CancellationError { + throw CancellationError() + } catch { + errorMessage = error.localizedDescription + throw error } } public func refreshPermission() async throws { - guard step == .allow, !isBusy else { return } - if permission != .granted { autoAdvancePermission = true } - try await checkCurrentStep() + guard isPresented, step == .allow else { return } + let permission = try await requireActions().permissionStatus() + try Task.checkCancellation() + guard isPresented, step == .allow else { return } + let newlyGranted = self.permission != .granted && permission == .granted + self.permission = permission + if newlyGranted, errorMessage == TourSetupFailure.accessibilityRequired.localizedDescription { + errorMessage = nil + } + if newlyGranted && autoAdvancePermission && canContinue && !showsVoiceOverChoice { + try await leaveAllow() + } + } + + public func updateVoiceOver(_ enabled: Bool) { voiceOverEnabled = enabled } + + public func chooseVoiceOverPrefix(useAlternate: Bool) async throws { + guard showsVoiceOverChoice else { throw TourSetupFailure.notReady } + try await perform { + if useAlternate { + try await requireActions().useAlternatePrefix() + shortcuts = try await requireActions().checkShortcuts() + } + voiceOverChoiceMade = true + } + } + + private func leaveAllow() async throws { + try await perform { try await commitLoginDraft() } + guard isPresented, step == .allow else { return } + step = .basics + } + + private func commitLoginDraft() async throws { + guard loginDraftPending else { return } + login = try await requireActions().setOpenAtLogin(openAtLogin) + loginDraftPending = false + hasAppliedLoginDefault = true + onLoginDefaultApplied() } public func openAccessibilitySettings() throws { @@ -310,6 +409,7 @@ public final class TourSetupController { guard canContinue, let index = TourSetupStep.allCases.firstIndex(of: step) else { throw TourSetupFailure.notReady } + if step == .allow { try await leaveAllow(); return } step = TourSetupStep.allCases[index + 1] if step == .allow { autoAdvancePermission = true } try await checkCurrentStep() @@ -324,10 +424,41 @@ public final class TourSetupController { self.draft = draft } + public var draftLayout: ConfigLayout { + get { requireDraft().layout } + set { editDraft(\.layout, newValue) } + } + public var draftWindowCount: Int { + get { requireDraft().windowCount } + set { editDraft(\.windowCount, newValue) } + } + public var draftHighlight: ConfigHighlight { + get { requireDraft().highlight } + set { editDraft(\.highlight, newValue) } + } + public var draftWhenFull: ConfigWhenFull { + get { requireDraft().whenFull } + set { editDraft(\.whenFull, newValue) } + } + + private func requireDraft() -> TourPersonalization { + guard let draft else { preconditionFailure("Personalization controls require a draft") } + return draft + } + + private func editDraft(_ path: WritableKeyPath, _ value: Value) { + var draft = requireDraft() + draft[keyPath: path] = value + do { try updateDraft(draft) } catch { errorMessage = error.localizedDescription } + } + public func setOpenAtLogin(_ enabled: Bool) async throws { guard step == .allow else { throw TourSetupFailure.notReady } + loginRequest = nil try await perform { login = try await requireActions().setOpenAtLogin(enabled) + loginSelection = login != .disabled + loginDraftPending = false hasAppliedLoginDefault = true onLoginDefaultApplied() } @@ -339,6 +470,8 @@ public final class TourSetupController { let actions = try requireActions() system = try await actions.checkSystem() guard system?.isClear == true else { throw TourSetupFailure.systemConflict } + try await commitLoginDraft() + try Task.checkCancellation() undo = try await actions.tidy(draft) didTidy = true step = .complete @@ -369,7 +502,12 @@ public final class TourSetupController { isBusy = true errorMessage = nil defer { isBusy = false } - do { try await operation() } catch { + do { + try Task.checkCancellation() + try await operation() + } catch is CancellationError { + throw CancellationError() + } catch { errorMessage = error.localizedDescription throw error } @@ -378,6 +516,7 @@ public final class TourSetupController { 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) @@ -385,22 +524,23 @@ public enum TourSetupFailure: LocalizedError { public var errorDescription: String? { switch self { - case .unavailable: TourText.text("Tour setup is unavailable. Reopen the tour and try again.") + case .unavailable: TourText.text("Reopen the tour to try setup again.") + case .accessibilityRequired: TourText.text("Allow Accessibility before tidying your windows.") case .notReady: TourText.text("Complete this step before continuing.") case .invalidDraft: TourText.text("Choose a valid window count and a highlight width between 2 and 6 points.") case .busy: TourText.text("Wait for the current tour action to finish.") case .systemConflict: TourText.text("Turn off Stage Manager and macOS window tiling before tidying.") case .workspaceUnavailable: - TourText.text("The selected screen or Space is no longer available. Start setup again.") - case .applyFailed: TourText.text("Your choices could not be applied. Review the configuration in Settings.") - case .tidyFailed: TourText.text("Some windows could not be tidied. Review Parcel’s notice, then try again.") + TourText.text("Restart setup to choose an available screen or Space.") + case .applyFailed: TourText.text("Review Settings before applying your choices again.") + case .tidyFailed: TourText.text("Review Parcel’s notice before tidying again.") case .configurationChanged: TourText.text( - "The configuration changed after Tidy started. Your newer edits were not overwritten. Review Settings before trying again." + "Review your newer configuration in Settings before tidying again." ) case .unsettledWindows(let windows, let titles): String( - format: TourText.text("These windows could not settle: %@. Review Parcel’s notice, then try again."), + format: TourText.text("Review Parcel’s notice for windows that could not settle: %@."), windows.map { id in if let title = titles[id], !title.isEmpty { return title } return String.localizedStringWithFormat(TourText.text("Window %lld"), Int64(id.rawValue)) @@ -408,12 +548,12 @@ public enum TourSetupFailure: LocalizedError { case .restorationIncomplete(let reason): String( format: TourText.text( - "Your previous setup could not be fully restored: %@. Review Settings and your windows before trying again." + "Review Settings and your windows after incomplete restoration: %@." ), reason) case .restorationFailed(let operation, let restoration): String( format: TourText.text( - "%@ Restoring your previous setup also failed: %@. Review Settings and your windows before trying again." + "Review Settings after setup failed (%1$@) and restoration failed (%2$@)." ), operation, restoration) } } diff --git a/Sources/ParcelUI/Tour/TourSetupView.swift b/Sources/ParcelUI/Tour/TourSetupView.swift index a770591e..907805d7 100644 --- a/Sources/ParcelUI/Tour/TourSetupView.swift +++ b/Sources/ParcelUI/Tour/TourSetupView.swift @@ -4,6 +4,8 @@ struct TourSetupView: View { let controller: WindowLearningController @Bindable private var setup: TourSetupController @Environment(\.dynamicTypeSize) private var dynamicTypeSize + @AccessibilityFocusState private var titleFocused: Bool + static let miniatureHeight: CGFloat = 160 init(controller: WindowLearningController) { self.controller = controller @@ -26,18 +28,21 @@ struct TourSetupView: View { .accessibilityElement(children: .ignore) .accessibilityLabel(TourText.text("Tour progress")) .accessibilityValue( - String.localizedStringWithFormat(TourText.text("Screen %lld of 6"), setup.step.screenIndex + 1)) + String.localizedStringWithFormat( + TourText.text("Screen %1$lld of %2$lld"), setup.step.screenIndex + 1, TourSetupStep.screens.count)) - ScrollView { + Group { VStack(alignment: .leading, spacing: 16) { Text(TourText.text(setup.step.title)) .font(.title.bold()) .accessibilityAddTraits(.isHeader) .accessibilityIdentifier("tour.title") + .accessibilityFocused($titleFocused) switch setup.step { case .welcome: TourMiniature(configuration: controller.configuration, layout: .grid, windowCount: 4) - .frame(height: 210) + .frame(height: Self.miniatureHeight) + .frame(maxWidth: .infinity) Text(TourText.text("Windows that find their place.")) case .allow: TourAllowView(controller: controller) @@ -53,13 +58,14 @@ struct TourSetupView: View { configuration: controller.configuration, layout: setup.draft?.layout ?? .grid, windowCount: setup.draft?.windowCount ?? 4, kind: .layout ) - .frame(height: 210) + .frame(height: Self.miniatureHeight) + .frame(maxWidth: .infinity) Text( TourText.text( setup.step == .complete ? "Find Parcel in your menu bar anytime." : "Ready to tidy this screen?")) if setup.step == .complete, setup.didTidy { - Button(TourText.text("Practice"), action: controller.finishSetup) + Button(TourText.text("Practice with your windows"), action: controller.finishSetup) .buttonStyle(.link) .accessibilityHint(TourText.text("Try shortcuts with your own windows.")) .accessibilityIdentifier("tour.practice") @@ -103,9 +109,12 @@ struct TourSetupView: View { Button(TourText.text("Tidy"), action: skipAndTidy).keyboardShortcut(.defaultAction) Button(TourText.text("Not Yet"), role: .cancel, action: skipWithoutTidy) } message: { - Text(TourText.text("Start automatic tiling with defaults, or leave it off.")) + Text(TourText.text("Start automatic tiling, or leave it off.")) + } + .onChange(of: setup.step, initial: true) { + titleFocused = true + controller.setupScreenChanged() } - .task(id: setup.step) { await refreshAllow() } } private var navigationLayout: AnyLayout { @@ -153,29 +162,18 @@ struct TourSetupView: View { } } - private func refreshAllow() async { - guard setup.step == .allow else { return } - while setup.isPresented && setup.step == .allow && !Task.isCancelled { - do { - try await setup.refreshPermission() - try await Task.sleep(for: .seconds(1)) - } catch is CancellationError { return } catch { - controller.reportSetupFailure(error) - return - } - } - } } extension TourSetupStep { var title: String { switch self { - case .welcome: "Welcome." - case .allow: "Allow Parcel." - case .basics: "The basics." - case .powerMoves: "Power moves." - case .personalize: "Make it yours." - case .tidy, .complete: "Tidy." + case .welcome: "Welcome to Parcel" + case .allow: "Allow Parcel" + case .basics: "The Basics" + case .powerMoves: "Power Moves" + case .personalize: "Make It Yours" + case .tidy: "Tidy Up" + case .complete: "You’re All Set" } } diff --git a/Sources/ParcelUI/Tour/TourTrackPicker.swift b/Sources/ParcelUI/Tour/TourTrackPicker.swift index 2acd915e..976f7b64 100644 --- a/Sources/ParcelUI/Tour/TourTrackPicker.swift +++ b/Sources/ParcelUI/Tour/TourTrackPicker.swift @@ -1,10 +1,10 @@ import SwiftUI struct TourTrackPicker: View { - let setup: TourSetupController + @Bindable var setup: TourSetupController var body: some View { - Picker(TourText.text("Learn with"), selection: selection) { + Picker(TourText.text("Learn with"), selection: $setup.track) { Text(TourText.text("Keyboard")).tag(TourTrack.keyboard) Text(TourText.text("Mouse")).tag(TourTrack.mouse) } @@ -12,8 +12,4 @@ struct TourTrackPicker: View { .accessibilityLabel(TourText.text("Learn with keyboard or mouse")) .accessibilityIdentifier("tour.track") } - - private var selection: Binding { - Binding(get: { setup.track }, set: { setup.selectTrack($0) }) - } } diff --git a/Sources/ParcelUI/Tour/TourView.swift b/Sources/ParcelUI/Tour/TourView.swift index cb2a9ba0..fb10fad3 100644 --- a/Sources/ParcelUI/Tour/TourView.swift +++ b/Sources/ParcelUI/Tour/TourView.swift @@ -28,7 +28,13 @@ struct TourView: View { } } } - .frame(width: 480, height: 600, alignment: .topLeading) + .frame(width: 440, alignment: .topLeading) + .fixedSize(horizontal: false, vertical: true) + .onGeometryChange(for: CGSize.self) { + $0.size + } action: { + controller.resizePanel(to: $0) + } .background(Color(nsColor: .windowBackgroundColor)) .overlay(RoundedRectangle(cornerRadius: 12).stroke(.primary, lineWidth: contrast == .increased ? 2 : 1)) .clipShape(RoundedRectangle(cornerRadius: 12)) diff --git a/Sources/ParcelUI/Tour/WindowLearningController.swift b/Sources/ParcelUI/Tour/WindowLearningController.swift index 3d731ba4..8762c045 100644 --- a/Sources/ParcelUI/Tour/WindowLearningController.swift +++ b/Sources/ParcelUI/Tour/WindowLearningController.swift @@ -2,6 +2,7 @@ public import AppKit import Observation public import ParcelConfig public import ParcelCore +import ParcelPlatform import SwiftUI @MainActor @@ -12,6 +13,7 @@ public final class WindowLearningController { public func beginSetup(_ track: TourTrack) { setup.begin(track) + observeSetupChanges() runSetup { try await self.setup.checkCurrentStep() } } @@ -23,6 +25,7 @@ public final class WindowLearningController { defaults.set(true, forKey: "onboardingCompleted") onTourResolved?() if hide { + stopSetupObservations() setup.dismiss() panel?.orderOut(nil) } @@ -32,6 +35,7 @@ public final class WindowLearningController { guard setup.step == .complete, setup.didTidy, !setup.isBusy else { return } completeTour(hide: false) let track = setup.track + stopSetupObservations() setup.dismiss() tour.start(track: track, state: state, configuration: configuration) persist() @@ -40,10 +44,16 @@ public final class WindowLearningController { func reportSetupFailure(_ error: any Error) { failure(error) } func runSetup(_ operation: @escaping @MainActor () async throws -> Void) { - Task { @MainActor in + guard !setup.isBusy else { return } + setupTask?.cancel() + setupTask = Task { @MainActor in do { try await operation() - if setup.step == .personalize { positionPanel() } + try Task.checkCancellation() + resizePanel() + positionPanel() + } catch is CancellationError { + return } catch { failure(error) } } } @@ -65,6 +75,15 @@ public final class WindowLearningController { private let failure: @MainActor (any Error) -> Void private let requestKeyboardFocus: @MainActor (NSPanel) -> Void @ObservationIgnored private var panel: LearningPanel? + @ObservationIgnored private var setupTask: Task? + @ObservationIgnored private var refreshTask: Task? + @ObservationIgnored private var refreshGeneration: UUID? + @ObservationIgnored private var pendingFullRefresh = false + @ObservationIgnored private var pendingPermissionRefresh = false + @ObservationIgnored private var trustObservation: AccessibilityTrustObservation? + @ObservationIgnored private var voiceOverObservation: NSKeyValueObservation? + @ObservationIgnored private var activationObservation: (any NSObjectProtocol)? + @ObservationIgnored private var workspaceObservations: [any NSObjectProtocol] = [] public convenience init( defaults: UserDefaults = .standard, @@ -114,26 +133,124 @@ public final class WindowLearningController { } } - public func present(afterOnboarding: Bool = false) { + public func present(afterOnboarding: Bool = false, defaultOpenAtLogin: Bool = false) { if afterOnboarding, defaults.bool(forKey: "guidedTour.v2.completed") { return } _ = tour.offer() tour.pause() - setup.begin(.keyboard, firstRun: afterOnboarding) + setup.begin(.keyboard, firstRun: afterOnboarding, defaultOpenAtLogin: defaultOpenAtLogin) + observeSetupChanges() runSetup { try await self.setup.checkCurrentStep() } persist() if panel == nil { - let panel = LearningPanel(title: UIStrings.text("Guided Tour"), interactive: true) - panel.contentView = NSHostingView(rootView: TourView(controller: self)) - panel.setContentSize(NSSize(width: 480, height: 600)) + let panel = LearningPanel(title: UIStrings.text("Guided Tour"), interactive: true, setupWindow: true) + let host = NSHostingView(rootView: TourView(controller: self)) + host.sizingOptions = [.preferredContentSize, .intrinsicContentSize] + host.wantsLayer = true + panel.contentView = host panel.isMovableByWindowBackground = true panel.center() self.panel = panel } + resizePanel() positionPanel() NSApplication.shared.activate() panel?.makeKeyAndOrderFront(nil) } + func setupScreenChanged() { + resizePanel() + announce(TourText.text(setup.step.title)) + if setup.step == .complete, setup.didTidy, let layer = panel?.contentView?.layer { + LearningMotion.show(layer, token: .drop, configuration: configuration.motion) + } + } + + func resizePanel() { + guard let content = panel?.contentView else { return } + content.layoutSubtreeIfNeeded() + resizePanel(to: content.fittingSize) + } + + func resizePanel(to size: CGSize) { + guard let panel, size.width > 0, size.height > 0 else { return } + let frameSize = panel.frameRect(forContentRect: CGRect(origin: .zero, size: size)).size + guard panel.frame.size != frameSize else { return } + let frame = CGRect( + x: panel.frame.midX - frameSize.width / 2, y: panel.frame.maxY - frameSize.height, + width: frameSize.width, height: frameSize.height) + LearningMotion.resize(panel, to: frame, configuration: configuration.motion) + } + + private func observeSetupChanges() { + guard activationObservation == nil else { return } + setup.updateVoiceOver(NSWorkspace.shared.isVoiceOverEnabled) + trustObservation = AccessibilityTrustObserver.shared.observe { [weak self] in + self?.refreshSetup(permissionOnly: true) + } + voiceOverObservation = NSWorkspace.shared.observe(\.isVoiceOverEnabled, options: [.new]) { + [weak self] _, change in + guard let enabled = change.newValue else { return } + MainActor.assumeIsolated { self?.setup.updateVoiceOver(enabled) } + } + activationObservation = NotificationCenter.default.addObserver( + forName: NSApplication.didBecomeActiveNotification, object: nil, queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { + guard let self, self.setup.isPresented else { return } + self.panel?.makeKey() + self.refreshSetup(permissionOnly: false) + } + } + for name in [NSWorkspace.didWakeNotification, NSWorkspace.sessionDidBecomeActiveNotification] { + workspaceObservations.append( + NSWorkspace.shared.notificationCenter.addObserver(forName: name, object: nil, queue: .main) { + [weak self] _ in + MainActor.assumeIsolated { self?.refreshSetup(permissionOnly: false) } + }) + } + } + + private func refreshSetup(permissionOnly: Bool) { + if permissionOnly { pendingPermissionRefresh = true } else { pendingFullRefresh = true } + guard refreshTask == nil else { return } + let generation = UUID() + refreshGeneration = generation + refreshTask = Task { @MainActor [weak self] in + guard let self else { return } + defer { + if refreshGeneration == generation { refreshTask = nil } + } + while !Task.isCancelled && setup.isPresented && (pendingFullRefresh || pendingPermissionRefresh) { + let fullRefresh = pendingFullRefresh + pendingFullRefresh = false + pendingPermissionRefresh = false + do { + if fullRefresh { try await setup.refreshAllowChecks() } else { try await setup.refreshPermission() } + try Task.checkCancellation() + resizePanel() + } catch is CancellationError { + return + } catch { failure(error) } + } + } + } + + private func stopSetupObservations() { + refreshTask?.cancel() + refreshTask = nil + refreshGeneration = nil + pendingFullRefresh = false + pendingPermissionRefresh = false + trustObservation?.cancel() + trustObservation = nil + voiceOverObservation?.invalidate() + voiceOverObservation = nil + if let activationObservation { NotificationCenter.default.removeObserver(activationObservation) } + activationObservation = nil + for observer in workspaceObservations { NSWorkspace.shared.notificationCenter.removeObserver(observer) } + workspaceObservations.removeAll() + } + private func positionPanel() { guard let panel else { return } guard let workspace = setup.draft?.workspace ?? state.activeWorkspace, @@ -181,6 +298,9 @@ public final class WindowLearningController { } public func pause() { + setupTask?.cancel() + setupTask = nil + stopSetupObservations() tour.pause() persist() panel?.orderOut(nil) @@ -200,6 +320,7 @@ public final class WindowLearningController { public func stop() { pause() + setup.dismiss() panel?.contentView = nil panel?.close() panel = nil diff --git a/Tests/ParcelUITests/SettingsShortcutConflictTests.swift b/Tests/ParcelUITests/SettingsShortcutConflictTests.swift index 69b3bdd6..5806b9d7 100644 --- a/Tests/ParcelUITests/SettingsShortcutConflictTests.swift +++ b/Tests/ParcelUITests/SettingsShortcutConflictTests.swift @@ -29,16 +29,19 @@ import Testing #expect(SettingsShortcutChecker.modeNotices(configuration: configuration, environment: .init()).isEmpty) } - @Test func editableShortcutPreviewsReflectValidDrafts() { - #expect( - ShortcutDisplayPreview.chord("ctrl-alt-u") - == .init(displayString: "⌃⌥U", accessibilityLabel: "Control Option U")) - #expect( - ShortcutDisplayPreview.keyModifiers("cmd-shift") - == .init(displayString: "⇧⌘", accessibilityLabel: "Shift Command")) - #expect( - ShortcutDisplayPreview.mouseModifiers("ctrl-alt") - == .init(displayString: "⌃⌥", accessibilityLabel: "Control Option")) + @Test func editableShortcutPreviewsReflectValidDrafts() throws { + let chord = try #require(ShortcutDisplayPreview.chord("ctrl-alt-u")) + #expect(chord.displayString == "⌃⌥U") + #expect(chord.accessibilityLabel == "Control Option U") + #expect(chord.tokens.map(\.glyph) == ["⌃", "⌥", "U"]) + let keys = try #require(ShortcutDisplayPreview.keyModifiers("cmd-shift")) + #expect(keys.displayString == "⇧⌘") + #expect(keys.accessibilityLabel == "Shift Command") + #expect(keys.tokens.map(\.glyph) == ["⇧", "⌘"]) + let mouse = try #require(ShortcutDisplayPreview.mouseModifiers("ctrl-alt")) + #expect(mouse.displayString == "⌃⌥") + #expect(mouse.accessibilityLabel == "Control Option") + #expect(mouse.tokens.map(\.glyph) == ["⌃", "⌥"]) #expect(ShortcutDisplayPreview.chord("ctrl-") == nil) #expect(ShortcutDisplayPreview.mouseModifiers("") == nil) #expect(ShortcutDisplayPreview.keyModifiers("") == nil) diff --git a/Tests/ParcelUITests/Tour/TourDemoTests.swift b/Tests/ParcelUITests/Tour/TourDemoTests.swift index af5580a5..d189538a 100644 --- a/Tests/ParcelUITests/Tour/TourDemoTests.swift +++ b/Tests/ParcelUITests/Tour/TourDemoTests.swift @@ -300,11 +300,11 @@ struct TourDemoTests { #expect(ShortcutDisplayPreview.chord("not-a-shortcut") == nil) } - @Test(arguments: [ColorSchemeContrast.standard, .increased]) - func keycapsRenderAtReadableBodySize(contrast: ColorSchemeContrast) throws { + @Test(arguments: [ColorScheme.light, .dark]) + func keycapsRenderAtReadableBodySize(colorScheme: ColorScheme) throws { let renderer = ImageRenderer( content: ShortcutLabel(chord: KeyChord(modifiers: [.ctrl, .alt], key: .space)) - .environment(\.colorSchemeContrast, contrast)) + .environment(\.colorScheme, colorScheme)) let image = try #require(renderer.cgImage) #expect(image.width >= 70) #expect(image.height >= 20 && image.height <= 40) diff --git a/Tests/ParcelUITests/Tour/TourSetupTests.swift b/Tests/ParcelUITests/Tour/TourSetupTests.swift index 72742de7..14e8d9fe 100644 --- a/Tests/ParcelUITests/Tour/TourSetupTests.swift +++ b/Tests/ParcelUITests/Tour/TourSetupTests.swift @@ -20,7 +20,7 @@ struct TourSetupTests { func firstRunBeginsAtWelcomeWithoutChangingTheWorkspace(track: TourTrack) async throws { let fixture = TourSetupFixture() let setup = fixture.controller - setup.begin(track, firstRun: true) + setup.begin(track, firstRun: true, defaultOpenAtLogin: true) #expect(setup.isPresented) #expect(setup.step == .welcome) #expect(setup.track == track) @@ -60,7 +60,7 @@ struct TourSetupTests { @Test func grantedPermissionChecksEveryAllowServiceThenAutomaticallyAdvances() async throws { let fixture = TourSetupFixture() let setup = fixture.controller - setup.begin(.keyboard, firstRun: true) + setup.begin(.keyboard, firstRun: true, defaultOpenAtLogin: true) try await setup.next() #expect(setup.permission == .granted) #expect(setup.step == .basics) @@ -88,12 +88,13 @@ struct TourSetupTests { personalization: actions.personalization, tidy: actions.tidy, openShortcuts: actions.openShortcuts, openSystemSettings: actions.openSystemSettings, openLoginSettings: actions.openLoginSettings, permissionStatus: actions.permissionStatus) - setup.begin(.keyboard, firstRun: true) + setup.begin(.keyboard, firstRun: true, defaultOpenAtLogin: true) try await setup.next() #expect(setup.permission == .missing) #expect(setup.step == .allow) #expect(fixture.permissionChecks == 1) - #expect(fixture.loginWrites == [true]) + #expect(fixture.loginWrites.isEmpty) + #expect(setup.openAtLogin) #expect(throws: TourSetupFailure.self) { try setup.openAccessibilitySettings() } setup.requestSkip() await #expect(throws: TourSetupFailure.self) { try await setup.resolveSkip(tidyNow: false) } @@ -109,19 +110,20 @@ struct TourSetupTests { let fixture = TourSetupFixture() fixture.permission = permission let setup = fixture.controller - setup.begin(.keyboard, firstRun: true) + setup.begin(.keyboard, firstRun: true, defaultOpenAtLogin: true) try await setup.next() #expect(setup.step == .allow) #expect(setup.permission == permission) #expect(!setup.canContinue) #expect(setup.system == fixture.system) #expect(setup.shortcuts == fixture.shortcuts) - #expect(setup.login == .enabled) + #expect(setup.login == .disabled) + #expect(setup.openAtLogin) #expect(fixture.permissionChecks == 1) #expect(fixture.systemChecks == 1) #expect(fixture.shortcutChecks == 1) #expect(fixture.loginChecks == 1) - #expect(fixture.loginWrites == [true]) + #expect(fixture.loginWrites.isEmpty) await #expect(throws: TourSetupFailure.self) { try await setup.next() } await #expect(throws: TourSetupFailure.self) { try await setup.tidyWorkspace() } #expect(fixture.tidyAttempts.isEmpty) @@ -130,7 +132,7 @@ struct TourSetupTests { @Test func backCanReviewAllowAndChangeLoginAfterPermissionWasGranted() async throws { let fixture = TourSetupFixture() let setup = fixture.controller - setup.begin(.keyboard, firstRun: true) + setup.begin(.keyboard, firstRun: true, defaultOpenAtLogin: true) try await setup.next() #expect(setup.step == .basics) try await setup.back() @@ -148,19 +150,19 @@ struct TourSetupTests { let fixture = TourSetupFixture() fixture.permission = .missing let setup = fixture.controller - setup.begin(.mouse, firstRun: true) + setup.begin(.mouse, firstRun: true, defaultOpenAtLogin: true) try await setup.next() try await setup.refreshPermission() #expect(setup.step == .allow) - #expect(fixture.loginWrites == [true]) + #expect(fixture.loginWrites.isEmpty) fixture.permission = .granted try await setup.refreshPermission() #expect(setup.permission == .granted) #expect(setup.step == .basics) #expect(fixture.permissionChecks == 3) - #expect(fixture.systemChecks == 3) - #expect(fixture.shortcutChecks == 3) - #expect(fixture.loginChecks == 3) + #expect(fixture.systemChecks == 1) + #expect(fixture.shortcutChecks == 1) + #expect(fixture.loginChecks == 1) #expect(fixture.loginWrites == [true]) try await setup.refreshPermission() #expect(fixture.permissionChecks == 3) @@ -180,7 +182,7 @@ struct TourSetupTests { fixture.system = check fixture.permission = .missing let setup = fixture.controller - setup.begin(.keyboard, firstRun: true) + setup.begin(.keyboard, firstRun: true, defaultOpenAtLogin: true) try await setup.next() #expect(setup.system == check) #expect(setup.system?.isClear == false) @@ -209,16 +211,16 @@ struct TourSetupTests { #expect(fixture.tidyAttempts.isEmpty) } - @Test func failedSystemCheckDoesNotRetainAReportedSuccess() async throws { + @Test func failedSystemRefreshKeepsThePreviousRowsAndSurfacesTheError() async throws { let fixture = TourSetupFixture() fixture.permission = .missing let setup = fixture.controller - setup.begin(.keyboard, firstRun: true) + setup.begin(.keyboard, firstRun: true, defaultOpenAtLogin: true) try await setup.next() #expect(setup.system?.isClear == true) fixture.failSystem = true await #expect(throws: TourSetupFailure.self) { try await setup.checkCurrentStep() } - #expect(setup.system == nil) + #expect(setup.system == fixture.system) #expect(setup.step == .allow) #expect(!setup.canContinue) #expect(!setup.isBusy) @@ -228,7 +230,7 @@ struct TourSetupTests { try await setup.checkCurrentStep() #expect(setup.system == fixture.system) #expect(setup.errorMessage == nil) - #expect(fixture.loginWrites == [true]) + #expect(fixture.loginWrites.isEmpty) } @Test func checksShowConflictsSuggestionsAndLimitationsWithoutPretendingSuccess() async throws { @@ -239,7 +241,7 @@ struct TourSetupTests { fixture.shortcuts = TourShortcutCheck(warnings: warnings, limitations: ["Menu access unavailable"]) fixture.permission = .missing let setup = fixture.controller - setup.begin(.keyboard, firstRun: true) + setup.begin(.keyboard, firstRun: true, defaultOpenAtLogin: true) try await setup.next() #expect(setup.shortcuts?.warnings.count == 2) #expect(setup.shortcuts?.warnings.first?.suggestions.isEmpty == false) @@ -247,8 +249,8 @@ struct TourSetupTests { #expect(setup.hasShortcutClash) fixture.failChecks = true await #expect(throws: TourSetupFailure.self) { try await setup.checkCurrentStep() } - #expect(setup.shortcuts == nil) - #expect(!setup.hasShortcutClash) + #expect(setup.shortcuts == fixture.shortcuts) + #expect(setup.hasShortcutClash) #expect(!setup.canContinue) #expect(setup.errorMessage != nil) #expect(fixture.tidyAttempts.isEmpty) @@ -278,7 +280,7 @@ struct TourSetupTests { fixture.permission = .missing fixture.shortcuts = TourShortcutCheck(warnings: [], modeNotices: ["Mode shortcut conflict"]) let setup = fixture.controller - setup.begin(.keyboard, firstRun: true) + setup.begin(.keyboard, firstRun: true, defaultOpenAtLogin: true) try await setup.next() #expect(setup.hasShortcutClash) fixture.shortcuts = TourShortcutCheck(warnings: [], limitations: ["Menu access unavailable"]) @@ -288,29 +290,32 @@ struct TourSetupTests { } @Test(arguments: [TourLoginStatus.enabled, .requiresApproval]) - func loginDefaultIsAppliedOnceAndNeverOverridesALaterOptOut(result: TourLoginStatus) async throws { + func loginDefaultCommitsOnLeavingAllowAndNeverOverridesALaterOptOut(result: TourLoginStatus) async throws { let fixture = TourSetupFixture() fixture.permission = .missing fixture.loginResult = result let setup = fixture.controller - setup.begin(.keyboard, firstRun: true) + setup.begin(.keyboard, firstRun: true, defaultOpenAtLogin: true) try await setup.next() + #expect(setup.login == .disabled) + #expect(setup.openAtLogin) + #expect(fixture.loginWrites.isEmpty) + try await setup.checkCurrentStep() + #expect(fixture.loginWrites.isEmpty) + fixture.permission = .granted + try await setup.refreshPermission() + #expect(setup.step == .basics) #expect(setup.login == result) #expect(fixture.loginWrites == [true]) - try await setup.checkCurrentStep() + try await setup.back() fixture.loginResult = .disabled try await setup.setOpenAtLogin(false) - #expect(setup.login == .disabled) try await setup.checkCurrentStep() - try await setup.back() - #expect(setup.step == .welcome) - try await setup.next() - try await setup.restart() - #expect(setup.step == .welcome) - try await setup.next() - setup.begin(.mouse, firstRun: true) + setup.begin(.mouse, firstRun: true, defaultOpenAtLogin: true) + fixture.permission = .missing try await setup.next() #expect(setup.login == .disabled) + #expect(!setup.openAtLogin) #expect(fixture.loginWrites == [true, false]) #expect(fixture.tidyAttempts.isEmpty) } @@ -321,7 +326,7 @@ struct TourSetupTests { fixture.permission = .missing fixture.loginStatusValue = status let setup = fixture.controller - setup.begin(.keyboard, firstRun: true) + setup.begin(.keyboard, firstRun: true, defaultOpenAtLogin: true) try await setup.next() #expect(setup.login == status) #expect(fixture.loginWrites.isEmpty) @@ -346,10 +351,9 @@ struct TourSetupTests { @Test func failedLoginDefaultStaysDisabledAndCanBeRetriedHonestly() async throws { let fixture = TourSetupFixture() - fixture.permission = .missing fixture.failLogin = true let setup = fixture.controller - setup.begin(.keyboard, firstRun: true) + setup.begin(.keyboard, firstRun: true, defaultOpenAtLogin: true) await #expect(throws: TourSetupFailure.self) { try await setup.next() } #expect(setup.step == .allow) #expect(setup.login == .disabled) @@ -359,9 +363,9 @@ struct TourSetupTests { fixture.failLogin = false fixture.loginResult = .requiresApproval try await setup.checkCurrentStep() + #expect(setup.step == .basics) #expect(setup.login == .requiresApproval) #expect(setup.errorMessage == nil) - try await setup.checkCurrentStep() #expect(fixture.loginWrites == [true, true]) #expect(fixture.tidyAttempts.isEmpty) } @@ -369,9 +373,10 @@ struct TourSetupTests { @Test func explicitLoginFailurePreservesRequiresApprovalInsteadOfClaimingEnabled() async throws { let fixture = TourSetupFixture() fixture.permission = .missing + fixture.loginStatusValue = .requiresApproval fixture.loginResult = .requiresApproval let setup = fixture.controller - setup.begin(.keyboard, firstRun: true) + setup.begin(.keyboard, firstRun: true, defaultOpenAtLogin: true) try await setup.next() #expect(setup.login == .requiresApproval) fixture.failLogin = true @@ -384,7 +389,7 @@ struct TourSetupTests { try await setup.setOpenAtLogin(false) #expect(setup.login == .disabled) #expect(setup.errorMessage == nil) - #expect(fixture.loginWrites == [true, false, false]) + #expect(fixture.loginWrites == [false, false]) #expect(fixture.tidyAttempts.isEmpty) } @@ -393,7 +398,7 @@ struct TourSetupTests { fixture.permission = .missing fixture.failLoginStatus = true let setup = fixture.controller - setup.begin(.keyboard, firstRun: true) + setup.begin(.keyboard, firstRun: true, defaultOpenAtLogin: true) await #expect(throws: TourSetupFailure.self) { try await setup.next() } #expect(setup.login == nil) #expect(!setup.canContinue) @@ -401,9 +406,10 @@ struct TourSetupTests { #expect(fixture.loginWrites.isEmpty) fixture.failLoginStatus = false try await setup.checkCurrentStep() - #expect(setup.login == .enabled) + #expect(setup.login == .disabled) + #expect(setup.openAtLogin) #expect(setup.errorMessage == nil) - #expect(fixture.loginWrites == [true]) + #expect(fixture.loginWrites.isEmpty) } @Test(arguments: TourSetupStep.allCases) @@ -433,7 +439,7 @@ struct TourSetupTests { let fixture = TourSetupFixture() fixture.permission = .missing let setup = fixture.controller - setup.begin(.keyboard, firstRun: true) + setup.begin(.keyboard, firstRun: true, defaultOpenAtLogin: true) try await setup.next() try setup.openAccessibilitySettings() #expect(fixture.openedSettings == [.accessibility]) @@ -839,7 +845,7 @@ struct TourSetupTests { @Test func missingIntegrationSurfacesAnErrorAtAllow() async { let setup = TourSetupController() - setup.begin(.keyboard, firstRun: true) + setup.begin(.keyboard, firstRun: true, defaultOpenAtLogin: true) await #expect(throws: TourSetupFailure.self) { try await setup.next() } #expect(setup.step == .allow) #expect(setup.errorMessage != nil) @@ -870,6 +876,137 @@ struct TourSetupTests { #expect(TourSystemCheck(enabled).nativeTiling == true) } + @Test func upgradeStartsAtWelcomeWithoutDraftingLoginRegistration() async throws { + let fixture = TourSetupFixture() + fixture.permission = .missing + let setup = fixture.controller + setup.begin(.keyboard, firstRun: true) + try await setup.next() + #expect(setup.step == .allow) + #expect(setup.login == .disabled) + #expect(!setup.openAtLogin) + #expect(fixture.loginWrites.isEmpty) + } + + @Test func quittingBeforeLeavingAllowDoesNotCommitTheLoginDraft() async throws { + let fixture = TourSetupFixture() + fixture.permission = .missing + let setup = fixture.controller + setup.begin(.keyboard, firstRun: true, defaultOpenAtLogin: true) + try await setup.next() + #expect(setup.openAtLogin) + setup.dismiss() + try await setup.refreshPermission() + #expect(fixture.loginWrites.isEmpty) + #expect(fixture.permissionChecks == 1) + } + + @Test(arguments: [true, false]) + func voiceOverOffersBothChoicesWithoutChangingTheDefaultUntilConsent(alternate: Bool) async throws { + let fixture = TourSetupFixture() + let setup = fixture.controller + var writes = 0 + var actions = try #require(setup.actions) + actions.useAlternatePrefix = { writes += 1 } + setup.actions = actions + setup.begin(.keyboard, firstRun: true) + #expect(!setup.showsVoiceOverChoice) + setup.updateVoiceOver(true) + try await setup.next() + #expect(setup.step == .allow) + #expect(setup.showsVoiceOverChoice) + #expect(writes == 0) + try await setup.chooseVoiceOverPrefix(useAlternate: alternate) + #expect(!setup.showsVoiceOverChoice) + #expect(writes == (alternate ? 1 : 0)) + await #expect(throws: TourSetupFailure.self) { try await setup.chooseVoiceOverPrefix(useAlternate: true) } + #expect(writes == (alternate ? 1 : 0)) + setup.updateVoiceOver(false) + #expect(!setup.showsVoiceOverChoice) + #expect(fixture.loginWrites.isEmpty) + } + + @Test func skipTidyWithoutAccessibilityRoutesToAllowWithoutTouchingWindows() async throws { + let fixture = TourSetupFixture() + fixture.permission = .missing + let setup = fixture.controller + setup.begin(.keyboard, firstRun: true) + setup.requestSkip() + await #expect(throws: TourSetupFailure.self) { try await setup.resolveSkip(tidyNow: true) } + #expect(setup.step == .allow) + #expect(setup.errorMessage == TourSetupFailure.accessibilityRequired.localizedDescription) + #expect(!setup.isSkipConfirmationPresented) + #expect(fixture.skipCalls.isEmpty) + #expect(fixture.tidyAttempts.isEmpty) + #expect(fixture.loginWrites.isEmpty) + fixture.permission = .granted + try await setup.refreshPermission() + #expect(setup.step == .allow) + try await setup.next() + #expect(setup.step == .basics) + } + + @Test func refreshingAllowRetainsRowsAndDoesNotBlockBackOrSkip() async throws { + let fixture = TourSetupFixture() + fixture.permission = .missing + let setup = fixture.controller + setup.begin(.keyboard, firstRun: true) + try await setup.next() + let system = setup.system + let shortcuts = setup.shortcuts + var release: CheckedContinuation? + var task: Task? + await withCheckedContinuation { started in + var actions = fixture.controller.actions! + actions.checkSystem = { + await withCheckedContinuation { + release = $0 + started.resume() + } + return TourSystemCheck(stageManager: true, nativeTiling: true) + } + setup.actions = actions + task = Task { try await setup.refreshAllowChecks() } + } + #expect(!setup.isBusy) + #expect(setup.system == system) + #expect(setup.shortcuts == shortcuts) + setup.requestSkip() + #expect(setup.isSkipConfirmationPresented) + setup.isSkipConfirmationPresented = false + try await setup.back() + #expect(setup.step == .welcome) + release?.resume() + try await task?.value + #expect(setup.system == system) + #expect(setup.shortcuts == shortcuts) + #expect(fixture.loginWrites.isEmpty) + } + + @Test func titlesHaveNoTerminalPunctuationAndCompletionIsDistinct() { + #expect(TourSetupStep.allCases.allSatisfy { !$0.title.hasSuffix(".") }) + #expect(TourSetupStep.tidy.title != TourSetupStep.complete.title) + #expect(TourSetupStep.complete.screenIndex == TourSetupStep.tidy.screenIndex) + } + + @Test func projectedPersonalizationBindingsPreserveTheDraftWorkspace() async throws { + let fixture = TourSetupFixture() + let setup = fixture.controller + setup.begin(.keyboard) + try await fixture.reachPersonalization() + let workspace = try #require(setup.draft).workspace + setup.draftLayout = .rows + setup.draftWindowCount = 2 + setup.draftHighlight = .active + setup.draftWhenFull = .float + #expect(setup.draftLayout == .rows) + #expect(setup.draftWindowCount == 2) + #expect(setup.draftHighlight == .active) + #expect(setup.draftWhenFull == .float) + #expect(setup.draft?.workspace == workspace) + #expect(fixture.tidyAttempts.isEmpty) + } + @Test func atomicSettingsBatchDoesNotPublishPartiallyValidChoices() throws { let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) @@ -1000,13 +1137,37 @@ struct TourSetupTests { extension AppKitTestSuite { @MainActor struct TourSetupRenderingTests { + private func assertNoLargeEmptyRegions(_ bitmap: NSBitmapImageRep) throws { + let background = try #require(bitmap.colorAt(x: 12, y: 12)?.usingColorSpace(.deviceRGB)) + let inset = 24 + var emptyRun = 0 + var longestRun = 0 + for y in inset..<(bitmap.pixelsHigh - inset) { + let empty = stride(from: inset, to: bitmap.pixelsWide - inset, by: 6).allSatisfy { x in + guard let color = bitmap.colorAt(x: x, y: y)?.usingColorSpace(.deviceRGB) else { return false } + return abs(color.redComponent - background.redComponent) < 0.035 + && abs(color.greenComponent - background.greenComponent) < 0.035 + && abs(color.blueComponent - background.blueComponent) < 0.035 + && abs(color.alphaComponent - background.alphaComponent) < 0.035 + } + emptyRun = empty ? emptyRun + 1 : 0 + longestRun = max(longestRun, emptyRun) + } + #expect(Double(longestRun) / Double(bitmap.pixelsHigh) < 0.28) + } + @Test( arguments: TourSetupStep.allCases, - [(false, ColorScheme.light), (false, .dark), (true, .light), (true, .dark)]) - func everySetupStateRendersAtTourWindowSize( - step: TourSetupStep, appearance: (accessible: Bool, colorScheme: ColorScheme) + [ + (false, false, ColorScheme.light), (false, false, .dark), + (true, false, .light), (true, false, .dark), + (false, true, .light), (false, true, .dark), + (true, true, .light), (true, true, .dark), + ]) + func everySetupStateFitsItsContentSizedPanelWithoutLargeEmptyRegions( + step: TourSetupStep, appearance: (accessible: Bool, highContrast: Bool, colorScheme: ColorScheme) ) async throws { - let (accessibleAppearance, colorScheme) = appearance + let (accessibleAppearance, highContrast, colorScheme) = appearance let suite = "tour-setup-tests.\(UUID().uuidString)" let defaults = try #require(UserDefaults(suiteName: suite)) defer { defaults.removePersistentDomain(forName: suite) } @@ -1019,7 +1180,7 @@ extension AppKitTestSuite { learning.update(state: LearningScene.state(), configuration: configuration, active: false) let setup = learning.setup setup.actions = fixture.controller.actions - setup.begin(.keyboard, firstRun: true) + setup.begin(.keyboard, firstRun: true, defaultOpenAtLogin: true) let destination: TourSetupStep = step == .complete ? .tidy : step if destination != .welcome { try await setup.next() } if destination.screenIndex > TourSetupStep.allow.screenIndex { @@ -1034,20 +1195,31 @@ extension AppKitTestSuite { .environment(\.colorScheme, colorScheme) .environment(\.dynamicTypeSize, accessibleAppearance ? .accessibility3 : .large)) let appearanceName: NSAppearance.Name = - if accessibleAppearance { + if highContrast { colorScheme == .light ? .accessibilityHighContrastAqua : .accessibilityHighContrastDarkAqua } else { colorScheme == .light ? .aqua : .darkAqua } host.appearance = NSAppearance(named: appearanceName) - host.frame = CGRect(x: 0, y: 0, width: 480, height: 600) + host.sizingOptions = [.preferredContentSize, .intrinsicContentSize] + host.frame = CGRect(x: 0, y: 0, width: 440, height: 1) + host.layoutSubtreeIfNeeded() + let fittingSize = host.fittingSize + #expect(abs(fittingSize.width - 440) < 1) + #expect(fittingSize.height > 200) + #expect(fittingSize.height < (accessibleAppearance ? 1200 : 800)) + host.frame = CGRect(origin: .zero, size: fittingSize) + host.layoutSubtreeIfNeeded() + host.frame.size = host.fittingSize host.layoutSubtreeIfNeeded() - #expect(host.bounds.size == CGSize(width: 480, height: 600)) + #expect(abs(host.fittingSize.height - host.bounds.height) < 1) + #expect(abs(host.fittingSize.width - host.bounds.width) < 1) let bitmap = try #require(host.bitmapImageRepForCachingDisplay(in: host.bounds)) host.cacheDisplay(in: host.bounds, to: bitmap) #expect(bitmap.tiffRepresentation?.isEmpty == false) #expect(fixture.tidyAttempts.count == (step == .complete ? 1 : 0)) - if !accessibleAppearance, let path = ProcessInfo.processInfo.environment["PARCEL_TOUR_QA_DIR"] { + try assertNoLargeEmptyRegions(bitmap) + if let path = ProcessInfo.processInfo.environment["PARCEL_TOUR_QA_DIR"] { try #require(path.hasPrefix("/"), "PARCEL_TOUR_QA_DIR must be an absolute private directory path.") let directory = URL(fileURLWithPath: path, isDirectory: true) let manager = FileManager.default @@ -1059,9 +1231,10 @@ extension AppKitTestSuite { try #require(values.isDirectory == true, "PARCEL_TOUR_QA_DIR must name a directory.") let index = try #require(TourSetupStep.allCases.firstIndex(of: step)) + 1 let appearance = colorScheme == .light ? "light" : "dark" - let name = String(format: "%02d-%@-%@.png", index, step.rawValue, appearance) + let suffix = (accessibleAppearance ? "-ax3" : "") + (highContrast ? "-ic" : "") + let name = String(format: "%02d-%@-%@%@.png", index, step.rawValue, appearance, suffix) let png = try #require(bitmap.representation(using: .png, properties: [:])) - try png.write(to: directory.appendingPathComponent(name), options: .withoutOverwriting) + try png.write(to: directory.appendingPathComponent(name), options: .atomic) } } } diff --git a/Tests/ParcelUITests/Tour/WindowLearningControllerTests.swift b/Tests/ParcelUITests/Tour/WindowLearningControllerTests.swift index 74618622..fd07bd82 100644 --- a/Tests/ParcelUITests/Tour/WindowLearningControllerTests.swift +++ b/Tests/ParcelUITests/Tour/WindowLearningControllerTests.swift @@ -165,20 +165,20 @@ struct WindowLearningPreferencesTests { openShortcuts: {}, openSystemSettings: {}, openLoginSettings: {}, permissionStatus: { .missing }) let first = try make(defaults) first.setup.actions = actions - first.setup.begin(.keyboard, firstRun: true) + first.setup.begin(.keyboard, firstRun: true, defaultOpenAtLogin: true) try await first.setup.next() try await first.setup.setOpenAtLogin(false) first.stop() - #expect(writes == [true, false]) + #expect(writes == [false]) #expect(defaults.bool(forKey: "guidedTour.v2.loginDefaultApplied")) #expect(!defaults.bool(forKey: "guidedTour.v2.completed")) let restored = try make(defaults) defer { restored.stop() } restored.setup.actions = actions - restored.setup.begin(.keyboard, firstRun: true) + restored.setup.begin(.keyboard, firstRun: true, defaultOpenAtLogin: true) try await restored.setup.next() #expect(restored.setup.login == .disabled) - #expect(writes == [true, false]) + #expect(writes == [false]) } @Test(arguments: ["guidedTour.v1"]) -- knotmirror 0.0.1