From 5afeba8c7e05444c89dee673f083a5806b46db01 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 12:47:14 -0400 Subject: [PATCH 1/7] Make workspace edits explicit and restorable --- Sources/ParcelCore/Commands.swift | 2 +- Sources/ParcelCore/Modes.swift | 9 +- Sources/ParcelCore/WorkspaceCommands.swift | 10 +- Sources/ParcelEngine/EngineEvents.swift | 1 + Sources/ParcelEngine/EngineMotion.swift | 7 +- .../EngineWorkspaceTransaction.swift | 193 +++++++++++++++++ Sources/ParcelEngine/ParcelEngine.swift | 23 +- .../WorkspaceCommandTests.swift | 42 +++- .../WorkspaceTransactionTests.swift | 202 ++++++++++++++++++ 9 files changed, 470 insertions(+), 19 deletions(-) create mode 100644 Sources/ParcelEngine/EngineWorkspaceTransaction.swift create mode 100644 Tests/ParcelEngineTests/WorkspaceTransactionTests.swift diff --git a/Sources/ParcelCore/Commands.swift b/Sources/ParcelCore/Commands.swift index f9852cc5..6f1553e9 100644 --- a/Sources/ParcelCore/Commands.swift +++ b/Sources/ParcelCore/Commands.swift @@ -57,7 +57,7 @@ extension State { } } - private mutating func applyWorkspace(_ command: Command, key: WorkspaceKey, effects: inout [Effect]) { + mutating func applyWorkspace(_ command: Command, key: WorkspaceKey, effects: inout [Effect]) { guard var workspace = workspaces[key] else { return } switch command { case .cycleLayout: diff --git a/Sources/ParcelCore/Modes.swift b/Sources/ParcelCore/Modes.swift index 3826c175..e4a333d5 100644 --- a/Sources/ParcelCore/Modes.swift +++ b/Sources/ParcelCore/Modes.swift @@ -28,7 +28,12 @@ extension State { effects.append(.report(.noActiveWorkspace)) return } + toggle(mode, in: key, effects: &effects) + } + + mutating func toggle(_ mode: FocusMode, in key: WorkspaceKey, effects: inout [Effect]) { var modes = modes(for: key) + let hasFocusedWindow = focusedWindow.flatMap(workspace(containing:)) == key let enabled: Bool switch mode { case .focus: @@ -59,14 +64,14 @@ extension State { effects.append(.raiseWindow(window)) } case .noPeek: - guard modes.noPeek || focusedWindow != nil else { + guard modes.noPeek || hasFocusedWindow else { effects.append(.report(.noFocusedWindow)) return } modes.noPeek.toggle() enabled = modes.noPeek case .cleanSpace: - guard modes.cleanSpace || focusedWindow != nil else { + guard modes.cleanSpace || hasFocusedWindow else { effects.append(.report(.noFocusedWindow)) return } diff --git a/Sources/ParcelCore/WorkspaceCommands.swift b/Sources/ParcelCore/WorkspaceCommands.swift index 04e580c8..34b8144f 100644 --- a/Sources/ParcelCore/WorkspaceCommands.swift +++ b/Sources/ParcelCore/WorkspaceCommands.swift @@ -9,11 +9,13 @@ extension State { guard displays[key.display] != nil else { return .unavailableDisplay(key.display) } guard isActive(key), workspaces[key] != nil else { return .noActiveWorkspace } guard command.supportsWorkspaceTarget else { return .unsupported } - let previousDisplay = activeDisplay - activeDisplay = key.display - defer { activeDisplay = previousDisplay } if command.endsFocus { endFocus(in: key, effects: &effects) } - apply(command, effects: &effects) + switch command { + case .toggleFocus: toggle(.focus, in: key, effects: &effects) + case .toggleNoPeek: toggle(.noPeek, in: key, effects: &effects) + case .toggleCleanSpace: toggle(.cleanSpace, in: key, effects: &effects) + default: applyWorkspace(command, key: key, effects: &effects) + } return nil } } diff --git a/Sources/ParcelEngine/EngineEvents.swift b/Sources/ParcelEngine/EngineEvents.swift index 34d31853..8b01ee0c 100644 --- a/Sources/ParcelEngine/EngineEvents.swift +++ b/Sources/ParcelEngine/EngineEvents.swift @@ -29,6 +29,7 @@ extension ParcelEngine { case .systemWindowConflictChanged(let conflict): systemWindowConflict = conflict onSystemWindowConflictChanged?(conflict) + resolveWorkspaceWaiters() case .failure(let failure): handle(failure) } } diff --git a/Sources/ParcelEngine/EngineMotion.swift b/Sources/ParcelEngine/EngineMotion.swift index 024f0186..ba0676ec 100644 --- a/Sources/ParcelEngine/EngineMotion.swift +++ b/Sources/ParcelEngine/EngineMotion.swift @@ -4,7 +4,7 @@ import ParcelCore extension ParcelEngine { func planFrames() { - guard writesPermitted, !isPaused else { return } + guard writesPermitted, !isPaused || pausedWorkspaceRestoration != nil else { return } let now = animationTime updateMotion() for window in snapshot.state.frames.keys.sorted() { @@ -12,7 +12,8 @@ extension ParcelEngine { else { continue } guard let managed = snapshot.state.windows[window], let key = snapshot.state.workspace(containing: window), !unmanageableApps.contains(managed.app), !suspendedDisplays.contains(key.display), - snapshot.state.isActive(key), let target = snapshot.state.frames[window], + snapshot.state.isActive(key), !isPaused || pausedWorkspaceRestoration == key, + let target = pausedRestorationFrames[window] ?? snapshot.state.frames[window], let screen = snapshot.state.displays[key.display] else { continue } if let adjustment = frameAdjustments[window], adjustment.requested == target, @@ -140,7 +141,7 @@ extension ParcelEngine { } func pump() { - guard isRunning, !isPaused, !pumping else { return } + guard isRunning, !isPaused || pausedWorkspaceRestoration != nil, !pumping else { return } pumping = true pumpWake?.cancel() pumpWake = nil diff --git a/Sources/ParcelEngine/EngineWorkspaceTransaction.swift b/Sources/ParcelEngine/EngineWorkspaceTransaction.swift new file mode 100644 index 00000000..028c191d --- /dev/null +++ b/Sources/ParcelEngine/EngineWorkspaceTransaction.swift @@ -0,0 +1,193 @@ +import Foundation +public import ParcelCore + +public enum EngineWorkspaceFailure: Error, Sendable, Equatable { + case workspaceUnavailable + case paused + case systemConflict + case busy + case unsettled([WindowID]) +} + +public struct EngineWorkspaceRestorePoint: Sendable { + public let workspace: WorkspaceKey + public let isPaused: Bool + fileprivate let owner: UUID + fileprivate let lifetime: UInt64 + fileprivate let model: Workspace + fileprivate let modes: FocusModes + fileprivate let windows: [WindowID: ManagedWindow] + fileprivate let frames: [WindowID: Rect] +} + +extension ParcelEngine { + struct WorkspaceWaiter { + let workspace: WorkspaceKey + let reply: CheckedContinuation + let timeout: any EngineCancellation + } + + public func captureWorkspaceRestorePoint(in key: WorkspaceKey) throws -> EngineWorkspaceRestorePoint { + try validateWorkspace(key) + guard let workspace = snapshot.state.workspaces[key] else { + throw EngineWorkspaceFailure.workspaceUnavailable + } + let members = Set(workspace.order) + return EngineWorkspaceRestorePoint( + workspace: key, isPaused: isPaused, owner: workspaceTransactionOwner, lifetime: lifetime, + model: workspace, modes: snapshot.state.modes(for: key), + windows: snapshot.state.windows.filter { members.contains($0.key) }, + frames: actualFrames.filter { members.contains($0.key) }) + } + + public func restoreWorkspace(_ point: EngineWorkspaceRestorePoint) async throws { + try Task.checkCancellation() + try validateWorkspace(point.workspace) + guard point.owner == workspaceTransactionOwner, point.lifetime == lifetime else { + throw EngineWorkspaceFailure.workspaceUnavailable + } + guard pausedWorkspaceRestoration == nil else { throw EngineWorkspaceFailure.busy } + // A paused workspace may contain hand-placed windows, not its layout's calculated slots. + if point.isPaused { setPaused(true) } + if !queue.isEmpty || needsRetile { + turn?.cancel() + turn = nil + flush() + } + let current = snapshot.state + guard let currentWorkspace = current.workspaces[point.workspace] else { + throw EngineWorkspaceFailure.workspaceUnavailable + } + var restored = current + restored.workspaces[point.workspace] = point.model + restored.windows = point.windows.merging(current.windows) { _, current in current } + let retained = Set( + currentWorkspace.order.filter { id in + guard let previous = point.windows[id], let window = current.windows[id] else { return false } + return previous.app == window.app + }) + var events: [Event] = point.model.order.filter { !retained.contains($0) }.map(Event.windowDisappeared) + events += currentWorkspace.order.compactMap { id in + guard let window = current.windows[id], + !retained.contains(id) || point.windows[id]?.isFloating != window.isFloating + else { return nil } + return .windowAppeared( + window, workspace: point.workspace, frame: actualFrames[id] ?? current.frames[id] ?? Rect()) + } + if events.isEmpty { events = [.relayout] } + let (reconciled, _) = reduce(restored, events) + restored = current + restored.workspaces[point.workspace] = reconciled.workspaces[point.workspace] + var modes = point.modes + if let focused = modes.focusedWindow, + !retained.contains(focused) || current.windows[focused]?.isFloating != false + { + modes.focusedWindow = nil + } + if restored.focusModes == nil { restored.focusModes = [:] } + restored.focusModes?[point.workspace] = modes + let members = Set(currentWorkspace.order) + for id in members { + cancelMotion(id, remove: false) + frameAdjustments[id] = nil + } + let (arranged, _) = reduce(restored, .relayout) + restored = arranged + if point.isPaused { + pausedWorkspaceRestoration = point.workspace + pausedRestorationFrames = point.frames.filter { retained.contains($0.key) } + for (id, frame) in pausedRestorationFrames { restored.frames[id] = frame } + } + revision += 1 + snapshot = EngineSnapshot(revision: revision, state: restored) + defer { + pausedWorkspaceRestoration = nil + pausedRestorationFrames.removeAll() + setPaused(point.isPaused) + } + if !point.isPaused { setPaused(false) } + planFrames() + for subscriber in subscribers.values { subscriber.yield(snapshot) } + try await awaitWorkspaceSettled(in: point.workspace) + } + + public func awaitWorkspaceSettled(in key: WorkspaceKey, timeout: Duration = .seconds(15)) async throws { + try Task.checkCancellation() + if let result = workspaceSettleResult(in: key) { return try result.get() } + let components = timeout.components + let delay = max(0, Double(components.seconds) + Double(components.attoseconds) / 1e18) + let id = UUID() + try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { (reply: CheckedContinuation) in + guard !Task.isCancelled else { + reply.resume(throwing: CancellationError()) + return + } + let cancellation = scheduler.schedule(after: delay) { [weak self] in + guard let self else { return } + let windows = self.unsettledWindows(in: key) + self.finishWorkspaceWaiter(id, result: .failure(EngineWorkspaceFailure.unsettled(windows))) + } + workspaceWaiters[id] = WorkspaceWaiter(workspace: key, reply: reply, timeout: cancellation) + } + } onCancel: { + Task { @MainActor [weak self] in + self?.finishWorkspaceWaiter(id, result: .failure(CancellationError())) + } + } + } + + func resolveWorkspaceWaiters() { + for (id, waiter) in workspaceWaiters { + if let result = workspaceSettleResult(in: waiter.workspace) { + finishWorkspaceWaiter(id, result: result) + } + } + } + + func finishWorkspaceWaiter(_ id: UUID, result: Result) { + guard let waiter = workspaceWaiters.removeValue(forKey: id) else { return } + waiter.timeout.cancel() + waiter.reply.resume(with: result) + } + + private func validateWorkspace(_ key: WorkspaceKey) throws { + guard isRunning else { throw EngineError.stopped } + guard snapshot.state.isActive(key), snapshot.state.workspaces[key] != nil else { + throw EngineWorkspaceFailure.workspaceUnavailable + } + } + + private func workspaceSettleResult(in key: WorkspaceKey) -> Result? { + do { try validateWorkspace(key) } catch { return .failure(error) } + if systemWindowConflict != nil { return .failure(EngineWorkspaceFailure.systemConflict) } + if suspendedDisplays.contains(key.display) { return .failure(EngineWorkspaceFailure.workspaceUnavailable) } + if isPaused && pausedWorkspaceRestoration != key { return .failure(EngineWorkspaceFailure.paused) } + guard !isFlushing, !pumping, queue.isEmpty, turn == nil, !needsRetile, + !spaceCommandRunning, focusOperations == 0, + animators[key.display]?.isIdle != false + else { return nil } + let ids = Set(snapshot.state.workspaces[key]?.order ?? []) + let apps = Set(ids.compactMap { snapshot.state.windows[$0]?.app.motionID }) + let motionIDs = Set(ids.map(\.motionID)) + guard !pendingFrames.values.contains(where: { motionIDs.contains($0.windowID) }), + busyApps.isDisjoint(with: apps), operatingWindows.isDisjoint(with: ids), dragging.isDisjoint(with: ids) + else { return nil } + let windows = unsettledWindows(in: key) + return windows.isEmpty ? .success(()) : .failure(EngineWorkspaceFailure.unsettled(windows)) + } + + private func unsettledWindows(in key: WorkspaceKey) -> [WindowID] { + let ids = + pausedWorkspaceRestoration == key + ? Array(pausedRestorationFrames.keys) : snapshot.state.workspaces[key]?.visibleWindows ?? [] + return ids.filter { id in + guard let target = pausedRestorationFrames[id] ?? snapshot.state.frames[id], + let actual = actualFrames[id] + else { return true } + if actual.matches(target) { return false } + guard let adjustment = frameAdjustments[id], adjustment.requested == target else { return true } + return !actual.matches(adjustment.accepted) + }.sorted() + } +} diff --git a/Sources/ParcelEngine/ParcelEngine.swift b/Sources/ParcelEngine/ParcelEngine.swift index 050870d2..9ffc1a88 100644 --- a/Sources/ParcelEngine/ParcelEngine.swift +++ b/Sources/ParcelEngine/ParcelEngine.swift @@ -112,6 +112,10 @@ public final class ParcelEngine { var reduceMotion = false var snapNextPass = false var needsRetile = false + let workspaceTransactionOwner = UUID() + var workspaceWaiters: [UUID: WorkspaceWaiter] = [:] + var pausedWorkspaceRestoration: WorkspaceKey? + var pausedRestorationFrames: [WindowID: Rect] = [:] var traced: Set = [] var firstWriteTraces: Set = [] var openWrites: Set = [] @@ -266,6 +270,7 @@ public final class ParcelEngine { queue.removeAll() needsRetile = false finishTracing() + for id in workspaceWaiters.keys { finishWorkspaceWaiter(id, result: .failure(EngineError.stopped)) } for subscriber in subscribers.values { subscriber.finish() } subscribers.removeAll() await configSource?.stop() @@ -284,6 +289,10 @@ public final class ParcelEngine { world.stop() reduceMotionSource?.stop() for pending in queue { pending.reply?.resume(throwing: EngineError.stopped) } + for waiter in workspaceWaiters.values { + waiter.timeout.cancel() + waiter.reply.resume(throwing: EngineError.stopped) + } for subscriber in subscribers.values { subscriber.finish() } } @@ -382,7 +391,10 @@ extension ParcelEngine { guard configuration != self.configuration else { return } if configuration.mouse != self.configuration.mouse { cancelMouseGesture() } var state = snapshot.state + var layoutChanged = false + let motionChanged = configuration.motion != self.configuration.motion for key in state.workspaces.keys where applied.values(for: key.display) != updated.values(for: key.display) { + layoutChanged = true let screen = state.displays[key.display]?.frame let preserveLayout = applied.defaultLayout(for: key.display, in: screen) @@ -406,8 +418,14 @@ extension ParcelEngine { reconcileQueuedModes(activeMode: state.activeMode) reportRatioBounds() snapshot = EngineSnapshot(revision: revision, state: state) - needsRetile = true - if isRunning { scheduleTurn() } + needsRetile = needsRetile || layoutChanged + if isRunning { + if motionChanged { + updateMotion() + for display in animators.keys.sorted() { tick(display, at: animationTime) } + } + if needsRetile || !queue.isEmpty { scheduleTurn() } + } } func enqueue(_ event: Event) { @@ -435,6 +453,7 @@ extension ParcelEngine { } func settleIfIdle() { + resolveWorkspaceWaiters() guard isIdle else { return } finishTracing() let apps = settledApps diff --git a/Tests/ParcelCoreTests/WorkspaceCommandTests.swift b/Tests/ParcelCoreTests/WorkspaceCommandTests.swift index bdf0a48d..8e0dad72 100644 --- a/Tests/ParcelCoreTests/WorkspaceCommandTests.swift +++ b/Tests/ParcelCoreTests/WorkspaceCommandTests.swift @@ -28,12 +28,14 @@ struct WorkspaceCommandTests { } @Test(arguments: [ - Command.setWindowCap(2), .setLayout(.rows), .setRatio(.threeFifths), .resetSizes, .retile, .toggleNoPeek, - .toggleCleanSpace, + Command.setWindowCap(2), .setLayout(.rows), .setRatio(.threeFifths), .resetSizes, .retile, ]) func targetsOneDisplayWithoutStealingFocus(command: Command) throws { - let before = scene() + var before = scene() let key = WorkspaceKey(display: right, space: space) + if case .setRatio = command { + before = reduce(before, .workspaceCommandIssued(.setLayout(.side), workspace: key)).0 + } let (after, effects) = reduce(before, .workspaceCommandIssued(command, workspace: key)) #expect(after.activeDisplay == left) #expect(after.focusedWindow == WindowID(rawValue: 1)) @@ -48,8 +50,10 @@ struct WorkspaceCommandTests { [WindowID(rawValue: 4)], [WindowID(rawValue: 5), WindowID(rawValue: 6)], ]) } - if command == .toggleNoPeek { #expect(after.modes(for: key).noPeek) } - if command == .toggleCleanSpace { #expect(after.modes(for: key).cleanSpace) } + if case .setRatio(let ratio) = command { + #expect(after.workspaces[key]?.layout == .side) + #expect(after.workspaces[key]?.ratio == ratio) + } if command == .retile { #expect(effects.contains(.report(.retiled(moved: 2)))) } } @@ -109,10 +113,34 @@ struct WorkspaceCommandTests { #expect(after.modes(for: second).focusedWindow == nil) } - @Test func rejectsFocusOnAnotherDisplaysWindow() { + @Test(arguments: [Command.toggleFocus, .toggleNoPeek, .toggleCleanSpace]) + func disablingTargetModesDoesNotNeedLocalFocus(command: Command) { + var state = scene() + let key = WorkspaceKey(display: right, space: space) + state.focusModes = [key: FocusModes(focusedWindow: WindowID(rawValue: 4), noPeek: true, cleanSpace: true)] + let (after, effects) = reduce(state, .workspaceCommandIssued(command, workspace: key)) + #expect(!effects.contains(.report(.noFocusedWindow))) + #expect(after.activeDisplay == left) + if command == .toggleFocus { #expect(after.modes(for: key).focusedWindow == nil) } + if command == .toggleNoPeek { #expect(!after.modes(for: key).noPeek) } + if command == .toggleCleanSpace { #expect(!after.modes(for: key).cleanSpace) } + } + + @Test func explicitWorkspaceDoesNotRequireAnActiveDisplay() { + var state = scene() + state.activeDisplay = nil + let key = WorkspaceKey(display: right, space: space) + let (after, effects) = reduce(state, .workspaceCommandIssued(.setLayout(.rows), workspace: key)) + #expect(after.activeDisplay == nil) + #expect(after.workspaces[key]?.layout == .rows) + #expect(!effects.contains(.report(.noActiveWorkspace))) + } + + @Test(arguments: [Command.toggleFocus, .toggleNoPeek, .toggleCleanSpace]) + func rejectsModeOnAnotherDisplaysWindow(command: Command) { let state = scene() let key = WorkspaceKey(display: right, space: space) - let (after, effects) = reduce(state, .workspaceCommandIssued(.toggleFocus, workspace: key)) + let (after, effects) = reduce(state, .workspaceCommandIssued(command, workspace: key)) #expect(after.modes(for: key).focusedWindow == nil) #expect(effects.contains(.report(.noFocusedWindow))) #expect(after.focusedWindow == state.focusedWindow) diff --git a/Tests/ParcelEngineTests/WorkspaceTransactionTests.swift b/Tests/ParcelEngineTests/WorkspaceTransactionTests.swift new file mode 100644 index 00000000..ded57cd1 --- /dev/null +++ b/Tests/ParcelEngineTests/WorkspaceTransactionTests.swift @@ -0,0 +1,202 @@ +import Foundation +import ParcelConfig +import ParcelCore +import Testing + +@testable import ParcelEngine + +@MainActor +struct WorkspaceTransactionTests { + @Test(arguments: [ + "login", "highlight", "width", "motion", "mouse", "hover", "accessibility", "privacy", "shortcuts", + ]) + func configurationOnlyEditDoesNotScheduleLayout(field: String) async throws { + let harness = try EngineHarness() + try await harness.start() + try harness.add([1, 2]) + let passes = harness.engine.layoutPassCount + let scheduled = harness.scheduler.scheduledCount + let writes = harness.world.allWrites.count + let state = harness.engine.snapshot.state + var config = harness.engine.configuration + switch field { + case "login": config.general.launchAtLogin.toggle() + case "highlight": config.motion.highlight = .glow + case "width": config.motion.highlightWidth = 5 + case "motion": config.motion.enabled.toggle() + case "mouse": config.mouse.enabled.toggle() + case "hover": config.hoverBar.enabled.toggle() + case "accessibility": config.accessibility.announceLayoutChanges.toggle() + case "privacy": config.focusModes.noPeekLevel = 0.3 + case "shortcuts": config.keybindings.removeAll() + default: Issue.record("Unknown configuration fixture") + } + try harness.engine.applyConfiguration(config) + #expect(harness.engine.configuration == config) + #expect(harness.engine.snapshot.state == state) + #expect(harness.engine.layoutPassCount == passes) + #expect(harness.scheduler.scheduledCount == scheduled) + #expect(harness.world.allWrites.count == writes) + #expect(harness.engine.isIdle) + await harness.engine.stop() + } + + @Test(arguments: [false, true]) + func acceptsEngineClampedReadback(grid: Bool) async throws { + let harness = try EngineHarness() + harness.world.behaviors[engineApp] = + grid + ? FakeEngineWorld.Behavior(widthMultiple: 7) + : FakeEngineWorld.Behavior(minimumSize: Size(width: 1300, height: 900)) + try await harness.start() + try harness.add([1, 2]) + #expect(!harness.engine.frameAdjustments.isEmpty) + let scheduled = harness.scheduler.scheduledCount + try await harness.engine.awaitWorkspaceSettled(in: engineWorkspace) + #expect(harness.scheduler.scheduledCount == scheduled) + await harness.engine.stop() + } + + @Test func waitsForWriteReceiptWithoutPolling() async throws { + let harness = try EngineHarness() + try await harness.start() + harness.world.deferWrites = true + try harness.add([1]) + let scheduled = harness.scheduler.scheduledCount + let wait = Task { try await harness.engine.awaitWorkspaceSettled(in: engineWorkspace) } + while harness.engine.workspaceWaiters.isEmpty { await Task.yield() } + #expect(harness.scheduler.scheduledCount == scheduled + 1) + try harness.world.completeNextWrite() + try await wait.value + #expect(harness.engine.workspaceWaiters.isEmpty) + #expect(harness.scheduler.pendingCount == 0) + await harness.engine.stop() + } + + @Test func reportsSpecificFailedWindow() async throws { + let harness = try EngineHarness() + try await harness.start() + harness.world.behaviors[engineApp] = FakeEngineWorld.Behavior(timesOut: true) + try harness.add([1]) + await #expect(throws: EngineWorkspaceFailure.unsettled([WindowID(rawValue: 1)])) { + try await harness.engine.awaitWorkspaceSettled(in: engineWorkspace) + } + await harness.engine.stop() + } + + @Test(arguments: ["timeout", "cancel", "stop", "space", "pause"]) + func pendingWaitTerminates(reason: String) async throws { + let harness = try EngineHarness() + try await harness.start() + harness.world.deferWrites = true + try harness.add([1]) + let wait = Task { try await harness.engine.awaitWorkspaceSettled(in: engineWorkspace, timeout: .seconds(1)) } + while harness.engine.workspaceWaiters.isEmpty { await Task.yield() } + switch reason { + case "timeout": try harness.scheduler.advance(by: 1) + case "cancel": wait.cancel() + case "stop": await harness.engine.stop() + case "space": + harness.engine.send(.activeSpaceChanged(display: engineDisplay, space: SpaceID(rawValue: 10))) + try harness.scheduler.runReady() + case "pause": harness.engine.setPaused(true) + default: Issue.record("Unknown wait fixture") + } + do { + try await wait.value + Issue.record("The pending wait should fail") + } catch { + switch reason { + case "timeout": #expect(error as? EngineWorkspaceFailure == .unsettled([WindowID(rawValue: 1)])) + case "cancel": #expect(error is CancellationError) + case "stop": #expect(error as? EngineError == .stopped) + case "space": #expect(error as? EngineWorkspaceFailure == .workspaceUnavailable) + case "pause": #expect(error as? EngineWorkspaceFailure == .paused) + default: break + } + } + #expect(harness.engine.workspaceWaiters.isEmpty) + await harness.engine.stop() + } + + @Test func restorePreservesOtherDisplayAndNewWindows() async throws { + let harness = try EngineHarness(initialState: engineInitialState(twoDisplays: true)) + try await harness.start() + try harness.add([1, 2]) + let otherKey = WorkspaceKey(display: secondEngineDisplay, space: SpaceID(rawValue: 2)) + try harness.add([3, 4], app: secondEngineApp, workspace: otherKey) + let point = try harness.engine.captureWorkspaceRestorePoint(in: engineWorkspace) + let original = harness.engine.snapshot.state.workspaces[engineWorkspace] + harness.engine.send(.workspaceCommandIssued(.setLayout(.rows), workspace: engineWorkspace)) + harness.engine.send(.workspaceCommandIssued(.setLayout(.side), workspace: otherKey)) + try harness.scheduler.runReady() + try harness.add([5]) + harness.world.disappear(WindowID(rawValue: 2)) + try harness.scheduler.runReady() + let other = harness.engine.snapshot.state.workspaces[otherKey] + try await restore(point, using: harness) + #expect(harness.engine.snapshot.state.workspaces[engineWorkspace]?.layout == original?.layout) + #expect( + Set(harness.engine.snapshot.state.workspaces[engineWorkspace]?.order ?? []) == [ + WindowID(rawValue: 1), WindowID(rawValue: 5), + ]) + #expect(harness.engine.snapshot.state.workspaces[otherKey] == other) + #expect(harness.world.frames == harness.engine.snapshot.state.frames) + await harness.engine.stop() + } + + @Test func restoringPausedWorkspaceRestoresHandPlacedFramesWithoutMovingOtherDisplay() async throws { + let harness = try EngineHarness(initialState: engineInitialState(twoDisplays: true)) + try await harness.start() + try harness.add([1, 2]) + let otherKey = WorkspaceKey(display: secondEngineDisplay, space: SpaceID(rawValue: 2)) + try harness.add([3], app: secondEngineApp, workspace: otherKey) + harness.engine.setPaused(true) + let handPlaced = Rect(x: 80, y: 90, width: 380, height: 290) + harness.world.userFrame(WindowID(rawValue: 1), frame: handPlaced) + try harness.scheduler.runReady() + let point = try harness.engine.captureWorkspaceRestorePoint(in: engineWorkspace) + harness.engine.setPaused(false) + harness.engine.send(.workspaceCommandIssued(.setLayout(.rows), workspace: engineWorkspace)) + try harness.scheduler.runReady() + let otherFrame = harness.world.frames[WindowID(rawValue: 3)] + let writes = harness.world.allWrites.count + try await restore(point, using: harness) + #expect(harness.engine.isPaused) + #expect(harness.world.frames[WindowID(rawValue: 1)] == handPlaced) + #expect(harness.world.frames[WindowID(rawValue: 3)] == otherFrame) + #expect(!harness.world.allWrites.dropFirst(writes).contains { $0.window == WindowID(rawValue: 3) }) + await harness.engine.stop() + } + + private func restore(_ point: EngineWorkspaceRestorePoint, using harness: EngineHarness) async throws { + var finished = false + let task = Task { + defer { finished = true } + try await harness.engine.restoreWorkspace(point) + } + for _ in 0..<100 where !finished { + await Task.yield() + try harness.scheduler.advance(by: 0.5) + } + try await task.value + } + + @Test func restorePointCannotCrossEnginesOrDisconnectedSpaces() async throws { + let first = try EngineHarness() + let second = try EngineHarness() + try await first.start() + try await second.start() + let point = try first.engine.captureWorkspaceRestorePoint(in: engineWorkspace) + await #expect(throws: EngineWorkspaceFailure.workspaceUnavailable) { + try await second.engine.restoreWorkspace(point) + } + first.engine.send(.displaySetChanged([])) + try first.scheduler.runReady() + await #expect(throws: EngineWorkspaceFailure.workspaceUnavailable) { + try await first.engine.restoreWorkspace(point) + } + await first.engine.stop() + await second.engine.stop() + } +} -- knotmirror 0.0.1 From dcf86efb8014970861676472b5a78e713aec66e7 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 12:47:20 -0400 Subject: [PATCH 2/7] Use dashed motion settings keys --- Sources/ParcelConfig/ConfigJSONSchema.swift | 62 ++++---- Sources/ParcelConfig/ConfigValidator.swift | 32 +++- .../ParcelConfig/Resources/Schema.xcstrings | 4 + Sources/ParcelUI/Settings/SettingsModel.swift | 4 +- .../ConfigJSONSchemaTests.swift | 35 ++++- .../ConfigValidationTests.swift | 16 +- .../FocusModeConfigurationTests.swift | 4 +- .../HighlightConfigurationTests.swift | 137 ++++++++++++++++-- Tests/ParcelE2ETests/ParcelE2ETests.swift | 2 +- .../HighlightSettingsTests.swift | 58 ++++++++ .../Overlays/OverlayDimmingTests.swift | 6 +- docs/parcel.schema.json | 38 ++++- 12 files changed, 333 insertions(+), 65 deletions(-) diff --git a/Sources/ParcelConfig/ConfigJSONSchema.swift b/Sources/ParcelConfig/ConfigJSONSchema.swift index f949e4e4..13c50786 100644 --- a/Sources/ParcelConfig/ConfigJSONSchema.swift +++ b/Sources/ParcelConfig/ConfigJSONSchema.swift @@ -109,31 +109,7 @@ public enum ConfigJSONSchema { "launch-at-login": boolean(defaults.general.launchAtLogin), ]), "layout": object(layout), - "motion": object([ - "enabled": boolean(defaults.motion.enabled), - "level": choice( - ConfigMotionLevel.allCases.map(\.rawValue), defaultValue: defaults.motion.level.rawValue), - "speed": number(ConfigLimits.speed, defaultValue: defaults.motion.speed), - "transitions": choice( - ConfigMotionTransition.allCases.map(\.rawValue), - defaultValue: defaults.motion.transitions.rawValue), - "focus_border": .object([ - "type": .string("boolean"), "default": .bool(defaults.motion.focusBorder), - "deprecated": .bool(true), - "description": .string( - "Legacy active border switch. Used only when highlight is absent; explicit highlight takes precedence." - ), - ]), - "highlight": choice( - ConfigHighlight.allCases.map(\.rawValue), defaultValue: defaults.motion.highlight.rawValue), - "highlight-width": number( - MotionConfiguration.highlightWidths, defaultValue: defaults.motion.highlightWidth), - "drop_hints": boolean(defaults.motion.dropHints), - "experimental_dimming": boolean(defaults.motion.experimentalDimming), - "sound": boolean(defaults.motion.sound), - "menu_bar_icon": choice( - ConfigMenuBarIcon.allCases.map(\.rawValue), defaultValue: defaults.motion.menuBarIcon.rawValue), - ]), + "motion": motion(defaults.motion), "focus_modes": object([ "no_peek_level": number( FocusModeConfiguration.noPeekLevels, defaultValue: defaults.focusModes.noPeekLevel), @@ -211,6 +187,42 @@ public enum ConfigJSONSchema { ) } + private static func motion(_ defaults: MotionConfiguration) -> SchemaValue { + var properties: [String: SchemaValue] = [ + "enabled": boolean(defaults.enabled), + "level": choice(ConfigMotionLevel.allCases.map(\.rawValue), defaultValue: defaults.level.rawValue), + "speed": number(ConfigLimits.speed, defaultValue: defaults.speed), + "transitions": choice( + ConfigMotionTransition.allCases.map(\.rawValue), defaultValue: defaults.transitions.rawValue), + "focus-border": .object([ + "type": .string("boolean"), "default": .bool(defaults.focusBorder), + "deprecated": .bool(true), + "description": .string( + "Legacy active border switch. Used only when highlight is absent; explicit highlight takes precedence." + ), + ]), + "highlight": choice(ConfigHighlight.allCases.map(\.rawValue), defaultValue: defaults.highlight.rawValue), + "highlight-width": number(MotionConfiguration.highlightWidths, defaultValue: defaults.highlightWidth), + "drop-hints": boolean(defaults.dropHints), + "experimental-dimming": boolean(defaults.experimentalDimming), + "sound": boolean(defaults.sound), + "menu-bar-icon": choice( + ConfigMenuBarIcon.allCases.map(\.rawValue), defaultValue: defaults.menuBarIcon.rawValue), + ] + for (key, value) in properties where key.contains("-") { + guard case .object(var alias) = value else { + preconditionFailure("Motion properties must be schema objects.") + } + var description = + "Deprecated alias for motion.\(key). The dashed key takes precedence when both are present. Both values are validated." + if case .string(let original) = alias["description"] { description += " " + original } + alias["deprecated"] = .bool(true) + alias["description"] = .string(description) + properties[key.replacingOccurrences(of: "-", with: "_")] = .object(alias) + } + return object(properties) + } + private static func binding(_ command: ConfigCommand? = nil, defaultChord: KeyChord? = nil) -> SchemaValue { var property: [String: SchemaValue] = [ "oneOf": .array([ diff --git a/Sources/ParcelConfig/ConfigValidator.swift b/Sources/ParcelConfig/ConfigValidator.swift index 4f0081dc..d7000b42 100644 --- a/Sources/ParcelConfig/ConfigValidator.swift +++ b/Sources/ParcelConfig/ConfigValidator.swift @@ -175,28 +175,52 @@ private struct Validation { var result = MotionConfiguration() guard let node else { return result } let values = table(node, path: "motion", example: "[motion]\nenabled = true") + let dashedKeys = ["focus-border", "drop-hints", "experimental-dimming", "menu-bar-icon", "highlight-width"] unknownKeys( values, - allowed: [ - "enabled", "level", "speed", "transitions", "focus_border", "drop_hints", "experimental_dimming", - "sound", "menu_bar_icon", "highlight", "highlight-width", - ], + allowed: ["enabled", "level", "speed", "transitions", "sound", "highlight"] + + dashedKeys.flatMap { [$0, $0.replacingOccurrences(of: "-", with: "_")] }, path: "motion" ) + for key in dashedKeys { + let alias = key.replacingOccurrences(of: "-", with: "_") + guard let node = values[alias] else { continue } + let aliasPath = "motion.\(alias)" + let path = "motion.\(key)" + diagnostics.append( + ConfigDiagnostic( + severity: .warning, location: node.keyRange?.start ?? node.range.start, + message: String( + localized: + "“\(aliasPath)” is deprecated; use “\(path)”. The dashed key takes precedence when both are present.", + table: "Schema", bundle: .module + ), + relatedLocation: values[key]?.keyRange?.start ?? values[key]?.range.start + )) + } result.enabled = boolean(values["enabled"], path: "motion.enabled", fallback: result.enabled) result.level = choice(values["level"], path: "motion.level", fallback: result.level) result.speed = number(values["speed"], path: "motion.speed", fallback: result.speed, bounds: ConfigLimits.speed) result.transitions = choice(values["transitions"], path: "motion.transitions", fallback: result.transitions) + // Validate both spellings before applying precedence so an invalid alias cannot hide behind a valid key. result.focusBorder = boolean(values["focus_border"], path: "motion.focus_border", fallback: result.focusBorder) + result.focusBorder = boolean(values["focus-border"], path: "motion.focus-border", fallback: result.focusBorder) result.highlight = choice(values["highlight"], path: "motion.highlight", fallback: result.highlight) + result.highlightWidth = number( + values["highlight_width"], path: "motion.highlight_width", fallback: result.highlightWidth, + bounds: MotionConfiguration.highlightWidths) result.highlightWidth = number( values["highlight-width"], path: "motion.highlight-width", fallback: result.highlightWidth, bounds: MotionConfiguration.highlightWidths) result.dropHints = boolean(values["drop_hints"], path: "motion.drop_hints", fallback: result.dropHints) + result.dropHints = boolean(values["drop-hints"], path: "motion.drop-hints", fallback: result.dropHints) result.experimentalDimming = boolean( values["experimental_dimming"], path: "motion.experimental_dimming", fallback: result.experimentalDimming) + result.experimentalDimming = boolean( + values["experimental-dimming"], path: "motion.experimental-dimming", fallback: result.experimentalDimming) result.sound = boolean(values["sound"], path: "motion.sound", fallback: result.sound) result.menuBarIcon = choice(values["menu_bar_icon"], path: "motion.menu_bar_icon", fallback: result.menuBarIcon) + result.menuBarIcon = choice(values["menu-bar-icon"], path: "motion.menu-bar-icon", fallback: result.menuBarIcon) return result } diff --git a/Sources/ParcelConfig/Resources/Schema.xcstrings b/Sources/ParcelConfig/Resources/Schema.xcstrings index b43b5a05..b269066f 100644 --- a/Sources/ParcelConfig/Resources/Schema.xcstrings +++ b/Sources/ParcelConfig/Resources/Schema.xcstrings @@ -118,6 +118,10 @@ "extractionState" : "manual", "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "“%@” must be one of %@. For example: %@." } } } }, + "“%@” is deprecated; use “%@”. The dashed key takes precedence when both are present." : { + "extractionState" : "manual", + "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "“%@” is deprecated; use “%@”. The dashed key takes precedence when both are present." } } } + }, "Unknown key “%@”. Did you mean “%@”?" : { "extractionState" : "manual", "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Unknown key “%@”. Did you mean “%@”?" } } } diff --git a/Sources/ParcelUI/Settings/SettingsModel.swift b/Sources/ParcelUI/Settings/SettingsModel.swift index 2791d1f5..92ad38ae 100644 --- a/Sources/ParcelUI/Settings/SettingsModel.swift +++ b/Sources/ParcelUI/Settings/SettingsModel.swift @@ -19,8 +19,8 @@ public enum SettingsLayoutField: String, CaseIterable, Sendable { public enum SettingsMotionField: String, CaseIterable, Sendable { case enabled, level, speed, transitions, sound, highlight case highlightWidth = "highlight-width" - case focusBorder = "focus_border" - case menuBarIcon = "menu_bar_icon" + case focusBorder = "focus-border" + case menuBarIcon = "menu-bar-icon" } public enum SettingsMouseField: String, CaseIterable, Sendable { diff --git a/Tests/ParcelConfigTests/ConfigJSONSchemaTests.swift b/Tests/ParcelConfigTests/ConfigJSONSchemaTests.swift index b9e20611..91b5fcc6 100644 --- a/Tests/ParcelConfigTests/ConfigJSONSchemaTests.swift +++ b/Tests/ParcelConfigTests/ConfigJSONSchemaTests.swift @@ -98,8 +98,9 @@ struct ConfigJSONSchemaTests { let motion = try #require(schema()["properties"]?["motion"]?["properties"]?.object) #expect( Set(motion.keys) == [ - "enabled", "level", "speed", "transitions", "focus_border", "sound", "menu_bar_icon", "drop_hints", - "experimental_dimming", "highlight", "highlight-width", + "enabled", "level", "speed", "transitions", "sound", "highlight", + "focus-border", "menu-bar-icon", "drop-hints", "experimental-dimming", "highlight-width", + "focus_border", "menu_bar_icon", "drop_hints", "experimental_dimming", "highlight_width", ]) } @@ -111,8 +112,29 @@ struct ConfigJSONSchemaTests { #expect(motion["highlight-width"]?["minimum"] == .number(MotionConfiguration.highlightWidths.lowerBound)) #expect(motion["highlight-width"]?["maximum"] == .number(MotionConfiguration.highlightWidths.upperBound)) #expect(motion["highlight-width"]?["default"] == .number(2)) - #expect(motion["focus_border"]?["deprecated"] == .bool(true)) - #expect(motion["focus_border"]?["description"]?.string?.contains("explicit highlight takes precedence") == true) + for key in ["focus-border", "focus_border"] { + #expect(motion[key]?["deprecated"] == .bool(true)) + #expect(motion[key]?["description"]?.string?.contains("explicit highlight takes precedence") == true) + } + } + + @Test(arguments: ["focus-border", "menu-bar-icon", "drop-hints", "experimental-dimming", "highlight-width"]) + func schemaMotionAliasesPreserveConstraintsAndExplainPrecedence(key: String) throws { + let properties = try #require(schema()["properties"]?["motion"]?["properties"]) + let aliasKey = key.replacingOccurrences(of: "-", with: "_") + var canonical = try #require(properties[key]?.object) + var alias = try #require(properties[aliasKey]?.object) + #expect(alias["deprecated"] == .bool(true)) + let description = try #require(alias["description"]?.string) + #expect(description.contains("Deprecated alias for motion.\(key)")) + #expect(description.contains("dashed key takes precedence")) + #expect(description.contains("Both values are validated")) + if key != "focus-border" { #expect(canonical["deprecated"] == nil) } + for metadata in ["description", "deprecated"] { + canonical.removeValue(forKey: metadata) + alias.removeValue(forKey: metadata) + } + #expect(alias == canonical) } @Test func schemaFocusModesMatchDefaultsAndValidation() throws { @@ -155,7 +177,7 @@ struct ConfigJSONSchemaTests { } @Test func schemaMenuBarIconEnumMatchesModel() throws { - let icon = try schema()["properties"]?["motion"]?["properties"]?["menu_bar_icon"] + let icon = try schema()["properties"]?["motion"]?["properties"]?["menu-bar-icon"] #expect(icon?["type"] == .string("string")) #expect(icon?["enum"] == .array(ConfigMenuBarIcon.allCases.map { .string($0.rawValue) })) #expect(icon?["default"] == .string(ParcelConfiguration.defaults.motion.menuBarIcon.rawValue)) @@ -165,7 +187,8 @@ struct ConfigJSONSchemaTests { let motion = try schema()["properties"]?["motion"]?["properties"] let defaults = ParcelConfiguration.defaults.motion for (key, expected) in [ - ("enabled", defaults.enabled), ("focus_border", defaults.focusBorder), ("sound", defaults.sound), + ("enabled", defaults.enabled), ("focus-border", defaults.focusBorder), ("sound", defaults.sound), + ("drop-hints", defaults.dropHints), ("experimental-dimming", defaults.experimentalDimming), ] { #expect(motion?[key]?["type"] == .string("boolean")) #expect(motion?[key]?["default"] == .bool(expected)) diff --git a/Tests/ParcelConfigTests/ConfigValidationTests.swift b/Tests/ParcelConfigTests/ConfigValidationTests.swift index 8502108d..c9a250ac 100644 --- a/Tests/ParcelConfigTests/ConfigValidationTests.swift +++ b/Tests/ParcelConfigTests/ConfigValidationTests.swift @@ -544,11 +544,11 @@ struct ConfigValidationTests { @Test(arguments: ConfigMenuBarIcon.allCases) func everyMenuBarIconIsAccepted(_ icon: ConfigMenuBarIcon) throws { - #expect(try configuration("[motion]\nmenu_bar_icon = \"\(icon.rawValue)\"").motion.menuBarIcon == icon) + #expect(try configuration("[motion]\nmenu-bar-icon = \"\(icon.rawValue)\"").motion.menuBarIcon == icon) } @Test( - arguments: ["level", "transitions", "menu_bar_icon"], ["\"maximum\"", "\"Playful\"", "false", "1", "[]", "{}"]) + arguments: ["level", "transitions", "menu-bar-icon"], ["\"maximum\"", "\"Playful\"", "false", "1", "[]", "{}"]) func invalidMotionChoicesAreRejectedWithValueLocations(key: String, value: String) throws { let document = try TOMLDocument(parsing: "[motion]\n\(key) = \(value)") let result = ConfigValidator.validate(document) @@ -568,9 +568,9 @@ struct ConfigValidationTests { level = "extra" speed = 1.5 transitions = "ghost" - focus_border = false + focus-border = false sound = true - menu_bar_icon = "logo" + menu-bar-icon = "logo" """ ).motion #expect( @@ -583,11 +583,11 @@ struct ConfigValidationTests { @Test func omittedMotionSettingsUseDefaults() throws { #expect(try configuration("[motion]").motion == MotionConfiguration()) #expect(try configuration("[motion]\nsound = true").motion == MotionConfiguration(sound: true)) - #expect(try configuration("[motion]\nfocus_border = false").motion == MotionConfiguration(focusBorder: false)) + #expect(try configuration("[motion]\nfocus-border = false").motion == MotionConfiguration(focusBorder: false)) } - @Test(arguments: ["whimsy", "focus-border", "menu-bar-icon"]) - func obsoleteMotionKeysWarnRatherThanChangeDefaults(key: String) throws { + @Test(arguments: ["whimsy", "focus-bordr", "menu-bar-icn"]) + func unknownMotionKeysWarnRatherThanChangeDefaults(key: String) throws { let result = try validate("[motion]\n\(key) = \"extra\"") #expect(result.configuration?.motion == MotionConfiguration()) #expect(result.diagnostics.count == 1) @@ -601,7 +601,7 @@ struct ConfigValidationTests { } @Test(arguments: [ - "general.launch-at-login", "motion.enabled", "motion.focus_border", "motion.sound", + "general.launch-at-login", "motion.enabled", "motion.focus-border", "motion.sound", "accessibility.announce-layout-changes", ]) func booleansRejectStrings(_ path: String) throws { diff --git a/Tests/ParcelConfigTests/FocusModeConfigurationTests.swift b/Tests/ParcelConfigTests/FocusModeConfigurationTests.swift index 4a09f762..a6bd6401 100644 --- a/Tests/ParcelConfigTests/FocusModeConfigurationTests.swift +++ b/Tests/ParcelConfigTests/FocusModeConfigurationTests.swift @@ -61,8 +61,8 @@ import Testing #expect(!FocusModeConfiguration(noPeekLevel: level).isValid) } - @Test func legacyDimmingKeyRemainsAcceptedAlongsideNewPreferences() throws { - let value = try configuration("[focus_modes]\nno_peek_level = 0.7\n[motion]\nexperimental_dimming = true\n") + @Test func dimmingKeyRemainsAcceptedAlongsideFocusPreferences() throws { + let value = try configuration("[focus_modes]\nno_peek_level = 0.7\n[motion]\nexperimental-dimming = true\n") #expect(value.motion.experimentalDimming) #expect(value.focusModes.noPeekLevel == 0.7) } diff --git a/Tests/ParcelConfigTests/HighlightConfigurationTests.swift b/Tests/ParcelConfigTests/HighlightConfigurationTests.swift index 78454c1b..9a2027bb 100644 --- a/Tests/ParcelConfigTests/HighlightConfigurationTests.swift +++ b/Tests/ParcelConfigTests/HighlightConfigurationTests.swift @@ -1,3 +1,4 @@ +import Foundation import ParcelConfig import Testing @@ -40,20 +41,28 @@ import Testing #expect(error.message.contains("motion.highlight")) } - @Test(arguments: [true, false]) - func legacyBorderSwitchStillWorks(enabled: Bool) throws { - let value = try configuration("[motion]\nfocus_border = \(enabled)\n") + @Test(arguments: ["focus-border", "focus_border"], [true, false]) + func legacyBorderSwitchStillWorks(key: String, enabled: Bool) throws { + let result = ConfigValidator.validate(try TOMLDocument(parsing: "[motion]\n\(key) = \(enabled)\n")) + let value = try #require(result.configuration) #expect(value.motion.highlight == (enabled ? .active : .none)) #expect(MotionConfiguration(focusBorder: enabled).highlight == value.motion.highlight) + #expect(result.diagnostics.count == (key == "focus_border" ? 1 : 0)) + #expect(result.diagnostics.allSatisfy { $0.severity == .warning }) } @Test(arguments: ConfigHighlight.allCases, [true, false]) func explicitHighlightWinsOverLegacySwitch(style: ConfigHighlight, enabled: Bool) throws { - for assignments in [ - "focus_border = \(enabled)\nhighlight = '\(style.rawValue)'", - "highlight = '\(style.rawValue)'\nfocus_border = \(enabled)", - ] { - #expect(try configuration("[motion]\n\(assignments)\n").motion.highlight == style) + for key in ["focus-border", "focus_border"] { + for assignments in [ + "\(key) = \(enabled)\nhighlight = '\(style.rawValue)'", + "highlight = '\(style.rawValue)'\n\(key) = \(enabled)", + ] { + let result = ConfigValidator.validate(try TOMLDocument(parsing: "[motion]\n\(assignments)\n")) + #expect(result.configuration?.motion.highlight == style) + #expect(result.diagnostics.count == (key == "focus_border" ? 1 : 0)) + #expect(result.diagnostics.allSatisfy { $0.severity == .warning }) + } } } @@ -78,12 +87,114 @@ import Testing #expect(configuration.highlightWidth == 4) } - @Test func misspelledWidthProducesAnActionableWarning() throws { - let result = ConfigValidator.validate(try TOMLDocument(parsing: "[motion]\nhighlight_width = 4\n")) - #expect(result.configuration?.motion.highlightWidth == 2) - let warning = try #require(result.diagnostics.first) + @Test(arguments: [false, true]) + func multiwordMotionKeysAcceptCanonicalAndDeprecatedSpellings(legacy: Bool) throws { + let assignments = """ + focus-border = false + drop-hints = false + experimental-dimming = true + menu-bar-icon = 'logo' + highlight-width = 5.5 + """ + let source = "[motion]\n" + (legacy ? assignments.replacingOccurrences(of: "-", with: "_") : assignments) + let document = try TOMLDocument(parsing: source) + let result = ConfigValidator.validate(document) + #expect( + result.configuration?.motion + == MotionConfiguration( + dropHints: false, experimentalDimming: true, menuBarIcon: .logo, + highlight: .none, highlightWidth: 5.5)) + #expect(result.diagnostics.count == (legacy ? 5 : 0)) + for key in Self.dashedKeys where legacy { + try expectDeprecation(for: key, in: document, diagnostics: result.diagnostics) + } + } + + @Test(arguments: [false, true]) + func canonicalValuesWinRegardlessOfSourceOrder(legacyFirst: Bool) throws { + let canonical = """ + focus-border = false + drop-hints = false + experimental-dimming = true + menu-bar-icon = 'logo' + highlight-width = 5.5 + """ + let legacy = """ + focus_border = true + drop_hints = true + experimental_dimming = false + menu_bar_icon = 'minimap' + highlight_width = 2 + """ + let assignments = legacyFirst ? [legacy, canonical] : [canonical, legacy] + let document = try TOMLDocument(parsing: "[motion]\n" + assignments.joined(separator: "\n")) + let result = ConfigValidator.validate(document) + #expect(result.configuration == (try configuration("[motion]\n" + canonical))) + #expect(result.diagnostics.count == 5) + for key in Self.dashedKeys { + try expectDeprecation(for: key, in: document, diagnostics: result.diagnostics) + } + let withHighlight = ConfigValidator.validate( + try TOMLDocument(parsing: document.render() + "\nhighlight = 'glow'\n")) + #expect(withHighlight.configuration?.motion.highlight == .glow) + } + + @Test(arguments: ["focus-border", "drop-hints", "experimental-dimming"], ["'false'", "1", "[]", "{}"]) + func invalidBooleanAliasesCannotBeHidden(key: String, invalid: String) throws { + try expectInvalidSpellings(key: key, valid: "false", invalid: invalid) + } + + @Test(arguments: ["'unknown'", "'Logo'", "true", "1", "[]", "{}"]) + func invalidMenuIconAliasesCannotBeHidden(invalid: String) throws { + try expectInvalidSpellings(key: "menu-bar-icon", valid: "'logo'", invalid: invalid) + } + + @Test(arguments: ["1.99", "6.01", "nan", "inf", "-inf", "'2'", "true", "[]", "{}"]) + func invalidWidthAliasesCannotBeHidden(invalid: String) throws { + try expectInvalidSpellings(key: "highlight-width", valid: "4", invalid: invalid) + } + + private static let dashedKeys = [ + "focus-border", "drop-hints", "experimental-dimming", "menu-bar-icon", "highlight-width", + ] + + private func expectDeprecation(for key: String, in document: TOMLDocument, diagnostics: [ConfigDiagnostic]) throws { + let alias = key.replacingOccurrences(of: "-", with: "_") + let node = try #require(document.root["motion"]?[alias]) + let warning = try #require(diagnostics.first { $0.location == node.keyRange?.start }) #expect(warning.severity == .warning) - #expect(warning.message.contains("highlight-width")) + #expect(warning.message.contains("motion.\(alias)")) + #expect(warning.message.contains("motion.\(key)")) + #expect(warning.message.contains("is deprecated")) + #expect(warning.message.contains("dashed key takes precedence")) + #expect(warning.relatedLocation == document.root["motion"]?[key]?.keyRange?.start) + } + + private func expectInvalidSpellings(key: String, valid: String, invalid: String) throws { + let alias = key.replacingOccurrences(of: "-", with: "_") + for (badKey, goodKey) in [(alias, key), (key, alias)] { + let invalidAssignment = "\(badKey) = \(invalid)" + let validAssignment = "\(goodKey) = \(valid)" + for assignments in [ + invalidAssignment, + invalidAssignment + "\n" + validAssignment, + validAssignment + "\n" + invalidAssignment, + ] { + let document = try TOMLDocument(parsing: "[motion]\n" + assignments) + let result = ConfigValidator.validate(document) + #expect(result.configuration == nil) + let errors = result.diagnostics.filter { $0.severity == .error } + #expect(errors.count == 1) + let error = try #require(errors.first) + #expect(error.location == document.root["motion"]?[badKey]?.range.start) + #expect(error.message.contains("motion.\(badKey)")) + let warnings = result.diagnostics.filter { $0.severity == .warning } + #expect(warnings.count == (document.root["motion"]?[alias] == nil ? 0 : 1)) + if !warnings.isEmpty { + try expectDeprecation(for: key, in: document, diagnostics: warnings) + } + } + } } private func configuration(_ source: String) throws -> ParcelConfiguration { diff --git a/Tests/ParcelE2ETests/ParcelE2ETests.swift b/Tests/ParcelE2ETests/ParcelE2ETests.swift index ee10cdec..061ceb01 100644 --- a/Tests/ParcelE2ETests/ParcelE2ETests.swift +++ b/Tests/ParcelE2ETests/ParcelE2ETests.swift @@ -358,7 +358,7 @@ struct E2EConfiguration { [motion] enabled = \(motion) transitions = "\(transition)" - focus_border = \(focusBorder) + focus-border = \(focusBorder) """ + "\n" if let floatTitle { text += "\n[[float-rules]]\ntitle-regex = \"\(floatTitle)\"\n" diff --git a/Tests/ParcelUITests/HighlightSettingsTests.swift b/Tests/ParcelUITests/HighlightSettingsTests.swift index 48ad2ca4..2e732e7b 100644 --- a/Tests/ParcelUITests/HighlightSettingsTests.swift +++ b/Tests/ParcelUITests/HighlightSettingsTests.swift @@ -54,10 +54,68 @@ import Testing } } + @Test(arguments: [false, true]) + func motionWritesUseDashedKeysAndPreserveExistingAliases(legacy: Bool) async throws { + let legacyAssignments = + "focus_border = true # border\r\nmenu_bar_icon = 'minimap' # icon\r\nhighlight_width = 2 # width\r\n" + let source = "# Keep this\r\n[motion]\r\n" + (legacy ? legacyAssignments : "") + try await withModel(source: source) { model, file in + #expect(model.error == nil) + #expect(model.diagnostics.count == (legacy ? 3 : 0)) + try await model.setValue(.bool(false), for: .motion(.focusBorder)) + try await model.setValue(.string("logo"), for: .motion(.menuBarIcon)) + try await model.setValue(.float(5.5), for: .motion(.highlightWidth)) + try await model.setValue(.float(4), for: .motion(.highlightWidth)) + #expect(model.configuration.motion.highlight == .none) + #expect(model.configuration.motion.menuBarIcon == .logo) + #expect(model.configuration.motion.highlightWidth == 4) + let saved = try String(contentsOf: file, encoding: .utf8) + #expect(saved.hasPrefix("# Keep this\r\n[motion]\r\n")) + #expect(saved.contains("\"focus-border\" = false\r\n")) + #expect(saved.contains("\"menu-bar-icon\" = \"logo\"\r\n")) + #expect(saved.contains("\"highlight-width\" = 4.0\r\n")) + if legacy { + #expect(saved.contains(legacyAssignments)) + } else { + for key in ["focus_border", "menu_bar_icon", "highlight_width"] { + #expect(!saved.contains(key)) + } + } + let result = ConfigValidator.validate(try TOMLDocument(parsing: saved)) + #expect(result.configuration == model.configuration) + #expect(result.diagnostics.count == (legacy ? 3 : 0)) + #expect(result.diagnostics.allSatisfy { $0.severity == .warning && $0.message.contains("is deprecated") }) + #expect(model.diagnostics == result.diagnostics) + } + } + + @Test(arguments: [ + "focus-border = false\nfocus_border = 'true'", + "menu-bar-icon = 'logo'\nmenu_bar_icon = 'invalid'", + "highlight-width = 4\nhighlight_width = 99", + "drop-hints = true\ndrop_hints = 'false'", + "experimental-dimming = false\nexperimental_dimming = 'true'", + ]) + func invalidLosingAliasesBlockSaves(assignments: String) async throws { + let source = "[motion]\n" + assignments + "\n" + try await withModel(source: source) { model, file in + #expect(model.error != nil) + #expect(model.diagnostics.filter { $0.severity == .error }.count == 1) + #expect(model.diagnostics.filter { $0.severity == .warning }.count == 1) + await #expect(throws: SettingsFailure.self) { + try await model.setValue(.float(5), for: .motion(.highlightWidth)) + } + let saved = try String(contentsOf: file, encoding: .utf8) + #expect(saved == source) + } + } + @Test func fieldPathsUseThePublishedKeys() throws { let document = try TOMLDocument(parsing: "") #expect(SettingsField.motion(.highlight).path(in: document) == ["motion", "highlight"]) #expect(SettingsField.motion(.highlightWidth).path(in: document) == ["motion", "highlight-width"]) + #expect(SettingsField.motion(.focusBorder).path(in: document) == ["motion", "focus-border"]) + #expect(SettingsField.motion(.menuBarIcon).path(in: document) == ["motion", "menu-bar-icon"]) } @Test func publicPreferencesRenderWithoutWindowAccess() throws { diff --git a/Tests/ParcelUITests/Overlays/OverlayDimmingTests.swift b/Tests/ParcelUITests/Overlays/OverlayDimmingTests.swift index a13d6141..f73babc7 100644 --- a/Tests/ParcelUITests/Overlays/OverlayDimmingTests.swift +++ b/Tests/ParcelUITests/Overlays/OverlayDimmingTests.swift @@ -153,13 +153,13 @@ extension OverlayTestSuite { let defaults = MotionConfiguration() #expect(defaults.dropHints && !defaults.experimentalDimming) let result = ConfigValidator.validate( - try TOMLDocument(parsing: "[motion]\ndrop_hints = false\nexperimental_dimming = true")) + try TOMLDocument(parsing: "[motion]\ndrop-hints = false\nexperimental-dimming = true")) #expect(result.diagnostics.isEmpty) let configuration = try #require(result.configuration) #expect(!configuration.motion.dropHints && configuration.motion.experimentalDimming) } - @Test(arguments: ["drop_hints", "experimental_dimming"]) + @Test(arguments: ["drop-hints", "experimental-dimming"]) func newConfigKnobsRejectWrongTypesAndAppearInSchema(key: String) throws { let result = ConfigValidator.validate(try TOMLDocument(parsing: "[motion]\n\(key) = 1")) #expect(result.configuration == nil) @@ -171,7 +171,7 @@ extension OverlayTestSuite { let knobs = try #require(motion["properties"] as? [String: Any]) let knob = try #require(knobs[key] as? [String: Any]) #expect(knob["type"] as? String == "boolean") - #expect(knob["default"] as? Bool == (key == "drop_hints")) + #expect(knob["default"] as? Bool == (key == "drop-hints")) } } } diff --git a/docs/parcel.schema.json b/docs/parcel.schema.json index 0bfcd7da..55bbe468 100644 --- a/docs/parcel.schema.json +++ b/docs/parcel.schema.json @@ -4011,24 +4011,42 @@ "motion" : { "additionalProperties" : true, "properties" : { + "drop-hints" : { + "default" : true, + "type" : "boolean" + }, "drop_hints" : { "default" : true, + "deprecated" : true, + "description" : "Deprecated alias for motion.drop-hints. The dashed key takes precedence when both are present. Both values are validated.", "type" : "boolean" }, "enabled" : { "default" : true, "type" : "boolean" }, + "experimental-dimming" : { + "default" : false, + "type" : "boolean" + }, "experimental_dimming" : { "default" : false, + "deprecated" : true, + "description" : "Deprecated alias for motion.experimental-dimming. The dashed key takes precedence when both are present. Both values are validated.", "type" : "boolean" }, - "focus_border" : { + "focus-border" : { "default" : true, "deprecated" : true, "description" : "Legacy active border switch. Used only when highlight is absent; explicit highlight takes precedence.", "type" : "boolean" }, + "focus_border" : { + "default" : true, + "deprecated" : true, + "description" : "Deprecated alias for motion.focus-border. The dashed key takes precedence when both are present. Both values are validated. Legacy active border switch. Used only when highlight is absent; explicit highlight takes precedence.", + "type" : "boolean" + }, "highlight" : { "default" : "active", "enum" : [ @@ -4045,6 +4063,14 @@ "minimum" : 2, "type" : "number" }, + "highlight_width" : { + "default" : 2, + "deprecated" : true, + "description" : "Deprecated alias for motion.highlight-width. The dashed key takes precedence when both are present. Both values are validated.", + "maximum" : 6, + "minimum" : 2, + "type" : "number" + }, "level" : { "default" : "playful", "enum" : [ @@ -4054,8 +4080,18 @@ ], "type" : "string" }, + "menu-bar-icon" : { + "default" : "minimap", + "enum" : [ + "minimap", + "logo" + ], + "type" : "string" + }, "menu_bar_icon" : { "default" : "minimap", + "deprecated" : true, + "description" : "Deprecated alias for motion.menu-bar-icon. The dashed key takes precedence when both are present. Both values are validated.", "enum" : [ "minimap", "logo" -- knotmirror 0.0.1 From c64a194b08d97f4b0a27763d013867f8adb41ff4 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 12:47:26 -0400 Subject: [PATCH 3/7] Clip highlights safely and reuse their layers --- .../ParcelUI/Overlays/OverlayController.swift | 196 +++++++++++----- .../ParcelUI/Overlays/OverlayGeometry.swift | 211 ++++++++++++----- Sources/ParcelUI/Overlays/OverlayPanel.swift | 4 +- .../ParcelUI/Overlays/OverlaySnapshot.swift | 15 +- .../ParcelUI/Overlays/PrivacyWindows.swift | 7 +- .../HighlightEndToEndTests.swift | 86 +++++++ .../Overlays/HighlightTests.swift | 220 ++++++++++++++++++ .../Overlays/OverlaySnapshotTests.swift | 31 ++- .../ParcelUITests/Overlays/OverlayTests.swift | 25 +- 9 files changed, 660 insertions(+), 135 deletions(-) create mode 100644 Tests/ParcelE2ETests/HighlightEndToEndTests.swift diff --git a/Sources/ParcelUI/Overlays/OverlayController.swift b/Sources/ParcelUI/Overlays/OverlayController.swift index d0b44004..891a0679 100644 --- a/Sources/ParcelUI/Overlays/OverlayController.swift +++ b/Sources/ParcelUI/Overlays/OverlayController.swift @@ -30,6 +30,10 @@ public final class OverlayController { private var privacyRevision: UInt64 = 0 private var nativeDimmingWindows: [OverlayWindow]? private var nativeWindows: [UInt32: OverlayWindow]? + private var nativeHighlightWindows: [UInt32: OverlayWindow]? + private var requiresNativeHighlightWindows = false + private var nativeReadPending = false + private let windowReader: @Sendable () throws -> [PrivacyWindowInfo] private var frameRevision: UInt64 = 0 private var observedPrivacyFrames: [UInt32: (revision: UInt64, frame: CGRect)] = [:] private var privacySuspended = false @@ -69,6 +73,7 @@ public final class OverlayController { brightness: (any OverlayBrightnessControlling)? = nil, color: @escaping @MainActor () -> NSColor = { .controlAccentColor }, notifications: OverlayNotifications, + windowReader: @escaping @Sendable () throws -> [PrivacyWindowInfo] = { try PrivacyWindowInfo.read() }, onFailure: @escaping @MainActor (any Error) -> Void ) { self.configuration = configuration @@ -76,12 +81,16 @@ public final class OverlayController { self.accessibility = accessibility self.color = color self.onFailure = onFailure + self.windowReader = windowReader dimming = OverlayDimming(brightness: brightness ?? PlatformOverlayBrightness(), onFailure: onFailure) dimming.onChange = { [weak self] in self?.renderPrivacy() } dimming.launch(enabled: configuration.enabled && configuration.experimentalDimming) observe(NSApplication.willTerminateNotification, center: notifications.application) { $0.stop() } observe(NSApplication.didChangeScreenParametersNotification, center: notifications.application) { $0.refresh() } observe(NSWorkspace.activeSpaceDidChangeNotification, center: notifications.workspace) { + $0.privacyRevision += 1 + $0.privacyRead?.cancel() + $0.nativeHighlightWindows = nil for id in $0.panels.keys { $0.removeLayers(display: id) } $0.clearTransientLayers() $0.dragTarget = nil @@ -92,15 +101,18 @@ public final class OverlayController { observe(NSWorkspace.didWakeNotification, center: notifications.workspace) { $0.privacySuspended = false $0.renderPrivacy() + if $0.requiresNativeHighlightWindows { $0.refreshPrivacyWindows() } } observe(NSWorkspace.sessionDidBecomeActiveNotification, center: notifications.workspace) { $0.privacySuspended = false $0.renderPrivacy() + if $0.requiresNativeHighlightWindows { $0.refreshPrivacyWindows() } } observeDistributed(Notification.Name("com.apple.screenIsLocked")) { $0.suspendPrivacy() } observeDistributed(Notification.Name("com.apple.screenIsUnlocked")) { $0.privacySuspended = false $0.renderPrivacy() + if $0.requiresNativeHighlightWindows { $0.refreshPrivacyWindows() } } if let notification = Self.simulatedSleepNotification(environment: ProcessInfo.processInfo.environment) { observeDistributed(notification) { $0.suspendPrivacy() } @@ -139,9 +151,9 @@ public final class OverlayController { public func consume( _ value: EngineSnapshot, cornerRadius: @MainActor (WindowID) -> CGFloat = { _ in 10 } ) { + requiresNativeHighlightWindows = true setDisplays(Self.systemDisplays(), primaryDisplayHeight: NSScreen.screens.first?.frame.height ?? 0) update(OverlaySnapshot(value, transitions: configuration.transitions, cornerRadius: cornerRadius)) - refreshPrivacyWindows() } public func setDisplays(_ displays: [OverlayDisplay], primaryDisplayHeight: CGFloat) { @@ -179,6 +191,7 @@ public final class OverlayController { if previous?.context != next.context { nativeDimmingWindows = nil nativeWindows = nil + nativeHighlightWindows = nil observedPrivacyFrames = [:] } privacyRevision += 1 @@ -190,13 +203,14 @@ public final class OverlayController { } let active = configuration.enabled renderPrivacy() - renderFocus(previous: previous) + renderFocus() if active, configuration.transitions == .ghost, let previous, previous.context == next.context { renderGhosts(previous: previous, next: next) } else { clearGhosts() } refreshPanelVisibility() + if requiresNativeHighlightWindows { refreshPrivacyWindows() } } public func update( @@ -207,10 +221,11 @@ public final class OverlayController { if let focusModes { self.focusModes = focusModes } self.accessibility = accessibility clearTransientLayers() - renderFocus(previous: nil) + renderFocus() renderPrivacy() if let dragTarget { dragChanged(target: dragTarget) } refreshPanelVisibility() + if requiresNativeHighlightWindows { refreshPrivacyWindows() } } public func dragChanged(target: OverlayWindow?) { @@ -252,9 +267,10 @@ public final class OverlayController { } public func refused(_ direction: Direction) { - let horizontal: Double = direction == .left ? -1 : direction == .right ? 1 : 0 - let vertical: Double = direction == .up ? 1 : direction == .down ? -1 : 0 - for tile in focusLayers.values { tile.nudge(horizontal: horizontal, vertical: vertical, motion: currentMotion) } + let motion = OverlayMotion(configuration: configuration, accessibility: accessibility, geometry: false) + for tile in focusLayers.values { + tile.move(to: tile.layer.frame, radius: tile.layer.cornerRadius, motion: motion, token: .fade) + } } public var activeAnimationCount: Int { @@ -265,6 +281,19 @@ public final class OverlayController { public var privacyPanelCount: Int { privacyPanels.count } public var cleanSpaceBackdropCount: Int { backdrops.count } + public func highlightAudit() -> OverlayHighlightAudit { + OverlayHighlightAudit( + ready: snapshot != nil && !privacySuspended && !nativeReadPending + && (!requiresNativeHighlightWindows || nativeHighlightWindows != nil), + displays: highlightCanvases.keys.sorted().compactMap { id in + guard let canvas = highlightCanvases[id], let display = panels[id]?.display else { return nil } + let focused = focusLayers[id] == nil ? [] : snapshot?.focusedWindow.map { [$0] } ?? [] + return OverlayHighlightAudit.Display( + id: id, frame: display.frame, cutouts: canvas.cutouts, gaps: canvas.gaps, + outlinedWindows: (Array(canvas.inactive.keys) + focused).sorted()) + }) + } + public func stop() { subscription?.cancel() subscription = nil @@ -282,7 +311,7 @@ public final class OverlayController { observers = [] } - private func renderPrivacy() { + private func renderPrivacy(displays: Set? = nil) { guard let snapshot else { return } let windows = (nativeDimmingWindows ?? snapshot.windows).map(latestPrivacyWindow) let solid = accessibility.reduceTransparency || accessibility.increaseContrast @@ -303,7 +332,7 @@ public final class OverlayController { } } dimming.update(offsets: offsets) - for (id, panel) in panels { + for (id, panel) in panels where displays?.contains(id) ?? true { let workspace = snapshot.privacyWorkspaces.first { $0.key.display.rawValue == id } let noPeek = workspace?.noPeek == true && !privacySuspended let clean = @@ -349,6 +378,8 @@ public final class OverlayController { cleanSpaceSuspended.formUnion(snapshot?.privacyWorkspaces.map(\.key) ?? []) clearPrivacy() dimming.restore() + renderFocus() + refreshPanelVisibility() onSessionSuspended?() } @@ -356,8 +387,10 @@ public final class OverlayController { privacyRevision += 1 privacyRead?.cancel() privacyRead = nil + nativeReadPending = false nativeDimmingWindows = nil nativeWindows = nil + nativeHighlightWindows = nil observedPrivacyFrames = [:] nativeProtectedWindows = [:] for panel in privacyPanels.values { panel.close() } @@ -386,14 +419,31 @@ public final class OverlayController { public func observePrivacyFrame(_ observed: WindowFrame) { precondition(observed.frame.isValid) - guard snapshot?.privacyWorkspaces.isEmpty == false else { return } - frameRevision += 1 + guard let snapshot, needsWindowRead, !privacySuspended else { return } + let id = observed.window.rawValue + let previous = + observedPrivacyFrames[id]?.frame ?? nativeWindows?[id]?.focusFrame + ?? snapshot.windows.first { $0.id == id }?.focusFrame + ?? snapshot.highlightCutouts.first { $0.id == id }?.focusFrame + ?? snapshot.privacyWorkspaces.flatMap(\.protectedWindows).first { $0.id == id }?.focusFrame let frame = observed.frame - observedPrivacyFrames[observed.window.rawValue] = ( - frameRevision, CGRect(x: frame.minX, y: frame.minY, width: frame.size.width, height: frame.size.height) - ) - renderPrivacy() - renderFocus(previous: snapshot) + let rectangle = CGRect(x: frame.minX, y: frame.minY, width: frame.size.width, height: frame.size.height) + guard previous != rectangle else { return } + frameRevision += 1 + observedPrivacyFrames[id] = (frameRevision, rectangle) + let affected = Set( + panels.compactMap { id, panel in + panel.display.frame.intersects(rectangle) || previous.map(panel.display.frame.intersects) == true + ? id : nil + }) + renderPrivacy(displays: affected) + renderFocus(displays: affected) + refreshPanelVisibility() + } + + private var needsWindowRead: Bool { + configuration.highlight != .none || snapshot?.privacyWorkspaces.isEmpty == false + || (configuration.enabled && configuration.experimentalDimming) } public func refreshPrivacyWindows() { @@ -401,15 +451,34 @@ public final class OverlayController { let revision = privacyRevision let readFrameRevision = frameRevision privacyRead?.cancel() - guard let snapshot, !snapshot.privacyWorkspaces.isEmpty, !privacySuspended else { return } + guard let snapshot, needsWindowRead, !privacySuspended else { return } + requiresNativeHighlightWindows = true + nativeReadPending = true + for canvas in highlightCanvases.values { withoutImplicitAnimations { canvas.layer.isHidden = true } } + if nativeHighlightWindows == nil { + renderFocus() + refreshPanelVisibility() + } let focused = observedFocusedWindow.map { $0()?.rawValue } ?? snapshot.focusedWindow + let reader = windowReader privacyRead = Task { [weak self] in - let result = await Task.detached { Result { try PrivacyWindowInfo.read() } }.value + let result = await Task.detached { Result { try reader() } }.value guard !Task.isCancelled, let self, privacyRevision == revision else { return } + privacyRead = nil + nativeReadPending = false switch result { case .success(let windows): applyPrivacyWindows(windows, focusedWindow: focused, readFrameRevision: readFrameRevision) - case .failure(let error): onFailure(error) + case .failure(let error): + nativeHighlightWindows = nil + nativeWindows = [:] + nativeDimmingWindows = [] + nativeProtectedWindows = [:] + observedPrivacyFrames = [:] + renderPrivacy() + renderFocus() + refreshPanelVisibility() + onFailure(OverlayWindowReadError(underlying: error)) } } } @@ -418,10 +487,20 @@ public final class OverlayController { _ windows: [PrivacyWindowInfo], focusedWindow: UInt32?, readFrameRevision: UInt64 = .max ) { guard let snapshot, !privacySuspended else { return } + nativeReadPending = false observedPrivacyFrames = observedPrivacyFrames.filter { $0.value.revision > readFrameRevision } let ownPID = ProcessInfo.processInfo.processIdentifier nativeWindows = Dictionary( uniqueKeysWithValues: windows.map { ($0.id, OverlayWindow(id: $0.id, frame: $0.frame)) }) + let decorations = Set(panels.values.compactMap { UInt32(exactly: $0.windowNumber) }) + .union(privacyPanels.values.compactMap { UInt32(exactly: $0.windowNumber) }) + .union(backdrops.values.compactMap { UInt32(exactly: $0.windowNumber) }) + // Exclude only our transparent canvases, not Parcel's own settings or other window content. + nativeHighlightWindows = Dictionary( + uniqueKeysWithValues: windows.compactMap { window in + guard !decorations.contains(window.id) else { return nil } + return (window.id, OverlayWindow(id: window.id, frame: window.frame)) + }) nativeDimmingWindows = windows.compactMap { guard $0.layer == 0, $0.pid != ownPID else { return nil } return OverlayWindow(id: $0.id, frame: $0.frame) @@ -444,7 +523,8 @@ public final class OverlayController { } } renderPrivacy() - renderFocus(previous: nil) + renderFocus() + refreshPanelVisibility() } private var currentMotion: OverlayMotion { @@ -456,46 +536,58 @@ public final class OverlayController { return OverlayMotion(configuration: configuration, accessibility: accessibility) } - private func renderFocus(previous: OverlaySnapshot?) { - let focused = snapshot?.windows.first { $0.id == snapshot?.focusedWindow } - for (id, panel) in panels { - guard configuration.highlight != .none, let snapshot else { + private func highlightWindow(_ window: OverlayWindow) -> OverlayWindow? { + if let nativeHighlightWindows, nativeHighlightWindows[window.id] == nil { return nil } + let frame = + observedPrivacyFrames[window.id]?.frame ?? nativeHighlightWindows?[window.id]?.focusFrame + ?? window.focusFrame + return OverlayWindow(id: window.id, frame: frame, cornerRadius: window.cornerRadius) + } + + private func renderFocus(displays: Set? = nil) { + let windows = snapshot?.windows.compactMap(highlightWindow) ?? [] + let focused = windows.first { $0.id == snapshot?.focusedWindow } + let nativeCutouts = nativeHighlightWindows.map { Array($0.values) } ?? [] + let protected = snapshot?.privacyWorkspaces.flatMap { privacyCutouts(in: $0) } ?? [] + let cutouts = + (nativeCutouts + (snapshot?.highlightCutouts ?? []) + protected).compactMap(highlightWindow) + + observedPrivacyFrames.map { OverlayWindow(id: $0.key, frame: $0.value.frame) } + windows + let color = color() + for (id, panel) in panels where displays?.contains(id) ?? true { + guard configuration.highlight != .none, let snapshot, !privacySuspended, + !requiresNativeHighlightWindows || nativeHighlightWindows != nil + else { focusLayers.removeValue(forKey: id)?.cancel() highlightCanvases.removeValue(forKey: id)?.layer.removeFromSuperlayer() continue } let canvas = highlightCanvases[id] ?? OverlayHighlightCanvas(parent: panel.canvas) highlightCanvases[id] = canvas - let cutouts = - snapshot.privacyWorkspaces.flatMap { privacyCutouts(in: $0) } - + (snapshot.windows + snapshot.highlightCutouts + (nativeDimmingWindows ?? [])).map(latestPrivacyWindow) - canvas.update( - display: panel.display, snapshot: snapshot, configuration: configuration, - accessibility: accessibility, color: color(), additionalCutouts: cutouts) - guard let focused, panel.display.frame.intersects(focused.focusFrame) else { - let tile = focusLayers.removeValue(forKey: id) - tile?.cancel() - tile?.layer.removeFromSuperlayer() - if canvas.inactive.isEmpty { - highlightCanvases.removeValue(forKey: id)?.layer.removeFromSuperlayer() + // Highlights follow observed geometry without overshoot; the outline and content mask commit together. + withoutImplicitAnimations { + canvas.layer.isHidden = nativeReadPending + canvas.update( + display: panel.display, windows: windows, focusedWindow: snapshot.focusedWindow, cutouts: cutouts, + configuration: configuration, accessibility: accessibility, color: color) + if let focused, panel.display.frame.intersects(focused.focusFrame) { + let tile = focusLayers[id] ?? OverlayTileLayer(parent: canvas.layer) + focusLayers[id] = tile + let frame = panel.display.localFrame(focused.focusFrame) + if tile.layer.frame != frame || tile.layer.cornerRadius != focused.cornerRadius { + tile.move(to: frame, radius: focused.cornerRadius, motion: instantMotion, token: .pop) + } + tile.styleHighlight( + OverlayHighlightStyle(configuration: configuration, accessibility: accessibility, active: true), + color: color, scale: panel.display.scale) + } else { + let tile = focusLayers.removeValue(forKey: id) + tile?.cancel() + tile?.layer.removeFromSuperlayer() + if canvas.inactive.isEmpty { + highlightCanvases.removeValue(forKey: id)?.layer.removeFromSuperlayer() + } } - continue - } - let existing = focusLayers[id] - let tile = existing ?? OverlayTileLayer(parent: canvas.layer) - focusLayers[id] = tile - let frame = panel.display.localFrame(focused.focusFrame) - if existing == nil || previous?.focusedWindow != snapshot.focusedWindow { - tile.cancel() - withoutImplicitAnimations { tile.layer.cornerRadius = focused.cornerRadius } - let motion = accessibility.reduceMotion ? instantMotion : currentMotion - tile.move(to: frame, radius: focused.cornerRadius, motion: motion, token: .pop, from: frame) - } else if tile.layer.frame != frame || tile.layer.cornerRadius != focused.cornerRadius { - tile.move(to: frame, radius: focused.cornerRadius, motion: instantMotion, token: .pop) } - tile.styleHighlight( - OverlayHighlightStyle(configuration: configuration, accessibility: accessibility, active: true), - color: color(), scale: panel.display.scale) } } @@ -586,7 +678,7 @@ public final class OverlayController { private func refresh() { setDisplays(Self.systemDisplays(), primaryDisplayHeight: NSScreen.screens.first?.frame.height ?? 0) - renderFocus(previous: nil) + renderFocus() if let dragTarget { dragChanged(target: dragTarget) } refreshPanelVisibility() } diff --git a/Sources/ParcelUI/Overlays/OverlayGeometry.swift b/Sources/ParcelUI/Overlays/OverlayGeometry.swift index 93874286..d1cd21b6 100644 --- a/Sources/ParcelUI/Overlays/OverlayGeometry.swift +++ b/Sources/ParcelUI/Overlays/OverlayGeometry.swift @@ -106,8 +106,13 @@ struct OverlayHighlightStyle: Equatable { enum OverlayHighlightGeometry { static func gaps(display: OverlayDisplay, windows: [OverlayWindow]) -> [CGRect] { - var result = [CGRect(origin: .zero, size: display.frame.size)] - for window in windows { + gaps( + in: CGRect(origin: .zero, size: display.frame.size), excluding: cutouts(display: display, windows: windows)) + } + + static func cutouts(display: OverlayDisplay, windows: [OverlayWindow]) -> [CGRect] { + let bounds = CGRect(origin: .zero, size: display.frame.size) + let frames = windows.compactMap { window -> CGRect? in let frame = display.localFrame(window.focusFrame) let scale = display.scale // Round cutouts outward so fractional window edges cannot pick up a tinted pixel. @@ -115,10 +120,21 @@ enum OverlayHighlightGeometry { let bottom = floor(frame.minY * scale) / scale let right = ceil(frame.maxX * scale) / scale let top = ceil(frame.maxY * scale) / scale - let cutout = CGRect(x: left, y: bottom, width: right - left, height: top - bottom) - result = result.flatMap { subtract(cutout, from: $0) } + let cutout = CGRect(x: left, y: bottom, width: right - left, height: top - bottom).intersection(bounds) + return cutout.isEmpty || cutout.isNull ? nil : cutout + }.sorted { + if $0.minX != $1.minX { return $0.minX < $1.minX } + if $0.minY != $1.minY { return $0.minY < $1.minY } + if $0.width != $1.width { return $0.width < $1.width } + return $0.height < $1.height + } + return frames.reduce(into: []) { result, frame in + if result.last != frame { result.append(frame) } } - return result + } + + static func gaps(in bounds: CGRect, excluding cutouts: [CGRect]) -> [CGRect] { + cutouts.reduce([bounds]) { regions, cutout in regions.flatMap { subtract(cutout, from: $0) } } } private static func subtract(_ cutout: CGRect, from rectangle: CGRect) -> [CGRect] { @@ -149,34 +165,52 @@ enum OverlayHighlightGeometry { @MainActor final class OverlayHighlightCanvas { + private struct MaskInputs: Equatable { + let size: CGSize + let scale: CGFloat + let cutouts: [CGRect] + } + let layer = CALayer() + let mask = CAShapeLayer() + private var maskInputs: MaskInputs? + private(set) var gaps: [CGRect] = [] + var cutouts: [CGRect] { maskInputs?.cutouts ?? [] } + private(set) var updateCount = 0 + private(set) var maskBuildCount = 0 private(set) var inactive: [UInt32: OverlayTileLayer] = [:] - init(parent: CALayer) { parent.addSublayer(layer) } + init(parent: CALayer) { + parent.addSublayer(layer) + mask.fillColor = NSColor.black.cgColor + layer.mask = mask + } func update( - display: OverlayDisplay, snapshot: OverlaySnapshot, configuration: MotionConfiguration, - accessibility: OverlayAccessibility, color: NSColor, additionalCutouts: [OverlayWindow] = [] + display: OverlayDisplay, windows: [OverlayWindow], focusedWindow: UInt32?, cutouts: [OverlayWindow], + configuration: MotionConfiguration, accessibility: OverlayAccessibility, color: NSColor ) { - let mask = CAShapeLayer() - let path = CGMutablePath() - for rectangle in OverlayHighlightGeometry.gaps( - display: display, windows: snapshot.windows + snapshot.highlightCutouts + additionalCutouts) - { - path.addRect(rectangle) - } - withoutImplicitAnimations { - layer.frame = CGRect(origin: .zero, size: display.frame.size) - layer.contentsScale = display.scale - mask.frame = layer.bounds - mask.contentsScale = display.scale - mask.path = path - mask.fillColor = NSColor.black.cgColor - layer.mask = mask + updateCount += 1 + let inputs = MaskInputs( + size: display.frame.size, scale: display.scale, + cutouts: OverlayHighlightGeometry.cutouts(display: display, windows: cutouts)) + if maskInputs != inputs { + gaps = OverlayHighlightGeometry.gaps( + in: CGRect(origin: .zero, size: inputs.size), excluding: inputs.cutouts) + let path = CGMutablePath() + for rectangle in gaps { path.addRect(rectangle) } + withoutImplicitAnimations { + layer.frame = CGRect(origin: .zero, size: inputs.size) + layer.contentsScale = inputs.scale + mask.frame = layer.bounds + mask.contentsScale = inputs.scale + mask.path = path + } + maskInputs = inputs + maskBuildCount += 1 } - let windows = snapshot.windows.filter { - configuration.highlight == .all && $0.id != snapshot.focusedWindow - && display.frame.intersects($0.focusFrame) + let windows = windows.filter { + configuration.highlight == .all && $0.id != focusedWindow && display.frame.intersects($0.focusFrame) } let visible = Set(windows.map(\.id)) for id in inactive.keys where !visible.contains(id) { @@ -189,49 +223,115 @@ final class OverlayHighlightCanvas { for window in windows { let tile = inactive[window.id] ?? OverlayTileLayer(parent: layer) inactive[window.id] = tile - tile.move( - to: display.localFrame(window.focusFrame), radius: window.cornerRadius, motion: motion, token: .pop) + let frame = display.localFrame(window.focusFrame) + if tile.layer.frame != frame || tile.layer.cornerRadius != window.cornerRadius { + tile.move(to: frame, radius: window.cornerRadius, motion: motion, token: .pop) + } tile.styleHighlight(style, color: color, scale: display.scale) } } } -extension OverlayTileLayer { - func styleHighlight(_ style: OverlayHighlightStyle, color: NSColor, scale: CGFloat) { +@MainActor +final class OverlayHighlightRenderer { + private struct Geometry: Equatable { + let bounds: CGRect + let radius: CGFloat + let width: CGFloat + } + + private struct Inputs: Equatable { + let bounds: CGRect + let radius: CGFloat + let style: OverlayHighlightStyle + let color: CGColor + let scale: CGFloat + } + + let stroke = CAShapeLayer() + private(set) var glow: [CAShapeLayer] = [] + private var inputs: Inputs? + private var glowGeometry: Geometry? + private(set) var pathBuildCount = 0 + private(set) var styleUpdateCount = 0 + + init(parent: CALayer) { parent.addSublayer(stroke) } + + func update(tile: OverlayTileLayer, style: OverlayHighlightStyle, color: NSColor, scale: CGFloat) { + let next = Inputs( + bounds: tile.layer.bounds, radius: tile.layer.cornerRadius, style: style, + color: (style.active ? color : .secondaryLabelColor).cgColor, scale: scale) + guard inputs != next else { return } + let geometryChanged = + inputs?.bounds != next.bounds || inputs?.radius != next.radius + || inputs?.style.width != style.width + let styleChanged = inputs?.style != style || inputs?.color != next.color || inputs?.scale != scale withoutImplicitAnimations { - layer.borderWidth = 0 - layer.backgroundColor = nil - layer.contentsScale = scale - layer.opacity = style.opacity - ticks.isHidden = true - highlight.sublayers = nil - let color = style.active ? color : NSColor.secondaryLabelColor - if style.glow { - for band in (1...6).reversed() { - addHighlightStroke( - distance: style.width + CGFloat(band) - 0.5, width: 1, - opacity: Float(7 - band) / 24, color: color, scale: scale, dashed: false) + if style.glow && glow.isEmpty { glow = (1...6).map { _ in CAShapeLayer() } } + if inputs?.style.glow != style.glow { + for band in glow { + if style.glow { + tile.highlight.insertSublayer(band, below: stroke) + } else { + band.removeFromSuperlayer() + } } } - addHighlightStroke( - distance: style.width / 2, width: style.width, opacity: 1, - color: color, scale: scale, dashed: !style.active) + if geometryChanged { + updatePath(stroke, bounds: next.bounds, radius: next.radius, distance: style.width / 2) + } + let geometry = Geometry(bounds: next.bounds, radius: next.radius, width: style.width) + if style.glow, glowGeometry != geometry { + for (index, band) in glow.enumerated() { + updatePath( + band, bounds: next.bounds, radius: next.radius, distance: style.width + CGFloat(6 - index) - 0.5 + ) + } + glowGeometry = geometry + } + if styleChanged { + tile.layer.borderWidth = 0 + tile.layer.backgroundColor = nil + tile.layer.contentsScale = scale + tile.layer.opacity = style.opacity + tile.ticks.isHidden = true + updateStroke( + stroke, color: next.color, width: style.width, opacity: 1, scale: scale, dashed: !style.active) + if style.glow { + for (index, band) in glow.enumerated() { + updateStroke( + band, color: next.color, width: 1, opacity: Float(index + 1) / 24, scale: scale, + dashed: false) + } + } + styleUpdateCount += 1 + } } + inputs = next + } + + private func updatePath(_ stroke: CAShapeLayer, bounds: CGRect, radius: CGFloat, distance: CGFloat) { + stroke.path = OverlayHighlightGeometry.outline(bounds: bounds, radius: radius, distance: distance) + pathBuildCount += 1 } - private func addHighlightStroke( - distance: CGFloat, width: CGFloat, opacity: Float, color: NSColor, scale: CGFloat, dashed: Bool + private func updateStroke( + _ stroke: CAShapeLayer, color: CGColor, width: CGFloat, opacity: Float, scale: CGFloat, dashed: Bool ) { - let stroke = CAShapeLayer() - stroke.path = OverlayHighlightGeometry.outline( - bounds: layer.bounds, radius: layer.cornerRadius, distance: distance) stroke.fillColor = nil - stroke.strokeColor = color.cgColor + stroke.strokeColor = color stroke.lineWidth = width stroke.opacity = opacity stroke.contentsScale = scale stroke.lineDashPattern = dashed ? [6, 4] : nil - highlight.addSublayer(stroke) + } +} + +extension OverlayTileLayer { + func styleHighlight(_ style: OverlayHighlightStyle, color: NSColor, scale: CGFloat) { + let renderer = highlightRenderer ?? OverlayHighlightRenderer(parent: highlight) + highlightRenderer = renderer + renderer.update(tile: self, style: style, color: color, scale: scale) } } @@ -239,10 +339,13 @@ struct OverlayMotion { let settings: MotionSettings let behavior: MotionBehavior - init(configuration: MotionConfiguration, accessibility: OverlayAccessibility) { + init(configuration: MotionConfiguration, accessibility: OverlayAccessibility, geometry: Bool = true) { settings = configuration.uiMotionSettings - behavior = MotionPolicy(enabled: configuration.enabled, reduceMotion: accessibility.reduceMotion) + let policy = MotionPolicy(enabled: configuration.enabled, reduceMotion: accessibility.reduceMotion) .behavior(for: .overlay, level: settings.level) + behavior = + !geometry && policy == .animate + ? .fade(duration: MotionToken.fade.spec(settings: settings).duration) : policy } func spec(_ token: MotionToken) -> MotionSpec { token.spec(settings: settings) } diff --git a/Sources/ParcelUI/Overlays/OverlayPanel.swift b/Sources/ParcelUI/Overlays/OverlayPanel.swift index e7de612e..f1644cc4 100644 --- a/Sources/ParcelUI/Overlays/OverlayPanel.swift +++ b/Sources/ParcelUI/Overlays/OverlayPanel.swift @@ -93,6 +93,7 @@ final class OverlayTileLayer { let layer = CALayer() let ticks = CAShapeLayer() let highlight = CALayer() + var highlightRenderer: OverlayHighlightRenderer? private var axes: [String: OverlayAxisMotion] = [:] private var completion: OverlayAnimationCompletion? private var revision = 0 @@ -137,12 +138,13 @@ final class OverlayTileLayer { axes = [:] completion = nil withoutImplicitAnimations { + let geometryChanged = layer.bounds.size != frame.size || layer.cornerRadius != radius layer.bounds = CGRect(origin: .zero, size: frame.size) layer.position = CGPoint(x: frame.midX, y: frame.midY) layer.cornerRadius = radius layer.transform = CATransform3DIdentity layer.opacity = transient ? 0 : layer.opacity - updateTicks() + if geometryChanged { updateTicks() } } var animations: [CAAnimation] = [] let spec = motion.spec(token) diff --git a/Sources/ParcelUI/Overlays/OverlaySnapshot.swift b/Sources/ParcelUI/Overlays/OverlaySnapshot.swift index 2e6ba9fe..e1bc90ae 100644 --- a/Sources/ParcelUI/Overlays/OverlaySnapshot.swift +++ b/Sources/ParcelUI/Overlays/OverlaySnapshot.swift @@ -1,4 +1,4 @@ -import AppKit +public import Foundation import ParcelConfig public import ParcelCore import ParcelEngine @@ -88,6 +88,19 @@ public struct OverlaySnapshot: Equatable, Sendable { } } +public struct OverlayHighlightAudit: Codable, Sendable { + public struct Display: Codable, Sendable { + public let id: String + public let frame: CGRect + public let cutouts: [CGRect] + public let gaps: [CGRect] + public let outlinedWindows: [UInt32] + } + + public let ready: Bool + public let displays: [Display] +} + extension Rect { fileprivate var overlayRectangle: CGRect { CGRect(x: minX, y: minY, width: size.width, height: size.height) diff --git a/Sources/ParcelUI/Overlays/PrivacyWindows.swift b/Sources/ParcelUI/Overlays/PrivacyWindows.swift index a92b060c..17d8dcf4 100644 --- a/Sources/ParcelUI/Overlays/PrivacyWindows.swift +++ b/Sources/ParcelUI/Overlays/PrivacyWindows.swift @@ -1,6 +1,11 @@ import AppKit import ParcelPlatform +public struct OverlayWindowReadError: Error, CustomStringConvertible { + public let underlying: any Error + public var description: String { String(describing: underlying) } +} + struct PrivacyWindowInfo: Sendable, Equatable { let id: UInt32 let pid: Int32 @@ -13,7 +18,7 @@ struct PrivacyWindowInfo: Sendable, Equatable { } static func read() throws -> [Self] { - try WindowServer().windows(options: .optionOnScreenOnly).compactMap { window in + try WindowServer().windows(options: [.optionOnScreenOnly, .excludeDesktopElements]).compactMap { window in guard window.bounds.isFiniteAndPositive else { return nil } return Self(id: window.number, pid: window.pid, frame: window.bounds, layer: window.layer) } diff --git a/Tests/ParcelE2ETests/HighlightEndToEndTests.swift b/Tests/ParcelE2ETests/HighlightEndToEndTests.swift new file mode 100644 index 00000000..5e0b1410 --- /dev/null +++ b/Tests/ParcelE2ETests/HighlightEndToEndTests.swift @@ -0,0 +1,86 @@ +import Foundation +import ParcelCore +import ParcelUI +import Testing + +extension RealAppEndToEndTests { + @Test func highlightsCutOutAnUnmanagedFixtureInTheGapWithoutPrivacy() async throws { + var configuration = E2EConfiguration() + configuration.innerGap = 160 + configuration.motion = true + configuration.focusBorder = true + try await withSession(configuration: configuration) { session in + try Data( + (configuration.source + + "highlight = \"glow\"\nhighlight-width = 6\n" + + "\n[[rules]]\ntitle-regex = '^Unmanaged Highlight Fixture 3$'\naction = \"ignore\"\n").utf8 + ).write(to: session.configURL, options: .atomic) + let (fixture, ready) = try await session.addFixture(arguments: [ + "--windows", "3", "--title", "Unmanaged Highlight Fixture", + ]) + let unmanaged = try #require(ready.windows.first { $0.index == 3 }) + _ = try await fixture.control(FixtureControl(action: "focus", window: 1)) + try await session.startApp() + let managed = try await session.settledWindows(for: fixture, count: 2) + #expect(!managed.contains { $0.id == unmanaged.number }) + let frames = try session.frames(for: fixture) + let ordered = try managed.map { window in (window.id, try #require(frames[window.id])) } + .sorted { $0.1.minX < $1.1.minX } + let left = try #require(ordered.first) + let right = try #require(ordered.last) + #expect(abs(right.1.minX - left.1.maxX - 160) < 2) + let focus = try #require(ready.windows.first { $0.number == left.0 }) + _ = try await fixture.control(FixtureControl(action: "focus", window: focus.index)) + let workspace = try await session.workspace(for: managed) + var previous: CGRect? + for offset in [0.0, 70.0] { + let requested = Rect( + x: left.1.maxX - 3, y: left.1.minY + 40 + offset, width: 140, height: 100) + _ = try await fixture.control( + FixtureControl( + action: "frame", window: unmanaged.index, + x: requested.minX, y: requested.minY, + width: requested.size.width, height: requested.size.height)) + try await waitUntil("unmanaged fixture content is excluded by the live highlight mask") { + let actual = try #require(session.frames(for: fixture)[unmanaged.number]) + guard framesMatch(actual, requested) else { return false } + let audit: OverlayHighlightAudit = try await session.query("e2e-highlights") + guard audit.ready, let display = audit.displays.first(where: { $0.id == workspace.id.display }) + else { + return false + } + let local = CGRect( + x: actual.minX - display.frame.minX, y: display.frame.maxY - actual.maxY, + width: actual.size.width, height: actual.size.height) + let includesFixture = display.cutouts.contains { rectangle in + abs(rectangle.minX - local.minX) < 1 && abs(rectangle.minY - local.minY) < 1 + && abs(rectangle.width - local.width) < 2 && abs(rectangle.height - local.height) < 2 + } + guard includesFixture, display.outlinedWindows.contains(left.0), + !display.outlinedWindows.contains(unmanaged.number), + display.gaps.allSatisfy({ $0.intersection(local).isEmpty }), + previous.map({ !display.cutouts.contains($0) }) ?? true + else { return false } + previous = local + return true + } + let status: HighlightPrivacyStatus = try await session.query("config") + #expect(status.privacyPanelCount == 0 && status.cleanSpaceBackdropCount == 0) + #expect(status.overlayActiveAnimations == 0) + #expect(try await session.windows(for: fixture).allSatisfy { $0.id != unmanaged.number }) + } + } + } +} + +private struct HighlightPrivacyStatus: Decodable { + let privacyPanelCount: Int + let cleanSpaceBackdropCount: Int + let overlayActiveAnimations: Int + + private enum CodingKeys: String, CodingKey { + case privacyPanelCount = "privacy_panel_count" + case cleanSpaceBackdropCount = "clean_space_backdrop_count" + case overlayActiveAnimations = "overlay_active_animations" + } +} diff --git a/Tests/ParcelUITests/Overlays/HighlightTests.swift b/Tests/ParcelUITests/Overlays/HighlightTests.swift index b0ad0f03..4cec7230 100644 --- a/Tests/ParcelUITests/Overlays/HighlightTests.swift +++ b/Tests/ParcelUITests/Overlays/HighlightTests.swift @@ -2,6 +2,7 @@ import AppKit import ParcelConfig import ParcelCore import QuartzCore +import Synchronization import Testing @testable import ParcelEngine @@ -188,6 +189,225 @@ extension OverlayTestSuite { try expectClearContent(image(controller), windows: [first, second, moved]) } + @Test(arguments: [ConfigHighlight.active, .all, .glow]) + func everyNativeContentLayerIsCutOutWithoutPrivacy(style: ConfigHighlight) throws { + let controller = controller(style: style, width: 6) + defer { controller.stop() } + controller.update(OverlaySnapshot(windows: [first, second], focusedWindow: 1)) + let unmanaged = [ + OverlayWindow(id: 3, frame: CGRect(x: 10, y: 70, width: 20, height: 50)), + OverlayWindow(id: 4, frame: CGRect(x: 100, y: 20, width: 50, height: 20)), + OverlayWindow(id: 5, frame: CGRect(x: 130, y: 90, width: 30, height: 40)), + OverlayWindow(id: 6, frame: CGRect(x: 10, y: 140, width: 30, height: 50)), + OverlayWindow(id: 7, frame: CGRect(x: 50, y: 160, width: 60, height: 30)), + ] + let ownPID = ProcessInfo.processInfo.processIdentifier + let panel = try #require(controller.panels[display.id]) + let panelID = try #require(UInt32(exactly: panel.windowNumber)) + controller.applyPrivacyWindows( + [ + PrivacyWindowInfo(id: 1, pid: 123, frame: first.frame, layer: 0), + PrivacyWindowInfo(id: 2, pid: 123, frame: second.frame, layer: 0), + PrivacyWindowInfo(id: 3, pid: 456, frame: unmanaged[0].frame, layer: 0), + PrivacyWindowInfo(id: 4, pid: 456, frame: unmanaged[1].frame, layer: 3), + PrivacyWindowInfo(id: 5, pid: 789, frame: unmanaged[2].frame, layer: 25), + PrivacyWindowInfo(id: 6, pid: ownPID, frame: unmanaged[3].frame, layer: 0), + PrivacyWindowInfo(id: panelID, pid: ownPID, frame: display.frame, layer: 3), + PrivacyWindowInfo(id: 7, pid: 789, frame: unmanaged[4].frame, layer: -1), + ], focusedWindow: 1) + #expect(controller.privacyPanels.isEmpty && controller.backdrops.isEmpty) + try expectClearContent(image(controller), windows: [first, second] + unmanaged) + #expect(alpha(try image(controller), x: 19, y: 55) > 0) + let audit = controller.highlightAudit() + #expect(audit.ready && audit.displays.first?.outlinedWindows.contains(1) == true) + } + + @Test func unchangedSnapshotsKeepMaskStrokeLayersAndPaths() throws { + let controller = controller(style: .all) + defer { controller.stop() } + let snapshot = OverlaySnapshot(windows: [first, second], focusedWindow: 1) + controller.update(snapshot) + let canvas = try #require(controller.highlightCanvases[display.id]) + let tile = try #require(controller.focusLayers[display.id]) + let renderer = try #require(tile.highlightRenderer) + let inactive = try #require(canvas.inactive[2]?.highlightRenderer) + let maskPath = try #require(canvas.mask.path) + let strokePath = try #require(renderer.stroke.path) + for _ in 0..<10 { controller.update(snapshot) } + let offscreen = OverlayWindow(id: 3, frame: CGRect(x: 500, y: 0, width: 100, height: 100)) + controller.update(OverlaySnapshot(windows: [second, offscreen, first], focusedWindow: 1)) + #expect(controller.highlightCanvases[display.id] === canvas) + #expect(canvas.layer.mask === canvas.mask && canvas.mask.path === maskPath) + #expect(controller.focusLayers[display.id] === tile && tile.highlightRenderer === renderer) + #expect(renderer.stroke.path === strokePath && canvas.inactive[2]?.highlightRenderer === inactive) + #expect(canvas.maskBuildCount == 1) + #expect(renderer.pathBuildCount == 1 && renderer.styleUpdateCount == 1) + #expect(inactive.pathBuildCount == 1 && inactive.styleUpdateCount == 1) + } + + @Test func translationRebuildsOnlyMaskAndResizeRebuildsStrokeGeometry() throws { + let controller = controller(style: .glow) + defer { controller.stop() } + controller.update(OverlaySnapshot(windows: [first, second], focusedWindow: 1)) + let canvas = try #require(controller.highlightCanvases[display.id]) + let tile = try #require(controller.focusLayers[display.id]) + let renderer = try #require(tile.highlightRenderer) + let strokes = try #require(tile.highlight.sublayers) + let moved = OverlayWindow(id: 1, frame: first.frame.offsetBy(dx: -3, dy: 0)) + controller.update(OverlaySnapshot(windows: [moved, second], focusedWindow: 1)) + #expect(canvas.maskBuildCount == 2) + #expect(renderer.pathBuildCount == 7 && renderer.styleUpdateCount == 1) + let resized = OverlayWindow(id: 1, frame: moved.frame.insetBy(dx: 3, dy: 2)) + controller.update(OverlaySnapshot(windows: [resized, second], focusedWindow: 1)) + #expect(canvas.maskBuildCount == 3) + #expect(renderer.pathBuildCount == 14 && renderer.styleUpdateCount == 1) + #expect(zip(strokes, tile.highlight.sublayers ?? []).allSatisfy { $0 === $1 }) + } + + @Test func styleChangesReuseGlowLayersAndLeaveMaskAndUnchangedPathsAlone() throws { + let controller = controller(style: .glow) + defer { controller.stop() } + controller.update(OverlaySnapshot(windows: [first, second], focusedWindow: 1)) + let canvas = try #require(controller.highlightCanvases[display.id]) + let renderer = try #require(controller.focusLayers[display.id]?.highlightRenderer) + let bands = renderer.glow + let stroke = renderer.stroke + for style in [ConfigHighlight.active, .glow, .active, .glow] { + controller.update( + configuration: MotionConfiguration(enabled: false, highlight: style), accessibility: .init()) + } + #expect(canvas.maskBuildCount == 1 && renderer.pathBuildCount == 7) + #expect(renderer.stroke === stroke && zip(bands, renderer.glow).allSatisfy { $0 === $1 }) + controller.update( + configuration: MotionConfiguration(enabled: false, highlight: .glow, highlightWidth: 6), + accessibility: .init()) + #expect(canvas.maskBuildCount == 1 && renderer.pathBuildCount == 14) + #expect(renderer.stroke === stroke && zip(bands, renderer.glow).allSatisfy { $0 === $1 }) + } + + @Test func colorAndScaleChangesUpdateStyleWithoutRebuildingPaths() throws { + let controller = controller(style: .glow) + defer { controller.stop() } + controller.update(OverlaySnapshot(windows: [first], focusedWindow: 1)) + let tile = try #require(controller.focusLayers[display.id]) + let renderer = try #require(tile.highlightRenderer) + let style = OverlayHighlightStyle( + configuration: controller.configuration, accessibility: .init(), active: true) + let path = try #require(renderer.stroke.path) + tile.styleHighlight(style, color: .systemOrange, scale: 1) + #expect(renderer.styleUpdateCount == 2 && renderer.pathBuildCount == 7) + #expect(renderer.stroke.path === path && renderer.stroke.contentsScale == 1) + #expect(renderer.stroke.strokeColor == NSColor.systemOrange.cgColor) + #expect( + renderer.glow.allSatisfy { $0.contentsScale == 1 && $0.strokeColor == NSColor.systemOrange.cgColor }) + tile.styleHighlight(style, color: .systemOrange, scale: 1) + #expect(renderer.styleUpdateCount == 2 && renderer.pathBuildCount == 7) + } + + @Test func observationsOnlyRenderIntersectingDisplaysAndSkipDuplicateFrames() throws { + let controller = controller(style: .all) + defer { controller.stop() } + let right = OverlayDisplay(id: "right", frame: CGRect(x: 320, y: 0, width: 320, height: 220), scale: 1) + let far = OverlayDisplay(id: "far", frame: CGRect(x: 640, y: 0, width: 320, height: 220), scale: 2) + controller.setDisplays([display, right, far], primaryDisplayHeight: 220) + let remote = OverlayWindow(id: 3, frame: first.frame.offsetBy(dx: 320, dy: 0)) + let distant = OverlayWindow(id: 4, frame: first.frame.offsetBy(dx: 640, dy: 0)) + controller.update(OverlaySnapshot(windows: [first, second, remote, distant], focusedWindow: 1)) + let main = try #require(controller.highlightCanvases[display.id]) + let other = try #require(controller.highlightCanvases[right.id]) + let unrelated = try #require(controller.highlightCanvases[far.id]) + let moved = WindowFrame(window: WindowID(rawValue: 1), frame: Rect(x: 22, y: 30, width: 120, height: 140)) + controller.observePrivacyFrame(moved) + #expect(main.updateCount == 2 && main.maskBuildCount == 2) + #expect(other.updateCount == 1 && unrelated.updateCount == 1) + controller.observePrivacyFrame(moved) + #expect(main.updateCount == 2 && other.updateCount == 1 && unrelated.updateCount == 1) + controller.observePrivacyFrame( + WindowFrame(window: WindowID(rawValue: 1), frame: Rect(x: 300, y: 30, width: 120, height: 140))) + #expect(main.updateCount == 3 && other.updateCount == 2 && unrelated.updateCount == 1) + #expect(controller.focusLayers[display.id] != nil && controller.focusLayers[right.id] != nil) + } + + @Test func nativeAndNewerObservedManagedFramesMoveMaskAndOutlineTogether() throws { + let controller = controller(style: .glow) + defer { controller.stop() } + controller.update(configuration: MotionConfiguration(highlight: .glow), accessibility: .init()) + controller.update(OverlaySnapshot(windows: [first, second], focusedWindow: 1)) + let actual = first.frame.offsetBy(dx: -4, dy: 0) + let native = [ + PrivacyWindowInfo(id: 1, pid: 123, frame: actual, layer: 0), + PrivacyWindowInfo(id: 2, pid: 123, frame: second.frame, layer: 0), + ] + controller.applyPrivacyWindows(native, focusedWindow: 1) + let tile = try #require(controller.focusLayers[display.id]) + #expect(tile.layer.frame == display.localFrame(actual)) + let moved = OverlayWindow(id: 1, frame: first.frame.offsetBy(dx: 4, dy: 0)) + controller.observePrivacyFrame( + WindowFrame(window: WindowID(rawValue: 1), frame: Rect(x: 24, y: 30, width: 120, height: 140))) + controller.applyPrivacyWindows(native, focusedWindow: 1, readFrameRevision: 0) + #expect(tile.layer.frame == display.localFrame(moved.frame)) + #expect(controller.activeAnimationCount == 0 && CATransform3DIsIdentity(tile.layer.transform)) + #expect(controller.highlightCanvases[display.id]?.mask.animationKeys()?.isEmpty != false) + try expectClearContent(image(controller), windows: [moved, second]) + #expect(alpha(try image(controller), x: 23, y: 100) > 0) + } + + @Test(arguments: [false, true]) + func visibilityReadsSurfaceFailuresAndRecoverWithOrWithoutPrivacy(noPeek: Bool) async throws { + enum Failure: Error { case unavailable } + let fails = Mutex(true) + let native = [ + PrivacyWindowInfo(id: 1, pid: 123, frame: first.frame, layer: 0), + PrivacyWindowInfo(id: 3, pid: 456, frame: CGRect(x: 10, y: 70, width: 20, height: 50), layer: 3), + ] + var errors: [OverlayWindowReadError] = [] + let controller = OverlayController( + configuration: MotionConfiguration(enabled: false, highlight: .glow), accessibility: .init(), + brightness: TestOverlayBrightness(), notifications: .system, + windowReader: { + if fails.withLock({ $0 }) { throw Failure.unavailable } + return native + }, + onFailure: { error in + guard let read = error as? OverlayWindowReadError else { + Issue.record(error) + return + } + errors.append(read) + }) + defer { controller.stop() } + controller.setDisplays([display], primaryDisplayHeight: 220) + let key = WorkspaceKey(display: DisplayID(rawValue: display.id), space: SpaceID(rawValue: 1)) + controller.update( + OverlaySnapshot( + windows: [first], focusedWindow: 1, + privacyWorkspaces: noPeek ? [OverlayPrivacyWorkspace(key: key, noPeek: true, focusedWindow: 1)] : [] + )) + controller.refreshPrivacyWindows() + #expect(!controller.highlightAudit().ready) + for _ in 0..<100 where errors.isEmpty { try await Task.sleep(for: .milliseconds(10)) } + #expect(errors.count == 1 && errors.first?.underlying is Failure) + #expect(controller.highlightCanvases.isEmpty && !controller.highlightAudit().ready) + #expect(controller.privacyPanels.isEmpty == !noPeek) + if noPeek { + #expect( + controller.privacyPanels[display.id]?.regions == [CGRect(origin: .zero, size: display.frame.size)]) + } + fails.withLock { $0 = false } + controller.refreshPrivacyWindows() + for _ in 0..<100 where !controller.highlightAudit().ready { try await Task.sleep(for: .milliseconds(10)) } + #expect(controller.highlightAudit().ready && errors.count == 1) + let sheet = OverlayWindow(id: 3, frame: native[1].frame) + try expectClearContent(image(controller), windows: [first, sheet]) + #expect(alpha(try image(controller), x: 19, y: 55) > 0) + let canvas = try #require(controller.highlightCanvases[display.id]) + controller.refreshPrivacyWindows() + #expect(canvas.layer.isHidden && !controller.highlightAudit().ready) + for _ in 0..<100 where !controller.highlightAudit().ready { try await Task.sleep(for: .milliseconds(10)) } + #expect(controller.highlightCanvases[display.id] === canvas && canvas.maskBuildCount == 1) + #expect(!canvas.layer.isHidden) + } + @Test func touchingWindowsAndScreenEdgesDoNotPaintContent() throws { let controller = controller(style: .all, width: 6) defer { controller.stop() } diff --git a/Tests/ParcelUITests/Overlays/OverlaySnapshotTests.swift b/Tests/ParcelUITests/Overlays/OverlaySnapshotTests.swift index 3eb0ec54..d8a83a56 100644 --- a/Tests/ParcelUITests/Overlays/OverlaySnapshotTests.swift +++ b/Tests/ParcelUITests/Overlays/OverlaySnapshotTests.swift @@ -24,18 +24,26 @@ extension OverlayTestSuite { observedFrames: observed.map { [window: $0] } ?? [:])) } - @Test func engineAdapterKeepsFocusOnObservedFramesInEveryTransitionMode() throws { + @Test func engineAdapterKeepsFocusOnObservedFramesInEveryTransitionMode() async throws { let target = Rect(x: 100, y: 100, width: 200, height: 150) let observed = Rect(x: 150, y: 130, width: 210, height: 180) for transition in [ConfigMotionTransition.glide, .ghost, .snap] { let controller = OverlayController( configuration: MotionConfiguration(transitions: transition), - accessibility: OverlayAccessibility(), brightness: TestOverlayBrightness() - ) { _ in - Issue.record("Unexpected failure") - } + accessibility: OverlayAccessibility(), brightness: TestOverlayBrightness(), notifications: .system, + windowReader: { + [ + PrivacyWindowInfo( + id: 1, pid: 123, frame: CGRect(x: 150, y: 130, width: 210, height: 180), layer: 0) + ] + }, + onFailure: { _ in Issue.record("Unexpected failure") }) defer { controller.stop() } controller.consume(engineSnapshot(frame: target, observed: observed), cornerRadius: { _ in 8 }) + #expect(controller.focusLayers.isEmpty) + for _ in 0..<100 where !controller.highlightAudit().ready { + try await Task.sleep(for: .milliseconds(10)) + } let entry = try #require(controller.focusLayers.first) let panel = try #require(controller.panels[entry.key]) let expected = observed @@ -48,11 +56,14 @@ extension OverlayTestSuite { @Test func snapshotSubscriptionCanBeReplacedAndStopped() async throws { let controller = OverlayController( - accessibility: OverlayAccessibility(), brightness: TestOverlayBrightness() - ) { - _ in - Issue.record("Unexpected failure") - } + accessibility: OverlayAccessibility(), brightness: TestOverlayBrightness(), notifications: .system, + windowReader: { + [ + PrivacyWindowInfo( + id: 1, pid: 123, frame: CGRect(x: 100, y: 100, width: 200, height: 150), layer: 0) + ] + }, + onFailure: { _ in Issue.record("Unexpected failure") }) defer { controller.stop() } let first = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) let second = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) diff --git a/Tests/ParcelUITests/Overlays/OverlayTests.swift b/Tests/ParcelUITests/Overlays/OverlayTests.swift index 31d35896..d2c650ee 100644 --- a/Tests/ParcelUITests/Overlays/OverlayTests.swift +++ b/Tests/ParcelUITests/Overlays/OverlayTests.swift @@ -137,24 +137,18 @@ extension OverlayTestSuite { #expect(!panel.isVisible) } - @Test func focusCommitsAtFrameZeroAndPopsOnlyTheBorder() throws { + @Test func focusCommitsSettledGeometryTogetherWithItsClip() throws { let controller = controller() defer { controller.stop() } controller.update(OverlaySnapshot(windows: [first, second], focusedWindow: 1)) let tile = try #require(controller.focusLayers[display.id]) #expect(tile.layer.frame == display.localFrame(first.frame)) #expect(tile.layer.cornerRadius == first.cornerRadius) - let animation = try group(tile) - let scale = try #require( - animation.animations?.first { ($0 as? CAPropertyAnimation)?.keyPath == "transform.scale" } - as? CASpringAnimation) - #expect(scale.fromValue as? Double == 0.98) - #expect(scale.toValue as? Double == 1) - #expect(animation.duration == MotionToken.pop.spec().duration) + #expect(tile.layer.animationKeys()?.isEmpty != false) #expect(controller.panels[display.id]?.isVisible == true) controller.update(OverlaySnapshot(windows: [first, second], focusedWindow: 2)) #expect(tile.layer.frame == display.localFrame(second.frame)) - #expect(try group(tile).animations?.count == 1) + #expect(tile.layer.animationKeys()?.isEmpty != false) } @Test func focusFollowsActualFrameWithoutGeometryAnimation() throws { @@ -309,20 +303,19 @@ extension OverlayTestSuite { } @Test(arguments: [ParcelCore.Direction.left, .right, .up, .down]) - func refusalUsesDirectionalFourPointNudge(direction: ParcelCore.Direction) throws { + func refusalUsesOpacityWithoutMovingTheClippedOutline(direction: ParcelCore.Direction) throws { let controller = controller() defer { controller.stop() } controller.update(OverlaySnapshot(windows: [first], focusedWindow: 1)) controller.refused(direction) let tile = try #require(controller.focusLayers[display.id]) let animation = try group(tile) - let key = direction == .left || direction == .right ? "transform.translation.x" : "transform.translation.y" - let nudge = try #require( - animation.animations?.first { ($0 as? CAPropertyAnimation)?.keyPath == key } as? CASpringAnimation) - let sign: Double = direction == .left || direction == .down ? -1 : 1 - #expect(nudge.fromValue as? Double == sign * 4) - #expect(nudge.toValue as? Double == 0) + let fade = try #require(animation.animations?.first as? CABasicAnimation) + #expect(animation.animations?.count == 1 && fade.keyPath == "opacity") + #expect(fade.fromValue as? Float == 0) + #expect(fade.toValue as? Float == tile.layer.opacity) #expect(tile.layer.frame == display.localFrame(first.frame)) + #expect(CATransform3DIsIdentity(tile.layer.transform)) } @Test func reduceMotionUsesOnlyOpacity() throws { -- knotmirror 0.0.1 From e16338cb8bb3b6382f4a3baabefa42c2bef07358 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 12:47:33 -0400 Subject: [PATCH 4/7] Refresh update notices after skip and install --- Sources/ParcelUpdate/SparkleDriver.swift | 21 ++++++-- Sources/ParcelUpdate/UpdateAvailability.swift | 19 +++++++ .../UpdateAvailabilityTests.swift | 50 +++++++++++++++++++ 3 files changed, 85 insertions(+), 5 deletions(-) create mode 100644 Sources/ParcelUpdate/UpdateAvailability.swift create mode 100644 Tests/ParcelUpdateTests/UpdateAvailabilityTests.swift diff --git a/Sources/ParcelUpdate/SparkleDriver.swift b/Sources/ParcelUpdate/SparkleDriver.swift index 14d1019f..ccc1088c 100644 --- a/Sources/ParcelUpdate/SparkleDriver.swift +++ b/Sources/ParcelUpdate/SparkleDriver.swift @@ -9,7 +9,8 @@ var availabilityDidChange: (@MainActor () -> Void)? private var observation: NSKeyValueObservation? - private(set) var availableVersion: String? + private var availability = UpdateAvailability() + var availableVersion: String? { availability.version } override init() { super.init() @@ -23,12 +24,22 @@ func checkForUpdates() { controller.checkForUpdates(nil) } func updater(_ updater: SPUUpdater, didFindValidUpdate item: SUAppcastItem) { - availableVersion = item.displayVersionString - availabilityDidChange?() + receive(.found(item.displayVersionString)) } - func updaterDidNotFindUpdate(_ updater: SPUUpdater) { - availableVersion = nil + func updaterDidNotFindUpdate(_ updater: SPUUpdater) { receive(.notFound) } + + func updater( + _ updater: SPUUpdater, userDidMake choice: SPUUserUpdateChoice, + forUpdate update: SUAppcastItem, state: SPUUserUpdateState + ) { + if choice == .skip { receive(.skipped) } + } + + func updaterWillRelaunchApplication(_ updater: SPUUpdater) { receive(.willRelaunch) } + + private func receive(_ event: UpdateAvailability.Event) { + availability.receive(event) availabilityDidChange?() } } diff --git a/Sources/ParcelUpdate/UpdateAvailability.swift b/Sources/ParcelUpdate/UpdateAvailability.swift new file mode 100644 index 00000000..8dbd0f40 --- /dev/null +++ b/Sources/ParcelUpdate/UpdateAvailability.swift @@ -0,0 +1,19 @@ +struct UpdateAvailability { + enum Event: Sendable { + case found(String) + case notFound + case skipped + case dismissed + case willRelaunch + } + + private(set) var version: String? + + mutating func receive(_ event: Event) { + switch event { + case .found(let version): self.version = version + case .notFound, .skipped, .willRelaunch: version = nil + case .dismissed: break + } + } +} diff --git a/Tests/ParcelUpdateTests/UpdateAvailabilityTests.swift b/Tests/ParcelUpdateTests/UpdateAvailabilityTests.swift new file mode 100644 index 00000000..8e009399 --- /dev/null +++ b/Tests/ParcelUpdateTests/UpdateAvailabilityTests.swift @@ -0,0 +1,50 @@ +import AppKit +import Testing + +@testable import ParcelUpdate + +@MainActor +struct UpdateAvailabilityTests { + @Test(arguments: [UpdateAvailability.Event.skipped, .willRelaunch, .notFound]) + func completedUpdateClearsMenuAvailability(event: UpdateAvailability.Event) throws { + let driver = AvailabilityDriver() + let controller = UpdateController(isEnabled: true) { driver } + let menu = NSMenu() + try controller.start() + controller.installMenuItem(in: menu, at: 0) + let item = try #require(menu.items.first) + driver.receive(.found("2.0")) + #expect(item.title == "Update 2.0 Available…") + #expect(item.image != nil) + driver.receive(event) + #expect(controller.availableVersion == nil) + #expect(item.title == "Check for Updates…") + #expect(item.image == nil) + #expect(item.accessibilityLabel() == item.title) + #expect(item.isEnabled) + } + + @Test func dismissKeepsAvailableUpdateAndLaterDiscoveryReplacesIt() { + var availability = UpdateAvailability() + availability.receive(.found("2.0")) + availability.receive(.dismissed) + #expect(availability.version == "2.0") + availability.receive(.skipped) + availability.receive(.found("3.0")) + #expect(availability.version == "3.0") + } +} + +@MainActor +private final class AvailabilityDriver: UpdateDriver { + private var availability = UpdateAvailability() + var availableVersion: String? { availability.version } + let canCheckForUpdates = true + var availabilityDidChange: (@MainActor () -> Void)? + func start() {} + func checkForUpdates() {} + func receive(_ event: UpdateAvailability.Event) { + availability.receive(event) + availabilityDidChange?() + } +} -- knotmirror 0.0.1 From c0ea0a26b8980e64e766fb337f97827db3fdfbac Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 12:47:34 -0400 Subject: [PATCH 5/7] Keep release note headings separate --- Sources/ParcelUI/Resources/WhatsNew.xcstrings | 2 +- .../WhatsNew/WhatsNewController.swift | 4 ++-- .../WhatsNewAccessibilityTests.swift | 22 +++++++++++++++++++ 3 files changed, 25 insertions(+), 3 deletions(-) create mode 100644 Tests/ParcelUITests/WhatsNewAccessibilityTests.swift diff --git a/Sources/ParcelUI/Resources/WhatsNew.xcstrings b/Sources/ParcelUI/Resources/WhatsNew.xcstrings index d9bfdc61..f4bf2946 100644 --- a/Sources/ParcelUI/Resources/WhatsNew.xcstrings +++ b/Sources/ParcelUI/Resources/WhatsNew.xcstrings @@ -10,7 +10,7 @@ "Choose a layout and window count for the display under your pointer. Small previews show what to expect.": { "localizations": { "en": { "stringUnit": { "state": "translated", "value": "Choose a layout and window count for the display under your pointer. Small previews show what to expect." } } } }, "Check shortcuts and macOS settings, choose your preferences, then tidy your workspace when you’re ready.": { "localizations": { "en": { "stringUnit": { "state": "translated", "value": "Check shortcuts and macOS settings, choose your preferences, then tidy your workspace when you’re ready." } } } }, "Highlight the active window, every tile, or add a soft glow. Choose a width that feels right.": { "localizations": { "en": { "stringUnit": { "state": "translated", "value": "Highlight the active window, every tile, or add a soft glow. Choose a width that feels right." } } } }, - "Switch Focus, No peek, and Clean Space from the menu. Your choices belong to each display and Space.": { "localizations": { "en": { "stringUnit": { "state": "translated", "value": "Switch Focus, No peek, and Clean Space from the menu. Your choices belong to each display and Space." } } } } + "Switch Focus, No Peek, and Clean Space from the menu. Your choices belong to each display and Space.": { "localizations": { "en": { "stringUnit": { "state": "translated", "value": "Switch Focus, No Peek, and Clean Space from the menu. Your choices belong to each display and Space." } } } } }, "version": "1.0" } diff --git a/Sources/ParcelUI/WhatsNew/WhatsNewController.swift b/Sources/ParcelUI/WhatsNew/WhatsNewController.swift index 99c7b882..1f85f604 100644 --- a/Sources/ParcelUI/WhatsNew/WhatsNewController.swift +++ b/Sources/ParcelUI/WhatsNew/WhatsNewController.swift @@ -28,7 +28,7 @@ public enum WhatsNewFeature: String, CaseIterable, Sendable { "Highlight the active window, every tile, or add a soft glow. Choose a width that feels right.") case .privacy: WhatsNewText.text( - "Switch Focus, No peek, and Clean Space from the menu. Your choices belong to each display and Space.") + "Switch Focus, No Peek, and Clean Space from the menu. Your choices belong to each display and Space.") } } } @@ -72,7 +72,7 @@ private struct WhatsNewView: View { Text(feature.title).font(.headline).accessibilityAddTraits(.isHeader) Text(feature.detail).fixedSize(horizontal: false, vertical: true) } - .accessibilityElement(children: .combine) + .accessibilityElement(children: .contain) } } .padding(28) diff --git a/Tests/ParcelUITests/WhatsNewAccessibilityTests.swift b/Tests/ParcelUITests/WhatsNewAccessibilityTests.swift new file mode 100644 index 00000000..a6fb3227 --- /dev/null +++ b/Tests/ParcelUITests/WhatsNewAccessibilityTests.swift @@ -0,0 +1,22 @@ +import Foundation +import ParcelUI +import Testing + +struct WhatsNewAccessibilityTests { + @Test func featureHeadingsRemainSeparateFromTheirParagraphs() throws { + let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .deletingLastPathComponent() + let source = try String( + contentsOf: root.appendingPathComponent("Sources/ParcelUI/WhatsNew/WhatsNewController.swift"), + encoding: .utf8) + #expect(source.contains("Text(feature.title).font(.headline).accessibilityAddTraits(.isHeader)")) + #expect(source.contains(".accessibilityElement(children: .contain)")) + #expect(!source.contains(".accessibilityElement(children: .combine)")) + #expect( + WhatsNewFeature.allCases.map(\.title) == [ + "Your workspace, at a glance", "A little help getting settled", "Find your focus", + "Room to concentrate", + ]) + #expect(WhatsNewFeature.privacy.detail.contains("No Peek")) + } +} -- knotmirror 0.0.1 From 0d49dd167e76a03de2324592780252b06cd07b59 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 12:48:01 -0400 Subject: [PATCH 6/7] Target menu actions from their actual activation --- Package.swift | 5 + Sources/ParcelApp/AppIPCHandler.swift | 16 +- Sources/ParcelApp/AppNotices.swift | 7 +- Sources/ParcelApp/EngineShellServices.swift | 28 ++- Sources/ParcelApp/NativeAppRuntime.swift | 179 ++++++++++++--- Sources/ParcelApp/Resources/App.xcstrings | 4 + Sources/ParcelUI/DisplayNaming.swift | 61 +++++ Sources/ParcelUI/MenuBarController.swift | 57 ++--- Sources/ParcelUI/MenuWorkspace.swift | 103 ++++++++- Sources/ParcelUI/Resources/Menu.xcstrings | 11 +- .../ParcelAppTests/HighlightNoticeTests.swift | 20 ++ Tests/ParcelAppTests/MenuAppTests.swift | 119 ++++++++++ Tests/ParcelE2ETests/MenuAppTests.swift | 48 ---- .../MenuPanelEndToEndTests.swift | 96 ++++++-- Tests/ParcelUITests/MenuWorkspaceTests.swift | 212 +++++++++++++++++- 15 files changed, 806 insertions(+), 160 deletions(-) create mode 100644 Sources/ParcelUI/DisplayNaming.swift create mode 100644 Tests/ParcelAppTests/HighlightNoticeTests.swift create mode 100644 Tests/ParcelAppTests/MenuAppTests.swift delete mode 100644 Tests/ParcelE2ETests/MenuAppTests.swift diff --git a/Package.swift b/Package.swift index bd5dcce4..0f289d26 100644 --- a/Package.swift +++ b/Package.swift @@ -85,6 +85,11 @@ let package = Package( .testTarget(name: "ParcelAnimationTests", dependencies: ["ParcelAnimation"]), .testTarget(name: "ParcelUITests", dependencies: ["ParcelUI", "ParcelConfig", "ParcelAnimation"]), .testTarget(name: "ParcelIPCTests", dependencies: ["ParcelIPC", "ParcelEngine", "prcl"]), + .testTarget( + name: "ParcelAppTests", + dependencies: [ + "ParcelApp", "ParcelUI", "ParcelConfig", "ParcelCore", "ParcelEngine", "ParcelPlatform", "ParcelIPC", + ]), .testTarget( name: "ParcelE2ETests", dependencies: [ diff --git a/Sources/ParcelApp/AppIPCHandler.swift b/Sources/ParcelApp/AppIPCHandler.swift index 8f09b6d7..b59234a0 100644 --- a/Sources/ParcelApp/AppIPCHandler.swift +++ b/Sources/ParcelApp/AppIPCHandler.swift @@ -18,8 +18,9 @@ final class AppIPCHandler: IPCHandler { private let fixtureKeyInput: (@MainActor (AppFixtureKeyInput) async throws -> Void)? private let feedback: (@MainActor ([String]) async throws -> JSONValue)? private let secureInput: @MainActor () -> Bool + private let highlightAudit: (@MainActor () async throws -> JSONValue)? private let tour: (@MainActor ([String]) async throws -> JSONValue)? - private let menuAction: (@MainActor ([String]) throws -> Void)? + private let menuAction: (@MainActor ([String]) async throws -> Void)? init( services: EngineShellServices, configPath: String, @@ -27,14 +28,16 @@ final class AppIPCHandler: IPCHandler { fixtureKeyInput: (@MainActor (AppFixtureKeyInput) async throws -> Void)? = nil, feedback: (@MainActor ([String]) async throws -> JSONValue)? = nil, secureInput: @escaping @MainActor () -> Bool = { false }, + highlightAudit: (@MainActor () async throws -> JSONValue)? = nil, tour: (@MainActor ([String]) async throws -> JSONValue)? = nil, - menuAction: (@MainActor ([String]) throws -> Void)? = nil, + menuAction: (@MainActor ([String]) async throws -> Void)? = nil, permission: @escaping @MainActor () -> Bool ) { self.settingsAudit = settingsAudit self.fixtureKeyInput = fixtureKeyInput self.feedback = feedback self.secureInput = secureInput + self.highlightAudit = highlightAudit self.tour = tour self.menuAction = menuAction self.services = services @@ -84,11 +87,18 @@ final class AppIPCHandler: IPCHandler { } if command == "e2e-tour", let tour { return try await tour(args) } if command == "e2e-menu", let menuAction { - try menuAction(args) + try await menuAction(args) return .object(["accepted": .bool(true)]) } throw IPCError(code: "invalid_command", message: AppText.string("Fixture UI input is unavailable.")) } + if command == "e2e-highlights" { + guard ProcessInfo.processInfo.environment["PARCEL_E2E"] == "1", args.isEmpty, let highlightAudit else { + throw IPCError(code: "invalid_command", message: AppText.string("Fixture UI input is unavailable.")) + } + _ = try runningEngine() + return try await highlightAudit() + } if command == "e2e-key" { let request = try AppFixtureKeyInput(arguments: args, environment: ProcessInfo.processInfo.environment) guard let fixtureKeyInput else { throw AppFixtureDrag.rejected("Fixture keyboard input is unavailable") } diff --git a/Sources/ParcelApp/AppNotices.swift b/Sources/ParcelApp/AppNotices.swift index 71c54512..af67ad2d 100644 --- a/Sources/ParcelApp/AppNotices.swift +++ b/Sources/ParcelApp/AppNotices.swift @@ -6,7 +6,8 @@ import ParcelPlatform @MainActor final class AppNotices { enum Kind: String, CaseIterable { - case configuration, permission, hotkeys, input, brightness, dimming, login, restoration, ipc, startup, motion, + case configuration, permission, hotkeys, input, brightness, dimming, highlights, login, restoration, ipc, + startup, motion, feedback, internalFailure @@ -21,6 +22,10 @@ final class AppNotices { AppText.string("Window brightness could not be restored. Recovery will be retried at launch.") case .dimming: AppText.string("Compositor dimming could not be verified. No peek is using the privacy overlay.") + case .highlights: + AppText.string( + "Window Highlights are hidden because visible windows could not be checked. Try again from Settings." + ) case .login: AppText.string("The login setting could not be changed. Check Login Items in System Settings.") case .restoration: AppText.string("Some windows could not be restored before shutdown.") case .ipc: AppText.string("The command connection needs attention. Try reconnecting.") diff --git a/Sources/ParcelApp/EngineShellServices.swift b/Sources/ParcelApp/EngineShellServices.swift index 05e56b4e..592108fa 100644 --- a/Sources/ParcelApp/EngineShellServices.swift +++ b/Sources/ParcelApp/EngineShellServices.swift @@ -86,9 +86,20 @@ final class EngineShellServices: LayoutSnapshotProviding, UICommandSink { func send(_ command: ConfigCommand, in workspace: WorkspaceKey) async throws { guard let engine else { throw AppText.failure("Accessibility access is required before tiling can start.") } let result = try await engine.perform(EngineCommandParser.command(command), in: workspace) - guard result.isAccepted else { - throw AppText.failure("The menu action could not finish. Reopen the menu and try again.") + guard result.isAccepted else { throw Self.menuFailure(reports: result.reports) } + } + + static func menuFailure(reports: [Report]) -> AppFailure { + if reports.contains(.noFocusedWindow) { + return AppText.failure("Focus a window on this display first.") + } + if reports.contains(where: { if case .unavailableDisplay = $0 { true } else { false } }) { + return AppText.failure("This display is no longer connected. Reopen the menu on a connected display.") } + if reports.contains(.noActiveWorkspace) { + return AppText.failure("This desktop is no longer active. Reopen the menu and try again.") + } + return AppText.failure("The menu action could not finish. Reopen the menu and try again.") } func send(_ command: ConfigCommand) async throws { @@ -115,6 +126,19 @@ final class EngineShellServices: LayoutSnapshotProviding, UICommandSink { deinit { for subscriber in subscribers.values { subscriber.finish() } } } +struct MenuHighlightPreference { + private(set) var lastEnabled: ConfigHighlight = .active + + mutating func observe(_ style: ConfigHighlight) { + if style != .none { lastEnabled = style } + } + + mutating func toggled(from current: ConfigHighlight) -> ConfigHighlight { + observe(current) + return current == .none ? lastEnabled : .none + } +} + extension Rect { var cgRect: CGRect { CGRect(x: minX, y: minY, width: size.width, height: size.height) } } diff --git a/Sources/ParcelApp/NativeAppRuntime.swift b/Sources/ParcelApp/NativeAppRuntime.swift index 152a2aab..bdbd2d9f 100644 --- a/Sources/ParcelApp/NativeAppRuntime.swift +++ b/Sources/ParcelApp/NativeAppRuntime.swift @@ -62,6 +62,8 @@ final class NativeAppRuntime: AppRuntime { private var effectiveShortcuts: [ConfigCommand: KeyChord]? private var registeredShortcutConfiguration: ParcelConfiguration? private var notice: String? + private var highlightPreference = MenuHighlightPreference() + private var desktopSpaces: [NativeDisplaySpaces] = [] private let logger = Logger(subsystem: "dev.vinnymac.parcel", category: "app") init( @@ -86,12 +88,14 @@ final class NativeAppRuntime: AppRuntime { services.privacyPanelCount = { [weak self] in self?.overlays?.privacyPanelCount ?? 0 } services.cleanSpaceBackdropCount = { [weak self] in self?.overlays?.cleanSpaceBackdropCount ?? 0 } services.toggleBorders = { [weak self] in - guard let self, let composition = self.services.composition else { throw CancellationError() } - let enabled = composition.configuration.motion.highlight != .none - try await self.settings.setValue(.string(enabled ? "none" : "active"), for: .motion(.highlight)) + guard let self, let composition = self.services.composition else { + throw AppText.failure("Parcel is shutting down.") + } + let style = self.highlightPreference.toggled(from: composition.configuration.motion.highlight) + try await self.settings.setValue(.string(style.rawValue), for: .motion(.highlight)) let snapshot = await composition.reload() guard snapshot.loadState != .rejected, - composition.configuration.motion.highlight == (enabled ? .none : .active) + composition.configuration.motion.highlight == style else { throw AppText.failure("Highlight settings could not be applied. Review the configuration in Settings.") } @@ -154,10 +158,23 @@ final class NativeAppRuntime: AppRuntime { let snapshots = engine.snapshots() snapshotTask = Task { @MainActor [weak self] in var changes = AppSnapshotChanges() + var namedSpaces: [DisplayID: SpaceID]? + var namedDisplays: [DisplayID]? for await snapshot in snapshots { guard !Task.isCancelled, let self else { return } _ = self.synchronizeMode() self.services.publish(snapshot) + let displays = snapshot.state.displays.keys.sorted() + if self.nativeWorld != nil, + namedSpaces != snapshot.state.activeSpaces || namedDisplays != displays + { + namedSpaces = snapshot.state.activeSpaces + namedDisplays = displays + do { self.desktopSpaces = try await NativeSpaceReader().snapshot() } catch { + self.desktopSpaces = [] + self.services.composition?.report(error) + } + } self.feedback?.controller.update( state: snapshot.state, configuration: self.learningConfiguration.motion, active: engine.isRunning && !engine.isPaused && engine.systemWindowConflict == nil) @@ -183,6 +200,7 @@ final class NativeAppRuntime: AppRuntime { } func applyConfiguration(_ configuration: ParcelConfiguration) throws { + highlightPreference.observe(configuration.motion.highlight) try services.engine?.applyConfiguration(configuration) learningConfiguration = configuration if hotkeyBindings != nil { @@ -213,7 +231,9 @@ final class NativeAppRuntime: AppRuntime { let overlays = OverlayController(configuration: configuration.motion, focusModes: configuration.focusModes) { [weak self] error in let kind: AppNotices.Kind = - (error as? OverlayBrightnessError) == .verificationFailed ? .dimming : .brightness + error is OverlayWindowReadError + ? .highlights + : (error as? OverlayBrightnessError) == .verificationFailed ? .dimming : .brightness self?.services.composition?.report(error, kind: kind) } overlays.inspectionWindow = { [weak self] in self?.world?.inspectionWindow($0) } @@ -257,6 +277,12 @@ final class NativeAppRuntime: AppRuntime { guard let feedback = self?.feedback else { throw AppText.failure("Parcel is shutting down.") } return try await feedback.run(arguments) }, secureInput: { [weak self] in self?.secureInput.refresh() == true }, + highlightAudit: { [weak self] in + guard let self, self.fixtureOnly, ProcessInfo.processInfo.environment["PARCEL_E2E"] == "1", + let overlays = self.overlays + else { throw AppText.failure("Parcel is not tiling right now.") } + return try JSONDecoder().decode(JSONValue.self, from: JSONEncoder().encode(overlays.highlightAudit())) + }, tour: { [weak self] arguments in guard let self, self.fixtureOnly, let learning = self.learning else { throw TourSetupFailure.unavailable @@ -265,7 +291,7 @@ final class NativeAppRuntime: AppRuntime { }, menuAction: { [weak self] arguments in guard let self, self.fixtureOnly else { throw TourSetupFailure.unavailable } - try self.performFixtureMenuAction(arguments) + try await self.performFixtureMenuAction(arguments) }, permission: { [permissions] in permissions.status == .granted }) let server = try IPCServer(handler: handler, socketPath: socketPath) { [weak self] error in @@ -582,7 +608,9 @@ extension NativeAppRuntime { } try await shell.start() shell.menuBar?.onMenuNeedsUpdate = { [weak self] in _ = self?.secureInput.refresh() } - shell.menuBar?.workspaceAtPointer = { [weak self] in self?.menuWorkspace() } + shell.menuBar?.workspaceForActivation = { [weak self] activation in + self?.menuWorkspace(activation) ?? .failure(.disconnected) + } shell.menuBar?.invokeInWorkspace = { [weak self] command, workspace in self?.dispatch { [weak self] in guard let self else { throw CancellationError() } @@ -599,46 +627,119 @@ extension NativeAppRuntime { } } } - private func performFixtureMenuAction(_ arguments: [String]) throws { - guard arguments.count == 2, let count = Int(arguments[1]), (1...5).contains(count), - let engine = services.engine, engine.isRunning, let menuBar = shell?.menuBar + private func performFixtureMenuAction(_ arguments: [String]) async throws { + guard fixtureOnly, ProcessInfo.processInfo.environment["PARCEL_E2E"] == "1", + arguments.count == 2, let count = Int(arguments[1]), (1...5).contains(count), + let engine = services.engine, engine.isRunning, let menuBar = shell?.menuBar, + let button = menuBar.statusItem.button, let window = button.window, let statusScreen = window.screen, + CGPreflightPostEventAccess(), let cursor = CGEvent(source: nil), + !CGEventSource.buttonState(.combinedSessionState, button: .left), + !CGEventSource.buttonState(.combinedSessionState, button: .right), + CGEventSource.flagsState(.combinedSessionState) + .intersection([.maskCommand, .maskAlternate, .maskControl, .maskShift, .maskSecondaryFn]).isEmpty else { throw TourSetupFailure.unavailable } let display = DisplayID(rawValue: arguments[0]) - guard let space = engine.snapshot.state.activeSpaces[display] else { throw TourSetupFailure.unavailable } - let key = WorkspaceKey(display: display, space: space) - guard let snapshot = services.menuSnapshot(engine.snapshot, in: key) else { throw TourSetupFailure.unavailable } - let provider = menuBar.workspaceAtPointer - defer { menuBar.workspaceAtPointer = provider } - menuBar.workspaceAtPointer = { MenuWorkspace(key: key, snapshot: snapshot) } - menuBar.menuNeedsUpdate(menuBar.menu) - let identifier = NSUserInterfaceItemIdentifier(ConfigCommand.setWindowCap(count).rawValue) - guard - let item = menuBar.menu.items.compactMap(\.submenu).flatMap(\.items).first(where: { - $0.identifier == identifier - }), - item.isEnabled, let submenu = item.menu + guard try DisplayNaming.id(for: statusScreen) == display, + let space = engine.snapshot.state.activeSpaces[display], + let workspace = engine.snapshot.state.workspaces[WorkspaceKey(display: display, space: space)], + !workspace.order.isEmpty else { throw TourSetupFailure.unavailable } - submenu.performActionForItem(at: submenu.index(of: item)) + let frame = window.convertToScreen(button.convert(button.bounds, to: nil)) + let point = CGPoint(x: frame.midX, y: frame.midY) + let location = CGPoint(x: point.x, y: CGDisplayBounds(CGMainDisplayID()).height - point.y) + guard statusScreen.frame.contains(point), let source = CGEventSource(stateID: .privateState), + let down = CGEvent( + mouseEventSource: source, mouseType: .leftMouseDown, + mouseCursorPosition: location, mouseButton: .left), + let up = CGEvent( + mouseEventSource: source, mouseType: .leftMouseUp, + mouseCursorPosition: location, mouseButton: .left) + else { throw TourSetupFailure.unavailable } + let rendered = menuBar.onMenuRendered + var result: Result? + menuBar.onMenuRendered = { menu in + rendered?(menu) + let identifier = NSUserInterfaceItemIdentifier(ConfigCommand.setWindowCap(count).rawValue) + let item = menu.items.compactMap(\.submenu).flatMap(\.items).first { $0.identifier == identifier } + DispatchQueue.main.async { + menu.cancelTrackingWithoutAnimation() + guard let item, item.isEnabled, let submenu = item.menu else { + result = .failure(TourSetupFailure.unavailable) + return + } + submenu.performActionForItem(at: submenu.index(of: item)) + result = .success(()) + } + } + defer { menuBar.onMenuRendered = rendered } + do { + guard CGWarpMouseCursorPosition(location) == .success else { throw TourSetupFailure.unavailable } + for event in [down, up] { + event.flags = [] + event.setIntegerValueField(.mouseEventClickState, value: 1) + event.setIntegerValueField(.eventTargetUnixProcessID, value: Int64(getpid())) + event.setIntegerValueField(.mouseEventWindowUnderMousePointer, value: Int64(window.windowNumber)) + event.setIntegerValueField( + .mouseEventWindowUnderMousePointerThatCanHandleThisEvent, value: Int64(window.windowNumber)) + event.postToPid(getpid()) + try await Task.sleep(for: .milliseconds(50)) + } + let deadline = ContinuousClock.now.advanced(by: .seconds(5)) + while result == nil { + guard ContinuousClock.now < deadline else { throw TourSetupFailure.unavailable } + try await Task.sleep(for: .milliseconds(50)) + } + if let result { try result.get() } + } catch { + menuBar.menu.cancelTrackingWithoutAnimation() + up.postToPid(getpid()) + guard CGWarpMouseCursorPosition(cursor.location) == .success else { + throw AppFixtureDrag.rejected("The menu test could not restore the pointer after failing: \(error)") + } + throw error + } + guard CGWarpMouseCursorPosition(cursor.location) == .success else { + throw AppFixtureDrag.rejected("The menu test could not restore the pointer") + } } - private func menuWorkspace() -> MenuWorkspace? { - guard let engine = services.engine, engine.isRunning else { return nil } + private func menuWorkspace( + _ activation: MenuWorkspaceActivation + ) -> Result { + guard let engine = services.engine, engine.isRunning else { return .failure(.disconnected) } do { - let displays = try Displays().current() - let screens = Dictionary( - uniqueKeysWithValues: displays.map { (DisplayID(rawValue: $0.id.uuidString), $0.frame) }) - guard - let key = MenuWorkspace.target( - at: NSEvent.mouseLocation, screens: screens, state: engine.snapshot.state), - let snapshot = services.menuSnapshot(engine.snapshot, in: key) - else { return nil } - return MenuWorkspace(key: key, snapshot: snapshot) + let displays = try DisplayNaming.screens() + let screens = Dictionary(uniqueKeysWithValues: displays.map { ($0.id, $0.frame) }) + let state = engine.snapshot.state + let statusDisplay = try activation.statusScreen.map { try DisplayNaming.id(for: $0) } + let target = MenuWorkspace.target( + at: activation.pointer, statusDisplay: statusDisplay, screens: screens, state: state) + return target.flatMap { key in + guard let snapshot = services.menuSnapshot(engine.snapshot, in: key) else { + return .failure(.unmanagedSpace) + } + let desktop = Self.menuDesktop(in: key, displays: desktopSpaces) + if let desktop, desktop.kind != .desktop { return .failure(.unmanagedSpace) } + return .success( + MenuWorkspace( + key: key, snapshot: snapshot, + displayName: DisplayNaming.name(for: key.display, screens: displays, state: state), + desktopNumber: desktop?.desktopNumber, + hasFocusedWindow: state.focusedWindow.flatMap { state.workspace(containing: $0) } == key)) + } } catch { services.composition?.report(error) - return nil + return .failure(.disconnected) } } + static func menuDesktop(in key: WorkspaceKey, displays: [NativeDisplaySpaces]) -> NativeSpace? { + let display = + displays.first { $0.displayID.caseInsensitiveCompare(key.display.rawValue) == .orderedSame } + ?? displays.first { $0.displayID == "Main" } + return display?.spaces.first { $0.id == key.space.rawValue } + } + private func auditSettings() async throws -> JSONValue { let thread = try AppThread(pid: getpid()) defer { thread.shutdown() } @@ -720,10 +821,14 @@ extension NativeAppRuntime { } func setLaunchAtLogin(_ enabled: Bool) throws { let item = SMAppService.mainApp - if enabled, item.status != .enabled { try item.register() } + if Self.shouldRegisterLoginItem(enabled: enabled, status: item.status) { try item.register() } if !enabled, item.status == .enabled || item.status == .requiresApproval { try item.unregister() } } + static func shouldRegisterLoginItem(enabled: Bool, status: SMAppService.Status) -> Bool { + enabled && status != .enabled && status != .requiresApproval + } + func stopInput() throws { drag?.stop() drag = nil diff --git a/Sources/ParcelApp/Resources/App.xcstrings b/Sources/ParcelApp/Resources/App.xcstrings index b31d86fd..819451af 100644 --- a/Sources/ParcelApp/Resources/App.xcstrings +++ b/Sources/ParcelApp/Resources/App.xcstrings @@ -1,6 +1,10 @@ { "sourceLanguage" : "en", "strings" : { + "Focus a window on this display first." : {"localizations": {"en": {"stringUnit": {"state": "translated", "value": "Focus a window on this display first."}}}}, + "This display is no longer connected. Reopen the menu on a connected display." : {"localizations": {"en": {"stringUnit": {"state": "translated", "value": "This display is no longer connected. Reopen the menu on a connected display."}}}}, + "This desktop is no longer active. Reopen the menu and try again." : {"localizations": {"en": {"stringUnit": {"state": "translated", "value": "This desktop is no longer active. Reopen the menu and try again."}}}}, + "Window Highlights are hidden because visible windows could not be checked. Try again from Settings." : {"localizations": {"en": {"stringUnit": {"state": "translated", "value": "Window Highlights are hidden because visible windows could not be checked. Try again from Settings."}}}}, "The menu action could not finish. Reopen the menu and try again." : {"localizations": {"en": {"stringUnit": {"state": "translated", "value": "The menu action could not finish. Reopen the menu and try again."}}}}, "Highlight settings could not be applied. Review the configuration in Settings." : {"localizations": {"en": {"stringUnit": {"state": "translated", "value": "Highlight settings could not be applied. Review the configuration in Settings."}}}}, "Fixture UI input requires e2e mode." : {"localizations": {"en": {"stringUnit": {"state": "translated", "value": "Fixture UI input requires e2e mode."}}}}, diff --git a/Sources/ParcelUI/DisplayNaming.swift b/Sources/ParcelUI/DisplayNaming.swift new file mode 100644 index 00000000..b4eb4c48 --- /dev/null +++ b/Sources/ParcelUI/DisplayNaming.swift @@ -0,0 +1,61 @@ +public import AppKit +public import ParcelCore + +public enum DisplayNaming { + public struct Screen: Equatable, Sendable { + public let id: DisplayID + public let frame: CGRect + public let name: String + + public init(id: DisplayID, frame: CGRect, name: String) { + self.id = id + self.frame = frame + self.name = name + } + } + + public enum Failure: LocalizedError { + case missingIdentity + + public var errorDescription: String? { + MenuText.text("A connected display could not be identified. Reconnect it and reopen the menu.") + } + } + + @MainActor + public static func id(for screen: NSScreen) throws -> DisplayID { + guard let number = screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber, + let uuid = CGDisplayCreateUUIDFromDisplayID(number.uint32Value)?.takeRetainedValue(), + let text = CFUUIDCreateString(nil, uuid) + else { throw Failure.missingIdentity } + return DisplayID(rawValue: text as String) + } + + @MainActor + public static func screens() throws -> [Screen] { + try NSScreen.screens.map { Screen(id: try id(for: $0), frame: $0.frame, name: $0.localizedName) } + } + + @MainActor + public static func name(for display: DisplayID, in state: State) throws -> String { + name(for: display, screens: try screens(), state: state) + } + + public static func name(for display: DisplayID, screens: [Screen], state: State) -> String { + if let name = screens.first(where: { $0.id == display })?.name, + !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + { + return name + } + let ordered = state.displays.values.sorted { + if $0.frame.minX != $1.frame.minX { return $0.frame.minX < $1.frame.minX } + if $0.frame.minY != $1.frame.minY { return $0.frame.minY < $1.frame.minY } + return $0.id < $1.id + } + let number = + ordered.firstIndex(where: { $0.id == display }).map { $0 + 1 } + ?? screens.firstIndex(where: { $0.id == display }).map { $0 + 1 } + guard let number else { return MenuText.text("Display unavailable") } + return String(format: MenuText.text("Display %lld"), locale: .current, Int64(number)) + } +} diff --git a/Sources/ParcelUI/MenuBarController.swift b/Sources/ParcelUI/MenuBarController.swift index 9762834d..79f4c52a 100644 --- a/Sources/ParcelUI/MenuBarController.swift +++ b/Sources/ParcelUI/MenuBarController.swift @@ -170,7 +170,8 @@ public final class MenuBarController: NSObject, NSMenuDelegate { public let menu: NSMenu public var onMenuRendered: (@MainActor (NSMenu) -> Void)? public var onMenuNeedsUpdate: (@MainActor () -> Void)? - public var workspaceAtPointer: (@MainActor () -> MenuWorkspace?)? + public var workspaceForActivation: + (@MainActor (MenuWorkspaceActivation) -> Result)? public var invokeInWorkspace: (@MainActor (ConfigCommand, MenuWorkspace) -> Void)? public var showWhatsNew: (@MainActor () -> Void)? private let shortMenu: CommandMenu @@ -182,7 +183,8 @@ public final class MenuBarController: NSObject, NSMenuDelegate { private var animation: Task? private var appearanceObservation: NSKeyValueObservation? private var pointerMonitor: (any NSObjectProtocol)? - private var pointerActivation: (id: UUID, menu: NSMenu)? + private var pointerActivation: (id: UUID, menu: NSMenu, location: CGPoint)? + private var openingPointer: CGPoint? private var trackingMenu: NSMenu? private var stopped = false private var lastContrast = false @@ -318,6 +320,7 @@ public final class MenuBarController: NSObject, NSMenuDelegate { public func menuDidClose(_ menu: NSMenu) { if trackingMenu === menu { trackingMenu = nil } + openingPointer = nil } func menuForActivation(_ event: NSEvent?) -> NSMenu { @@ -332,7 +335,7 @@ public final class MenuBarController: NSObject, NSMenuDelegate { event.window === window, event.type == .leftMouseUp || event.type == .rightMouseUp else { return } let id = UUID() - pointerActivation = (id, menuForActivation(event)) + pointerActivation = (id, menuForActivation(event), window.convertPoint(toScreen: event.locationInWindow)) DispatchQueue.main.async { [weak self] in if self?.pointerActivation?.id == id { self?.pointerActivation = nil } } @@ -341,6 +344,7 @@ public final class MenuBarController: NSObject, NSMenuDelegate { func consumeActivationMenu() -> NSMenu { defer { pointerActivation = nil } // AXPress can leave currentEvent pointing at an old click. + openingPointer = pointerActivation?.location return pointerActivation?.menu ?? menu } @@ -362,12 +366,21 @@ public final class MenuBarController: NSObject, NSMenuDelegate { } private func fill(_ menu: CommandMenu, presentation: MenuPresentation, short: Bool) { - let workspace = workspaceAtPointer?() + let target = workspaceForActivation?( + MenuWorkspaceActivation(pointer: openingPointer, statusScreen: statusItem.button?.window?.screen)) + let workspace: MenuWorkspace? + let unavailability: MenuWorkspace.Unavailability? + switch target { + case .success(let selected): (workspace, unavailability) = (selected, nil) + case .failure(let reason): (workspace, unavailability) = (nil, reason) + case nil: (workspace, unavailability) = (nil, nil) + } let snapshot = workspace?.snapshot ?? presentation.snapshot - let unavailable = workspaceAtPointer != nil && workspace == nil + let unavailable = unavailability != nil let invoke: @MainActor (ConfigCommand) -> Void = { [weak self] command in guard let self else { return } if command.targetsMenuWorkspace, let workspace { + guard workspace.disabledReason(for: command) == nil else { return } guard let send = self.invokeInWorkspace else { preconditionFailure("A workspace menu needs a command sink") } @@ -388,11 +401,12 @@ public final class MenuBarController: NSObject, NSMenuDelegate { let item = CommandMenuItem( title: title, command: command, chord: shortcuts[command], invoke: invoke) destination.addItem(item) - if unavailable && command.targetsMenuWorkspace { + let reason = + command.targetsMenuWorkspace ? unavailability?.detail ?? workspace?.disabledReason(for: command) : nil + if let reason { item.isEnabled = false - item.toolTip = MenuText.text( - "The display under the pointer is unavailable. Reopen the menu on a connected display.") - item.setAccessibilityHelp(item.toolTip) + item.toolTip = reason + item.setAccessibilityHelp(reason) } else { menu.routing.bindings[command] = shortcuts[command] } @@ -400,22 +414,16 @@ public final class MenuBarController: NSObject, NSMenuDelegate { } if !short { let summary = NSMenuItem.sectionHeader( - title: unavailable ? MenuText.text("Display unavailable") : snapshot.accessibilityDescription) + title: unavailability?.title ?? snapshot.accessibilityDescription) if !unavailable { summary.image = renderer.image( for: MenuIcon(snapshot: snapshot, style: .minimap), increaseContrast: presentation.increaseContrast) } menu.addItem(summary) if let workspace { - let title = String( - format: MenuText.text("Display %@ · Space %llu"), locale: .current, - workspace.key.display.rawValue, workspace.key.space.rawValue) - menu.addItem(.sectionHeader(title: title)) - } else if unavailable { - menu.addItem( - .sectionHeader( - title: MenuText.text( - "The display under the pointer is unavailable. Reopen the menu on a connected display."))) + menu.addItem(.sectionHeader(title: workspace.title)) + } else if let unavailability { + menu.addItem(.sectionHeader(title: unavailability.detail)) } if let systemNotice = presentation.systemNotice { menu.addItem(SystemNoticeMenuItem(title: systemNotice, invoke: openSystemSettings)) @@ -435,10 +443,7 @@ public final class MenuBarController: NSObject, NSMenuDelegate { let item = add(layout.uiTitle, layout.command, to: layouts) item.state = !unavailable && snapshot.layout == layout ? .on : .off guard !unavailable else { continue } - let count = min( - snapshot.windowCap == 0 - ? max(1, snapshot.tiles.count) : (snapshot.windowCap ?? max(1, snapshot.tiles.count)), - layout.capabilities(in: snapshot.bounds).maximumWindowCount) + let count = MenuLayoutPreview.count(for: layout, in: snapshot) item.image = renderer.image( for: MenuIcon( snapshot: MenuLayoutPreview.snapshot( @@ -451,7 +456,7 @@ public final class MenuBarController: NSObject, NSMenuDelegate { let counts = NSMenu(title: countItem.title) counts.autoenablesItems = false for preset in WindowCountPreset.allCases { - let reason = unavailable ? MenuText.text("Display unavailable") : preset.disabledReason(in: snapshot) + let reason = unavailability?.detail ?? preset.disabledReason(in: snapshot) let title = reason.map { String(format: UIStrings.text("%@ — %@"), locale: .current, preset.title, $0) @@ -505,8 +510,8 @@ public final class MenuBarController: NSObject, NSMenuDelegate { pause.state = snapshot.isPaused ? .on : .off if !short { _ = add(UIStrings.text("Retile"), .retile, to: menu) - let borders = add(MenuText.text("Borders"), .toggleBorders, to: menu) - borders.state = presentation.configuration.motion.highlight == .none ? .off : .on + let highlights = add(MenuText.text("Window Highlights"), .toggleBorders, to: menu) + highlights.state = presentation.configuration.motion.highlight == .none ? .off : .on if let enabled = snapshot.hoverFocus { let hover = add(MenuText.text("Hover Focus"), .toggleHoverFocus, to: menu) hover.state = enabled ? .on : .off diff --git a/Sources/ParcelUI/MenuWorkspace.swift b/Sources/ParcelUI/MenuWorkspace.swift index 8afeb8e9..2a6fcce0 100644 --- a/Sources/ParcelUI/MenuWorkspace.swift +++ b/Sources/ParcelUI/MenuWorkspace.swift @@ -2,22 +2,98 @@ public import AppKit import ParcelConfig public import ParcelCore +public struct MenuWorkspaceActivation { + public let pointer: CGPoint? + public let statusScreen: NSScreen? + + public init(pointer: CGPoint?, statusScreen: NSScreen?) { + self.pointer = pointer + self.statusScreen = statusScreen + } +} + public struct MenuWorkspace: Equatable, Sendable { + public enum Unavailability: Error, Equatable, Sendable { + case disconnected + case unmanagedSpace + + var title: String { + MenuText.text(self == .disconnected ? "Display unavailable" : "Space not arranged") + } + + var detail: String { + MenuText.text( + self == .disconnected + ? "This display is unavailable. Reopen the menu on a connected display." + : "Parcel doesn’t arrange this Space (for example, a full-screen app).") + } + } + public let key: WorkspaceKey public let snapshot: LayoutSnapshot + public let displayName: String + public let desktopNumber: Int? + public let hasFocusedWindow: Bool - public init(key: WorkspaceKey, snapshot: LayoutSnapshot) { + public init( + key: WorkspaceKey, snapshot: LayoutSnapshot, displayName: String, desktopNumber: Int? = nil, + hasFocusedWindow: Bool = false + ) { self.key = key self.snapshot = snapshot + self.displayName = displayName + self.desktopNumber = desktopNumber + self.hasFocusedWindow = hasFocusedWindow + } + + var title: String { + guard let desktopNumber else { return displayName } + return String( + format: MenuText.text("%@ · Desktop %lld"), locale: .current, displayName, Int64(desktopNumber)) + } + + func disabledReason(for command: ConfigCommand) -> String? { + let needsFocus: Bool + switch command { + case .toggleFocus: needsFocus = !snapshot.isFocused + case .toggleNoPeek: needsFocus = !snapshot.noPeek + case .toggleCleanSpace: needsFocus = !snapshot.cleanSpace + default: needsFocus = false + } + return needsFocus && !hasFocusedWindow ? MenuText.text("Focus a window on this display first.") : nil } - public static func target(at pointer: CGPoint, screens: [DisplayID: CGRect], state: State) -> WorkspaceKey? { - guard pointer.x.isFinite, pointer.y.isFinite, - let display = screens.keys.sorted().first(where: { screens[$0]?.contains(pointer) == true }), - state.displays[display] != nil, let space = state.activeSpaces[display] - else { return nil } + public static func target( + at pointer: CGPoint?, statusDisplay: DisplayID? = nil, screens: [DisplayID: CGRect], state: State + ) -> Result { + let display: DisplayID? + if let pointer { + guard pointer.x.isFinite, pointer.y.isFinite else { return .failure(.disconnected) } + let ordered = screens.keys.sorted() + // Prefer the interior at shared edges; include the menu bar's outermost pixel only as a second pass. + display = + ordered.first { screens[$0]?.contains(pointer) == true } + ?? ordered.first { + guard let frame = screens[$0] else { return false } + return pointer.x >= frame.minX && pointer.x < frame.maxX + && pointer.y >= frame.minY && pointer.y <= frame.maxY + } + ?? ordered.first { + guard let frame = screens[$0] else { return false } + return pointer.x >= frame.minX && pointer.x <= frame.maxX + && pointer.y >= frame.minY && pointer.y <= frame.maxY + } + } else { + display = + statusDisplay.flatMap { screens[$0] != nil && state.displays[$0] != nil ? $0 : nil } + ?? state.activeWorkspace?.display + } + guard let display, screens[display] != nil, state.displays[display] != nil else { + return .failure(.disconnected) + } + guard let space = state.activeSpaces[display] else { return .failure(.unmanagedSpace) } let key = WorkspaceKey(display: display, space: space) - return state.workspaces[key] == nil ? nil : key + return state.workspaces[key] == nil ? .failure(.unmanagedSpace) : .success(key) } } @@ -34,15 +110,24 @@ extension ConfigCommand { } struct MenuLayoutPreview { + static let maximumTileCount = 5 + + static func count(for layout: ConfigLayout, in snapshot: LayoutSnapshot) -> Int { + let visibleCount = max(1, snapshot.tiles.count) + let requested = snapshot.windowCap.flatMap { $0 > 0 ? $0 : nil } ?? visibleCount + return max(1, min(requested, maximumTileCount, layout.capabilities(in: snapshot.bounds).maximumWindowCount)) + } + static func snapshot(layout: ConfigLayout, count: Int, bounds: CGRect, ratio: Double) -> LayoutSnapshot { let key = WorkspaceKey(display: DisplayID(rawValue: "preview"), space: SpaceID(rawValue: 1)) - let ids = (1...max(1, min(count, 5))).map { WindowID(rawValue: UInt32($0)) } + let ids = (1...max(1, min(count, maximumTileCount))).map { WindowID(rawValue: UInt32($0)) } guard let coreLayout = Layout(rawValue: layout.rawValue) else { preconditionFailure("Every configured layout needs a core layout") } - let workspace = Workspace( + var workspace = Workspace( key: key, layout: coreLayout, ratio: MainRatio(ratio), windowCap: ids.count, order: ids) let frame = Rect(width: bounds.width, height: bounds.height) + workspace.adapt(to: frame) let windows = Dictionary( uniqueKeysWithValues: ids.map { ($0, ManagedWindow(id: $0, app: AppID(pid: 0, bundleID: "preview"))) diff --git a/Sources/ParcelUI/Resources/Menu.xcstrings b/Sources/ParcelUI/Resources/Menu.xcstrings index ec794955..082bab2c 100644 --- a/Sources/ParcelUI/Resources/Menu.xcstrings +++ b/Sources/ParcelUI/Resources/Menu.xcstrings @@ -1,11 +1,16 @@ { "sourceLanguage": "en", "strings": { - "Borders": { "localizations": { "en": { "stringUnit": { "state": "translated", "value": "Borders" } } } }, + "Window Highlights": { "localizations": { "en": { "stringUnit": { "state": "translated", "value": "Window Highlights" } } } }, "Hover Focus": { "localizations": { "en": { "stringUnit": { "state": "translated", "value": "Hover Focus" } } } }, - "Display %@ · Space %llu": { "localizations": { "en": { "stringUnit": { "state": "translated", "value": "Display %@ · Space %llu" } } } }, + "%@ · Desktop %lld": { "localizations": { "en": { "stringUnit": { "state": "translated", "value": "%@ · Desktop %lld" } } } }, + "Display %lld": { "localizations": { "en": { "stringUnit": { "state": "translated", "value": "Display %lld" } } } }, "Display unavailable": { "localizations": { "en": { "stringUnit": { "state": "translated", "value": "Display unavailable" } } } }, - "The display under the pointer is unavailable. Reopen the menu on a connected display.": { "localizations": { "en": { "stringUnit": { "state": "translated", "value": "The display under the pointer is unavailable. Reopen the menu on a connected display." } } } }, + "Space not arranged": { "localizations": { "en": { "stringUnit": { "state": "translated", "value": "Space not arranged" } } } }, + "This display is unavailable. Reopen the menu on a connected display.": { "localizations": { "en": { "stringUnit": { "state": "translated", "value": "This display is unavailable. Reopen the menu on a connected display." } } } }, + "Parcel doesn’t arrange this Space (for example, a full-screen app).": { "localizations": { "en": { "stringUnit": { "state": "translated", "value": "Parcel doesn’t arrange this Space (for example, a full-screen app)." } } } }, + "Focus a window on this display first.": { "localizations": { "en": { "stringUnit": { "state": "translated", "value": "Focus a window on this display first." } } } }, + "A connected display could not be identified. Reconnect it and reopen the menu.": { "localizations": { "en": { "stringUnit": { "state": "translated", "value": "A connected display could not be identified. Reconnect it and reopen the menu." } } } }, "What’s New…": { "localizations": { "en": { "stringUnit": { "state": "translated", "value": "What’s New…" } } } } }, "version": "1.0" diff --git a/Tests/ParcelAppTests/HighlightNoticeTests.swift b/Tests/ParcelAppTests/HighlightNoticeTests.swift new file mode 100644 index 00000000..d9a1e286 --- /dev/null +++ b/Tests/ParcelAppTests/HighlightNoticeTests.swift @@ -0,0 +1,20 @@ +import Testing + +@testable import ParcelApp + +@MainActor +struct HighlightNoticeTests { + @Test func highlightReadFailureDoesNotSuggestDisablingMotionOrRestoringBrightness() { + let notices = AppNotices() + notices.report(NoticeFailure(), kind: .highlights) + #expect( + notices.visible == [ + "Window Highlights are hidden because visible windows could not be checked. Try again from Settings." + ]) + #expect(notices.counts[.highlights] == 1) + notices.clear(.highlights) + #expect(notices.visible.isEmpty) + } +} + +private struct NoticeFailure: Error {} diff --git a/Tests/ParcelAppTests/MenuAppTests.swift b/Tests/ParcelAppTests/MenuAppTests.swift new file mode 100644 index 00000000..2606191a --- /dev/null +++ b/Tests/ParcelAppTests/MenuAppTests.swift @@ -0,0 +1,119 @@ +import Foundation +import ParcelConfig +import ParcelCore +import ParcelPlatform +import ParcelUI +import ServiceManagement +import Testing + +@testable import ParcelApp +@testable import ParcelEngine + +@MainActor +struct MenuAppTests { + @Test func shellSnapshotUsesAddressedSpaceAndItsModes() throws { + let first = DisplayID(rawValue: "first") + let second = DisplayID(rawValue: "second") + let space = SpaceID(rawValue: 8) + let key = WorkspaceKey(display: second, space: space) + var state = State( + displays: [ + Display(id: first, frame: Rect(width: 1440, height: 900)), + Display(id: second, frame: Rect(x: 1440, y: 0, width: 1440, height: 900)), + ], activeSpaces: [first: SpaceID(rawValue: 2), second: space], activeDisplay: first) + state.workspaces[key] = Workspace(key: key, layout: .rows, ratio: .twoThirds, windowCap: 2) + state.focusModes = [key: FocusModes(noPeek: true, cleanSpace: true)] + let services = EngineShellServices() + let snapshot = try #require(services.menuSnapshot(EngineSnapshot(revision: 1, state: state), in: key)) + #expect(snapshot.layout == .rows) + #expect(snapshot.windowCap == 2) + #expect(snapshot.ratio == 2.0 / 3) + #expect(snapshot.noPeek && snapshot.cleanSpace) + #expect( + services.menuSnapshot( + EngineSnapshot(revision: 1, state: state), + in: WorkspaceKey(display: second, space: SpaceID(rawValue: 99))) == nil) + state.displays[second] = nil + #expect(services.menuSnapshot(EngineSnapshot(revision: 2, state: state), in: key) == nil) + } + + @Test(arguments: ConfigHighlight.allCases.filter { $0 != .none }) + func highlightTogglePreservesEveryEnabledStyle(style: ConfigHighlight) { + var preference = MenuHighlightPreference() + #expect(preference.toggled(from: style) == .none) + #expect(preference.toggled(from: .none) == style) + #expect(preference.toggled(from: style) == .none) + #expect(preference.toggled(from: .none) == style) + } + + @Test func highlightToggleFollowsSettingsChangesWithoutForgettingWhenOff() { + var preference = MenuHighlightPreference() + #expect(preference.toggled(from: .none) == .active) + preference.observe(.all) + preference.observe(.none) + #expect(preference.toggled(from: .none) == .all) + preference.observe(.glow) + #expect(preference.toggled(from: .none) == .glow) + } + + @Test func runtimeHighlightToggleMissingCompositionIsVisibleFailure() async throws { + let runtime = NativeAppRuntime(store: ConfigStore(), socketPath: "/tmp/menu-tests-unused.sock") + await #expect(throws: AppFailure.self) { try await runtime.services.send(.toggleBorders) } + } + + @Test func loginItemApprovalDoesNotRegisterAgain() { + for status in [SMAppService.Status.enabled, .requiresApproval, .notRegistered, .notFound] { + #expect(!NativeAppRuntime.shouldRegisterLoginItem(enabled: false, status: status)) + #expect( + NativeAppRuntime.shouldRegisterLoginItem(enabled: true, status: status) + == (status == .notRegistered || status == .notFound)) + } + } + + @Test func desktopLabelsUseNativeOrdinalsAndSharedSpaceIdentity() { + let key = WorkspaceKey(display: DisplayID(rawValue: "DISPLAY-B"), space: SpaceID(rawValue: 999)) + let desktop = NativeSpace(id: 999, kind: .desktop, desktopNumber: 3) + let displays = [ + NativeDisplaySpaces( + displayID: "display-b", currentSpace: 999, + spaces: [ + NativeSpace(id: 44, kind: .desktop, desktopNumber: 2), desktop, + ]) + ] + #expect(NativeAppRuntime.menuDesktop(in: key, displays: displays) == desktop) + #expect( + NativeAppRuntime.menuDesktop( + in: key, displays: [NativeDisplaySpaces(displayID: "Main", currentSpace: 999, spaces: [desktop])]) + == desktop) + #expect(NativeAppRuntime.menuDesktop(in: key, displays: []) == nil) + #expect( + NativeAppRuntime.menuDesktop( + in: WorkspaceKey(display: key.display, space: SpaceID(rawValue: 55)), displays: displays) == nil) + } + + @Test func menuReportsExplainTheActualFailureWithoutLeakingIdentifiers() { + #expect( + EngineShellServices.menuFailure(reports: [.noFocusedWindow]).message + == "Focus a window on this display first.") + #expect( + EngineShellServices.menuFailure(reports: [.noActiveWorkspace]).message + == "This desktop is no longer active. Reopen the menu and try again.") + #expect( + EngineShellServices.menuFailure(reports: [.unavailableDisplay(DisplayID(rawValue: "private-uuid"))]).message + == "This display is no longer connected. Reopen the menu on a connected display.") + #expect( + EngineShellServices.menuFailure(reports: [.unsupported]).message + == "The menu action could not finish. Reopen the menu and try again.") + } + + @Test func highlightsArePersistedByTheAppSinkAndFailuresReachCallers() async throws { + let services = EngineShellServices() + await #expect(throws: AppFailure.self) { try await services.send(.toggleBorders) } + var calls = 0 + services.toggleBorders = { calls += 1 } + try await services.send(.toggleBorders) + #expect(calls == 1) + services.toggleBorders = { throw AppFailure(message: "write refused") } + await #expect(throws: AppFailure.self) { try await services.send(.toggleBorders) } + } +} diff --git a/Tests/ParcelE2ETests/MenuAppTests.swift b/Tests/ParcelE2ETests/MenuAppTests.swift deleted file mode 100644 index ffe03ed1..00000000 --- a/Tests/ParcelE2ETests/MenuAppTests.swift +++ /dev/null @@ -1,48 +0,0 @@ -import Foundation -import ParcelConfig -import ParcelCore -import ParcelUI -import Testing - -@testable import ParcelApp -@testable import ParcelEngine - -@MainActor -struct MenuAppTests { - @Test func shellSnapshotUsesAddressedSpaceAndItsModes() throws { - let first = DisplayID(rawValue: "first") - let second = DisplayID(rawValue: "second") - let space = SpaceID(rawValue: 8) - let key = WorkspaceKey(display: second, space: space) - var state = State( - displays: [ - Display(id: first, frame: Rect(width: 1440, height: 900)), - Display(id: second, frame: Rect(x: 1440, y: 0, width: 1440, height: 900)), - ], activeSpaces: [first: SpaceID(rawValue: 2), second: space], activeDisplay: first) - state.workspaces[key] = Workspace(key: key, layout: .rows, ratio: .twoThirds, windowCap: 2) - state.focusModes = [key: FocusModes(noPeek: true, cleanSpace: true)] - let services = EngineShellServices() - let snapshot = try #require(services.menuSnapshot(EngineSnapshot(revision: 1, state: state), in: key)) - #expect(snapshot.layout == .rows) - #expect(snapshot.windowCap == 2) - #expect(snapshot.ratio == 2.0 / 3) - #expect(snapshot.noPeek && snapshot.cleanSpace) - #expect( - services.menuSnapshot( - EngineSnapshot(revision: 1, state: state), - in: WorkspaceKey(display: second, space: SpaceID(rawValue: 99))) == nil) - state.displays[second] = nil - #expect(services.menuSnapshot(EngineSnapshot(revision: 2, state: state), in: key) == nil) - } - - @Test func bordersArePersistedByTheAppSinkAndFailuresReachCallers() async throws { - let services = EngineShellServices() - await #expect(throws: AppFailure.self) { try await services.send(.toggleBorders) } - var calls = 0 - services.toggleBorders = { calls += 1 } - try await services.send(.toggleBorders) - #expect(calls == 1) - services.toggleBorders = { throw AppFailure(message: "write refused") } - await #expect(throws: AppFailure.self) { try await services.send(.toggleBorders) } - } -} diff --git a/Tests/ParcelE2ETests/MenuPanelEndToEndTests.swift b/Tests/ParcelE2ETests/MenuPanelEndToEndTests.swift index fabcb9d5..15382046 100644 --- a/Tests/ParcelE2ETests/MenuPanelEndToEndTests.swift +++ b/Tests/ParcelE2ETests/MenuPanelEndToEndTests.swift @@ -1,9 +1,10 @@ +import AppKit import Foundation import ParcelCore import Testing extension RealAppEndToEndTests { - @Test func menuCountTwoRetilesFixtureThroughTheMenuAction() async throws { + @Test func pointerOpenedMenuCountTwoRetilesFixtureThroughTheMenuAction() async throws { try await withSession { session in let (fixture, _) = try await session.addFixture(arguments: [ "--windows", "3", "--title", "Menu Count Fixture", @@ -12,24 +13,7 @@ extension RealAppEndToEndTests { let before = try await session.settledWindows(for: fixture, count: 3) let workspace = try await session.workspace(for: before) let usable = try E2EScreenGeometry.visibleFrame(displayID: workspace.id.display) - let x = usable.minX + 20 - let y = usable.minY + 20 - let width = usable.size.width - 40 - let height = usable.size.height - 40 - let expected: [Rect] - if usable.size.height > usable.size.width { - let first = ((height - 12) / 2).rounded() - expected = [ - Rect(x: x, y: y, width: width, height: first), - Rect(x: x, y: y + first + 12, width: width, height: height - first - 12), - ] - } else { - let first = ((width - 12) / 2).rounded() - expected = [ - Rect(x: x, y: y, width: first, height: height), - Rect(x: x + first + 12, y: y, width: width - first - 12, height: height), - ] - } + let expected = menuTwoTileFrames(in: usable) try await session.command("e2e-menu", workspace.id.display, "2") try await waitUntil("menu count two arranges two fixture tiles") { let windows = try await session.windows(for: fixture) @@ -41,4 +25,78 @@ extension RealAppEndToEndTests { } } } + + @Test func pointerOpenedMenuChangesOnlyItsDisplayWhileAnotherDisplayIsFocused() async throws { + guard NSScreen.screens.count >= 2 else { + try FileHandle.standardError.write( + contentsOf: Data("Skipped multi-display menu e2e: connect a second display.\n".utf8)) + return + } + let otherScreen = NSScreen.screens[1] + let otherBounds = E2EScreenGeometry.windowServerFrame( + otherScreen.visibleFrame, mainDisplayHeight: CGDisplayBounds(CGMainDisplayID()).height) + try await withSession { session in + let (target, _) = try await session.addFixture(arguments: [ + "--windows", "3", "--title", "Pointer Target Fixture", + ]) + let (other, ready) = try await session.addFixture(arguments: [ + "--windows", "3", "--title", "Focused Display Fixture", + ]) + for window in ready.windows { + _ = try await other.control( + FixtureControl( + action: "frame", window: window.index, + x: otherBounds.minX + 80 + Double(window.index * 10), y: otherBounds.minY + 80, + width: 360, height: 240)) + } + try await session.startApp() + let targetWindows = try await session.settledWindows(for: target, count: 3) + let otherWindows = try await session.settledWindows(for: other, count: 3) + let targetWorkspace = try await session.workspace(for: targetWindows) + let otherWorkspace = try await session.workspace(for: otherWindows) + #expect(targetWorkspace.id.display != otherWorkspace.id.display) + let focused = try #require(ready.windows.first) + _ = try await other.control(FixtureControl(action: "focus", window: focused.index)) + try await waitUntil("other display owns the focused fixture window") { + try await session.windows(for: other).contains { $0.id == UInt32(focused.number) && $0.focused } + } + let unchangedFrames = try session.frames(for: other) + let expected = try menuTwoTileFrames( + in: E2EScreenGeometry.visibleFrame(displayID: targetWorkspace.id.display)) + try await session.command("e2e-menu", targetWorkspace.id.display, "2") + try await waitUntil("real pointer activation changes only the clicked workspace") { + let windows = try await session.windows(for: target) + let workspace = try await session.workspace(for: windows) + let frames = try session.frames(for: target) + return workspace.tiles?.tileCount == 2 && frames.count == 3 + && expected.allSatisfy { expected in frames.values.contains { framesMatch($0, expected) } } + && frames.values.allSatisfy { actual in expected.contains { framesMatch(actual, $0) } } + } + #expect(try session.frames(for: other) == unchangedFrames) + let afterOther = try await session.workspace(for: session.windows(for: other)) + #expect(afterOther.layout == otherWorkspace.layout) + #expect(afterOther.tiles == otherWorkspace.tiles) + #expect(afterOther.windows == otherWorkspace.windows) + #expect(try await session.windows(for: other).contains { $0.id == UInt32(focused.number) && $0.focused }) + } + } +} + +private func menuTwoTileFrames(in usable: Rect) -> [Rect] { + let x = usable.minX + 20 + let y = usable.minY + 20 + let width = usable.size.width - 40 + let height = usable.size.height - 40 + if usable.size.height > usable.size.width { + let first = ((height - 12) / 2).rounded() + return [ + Rect(x: x, y: y, width: width, height: first), + Rect(x: x, y: y + first + 12, width: width, height: height - first - 12), + ] + } + let first = ((width - 12) / 2).rounded() + return [ + Rect(x: x, y: y, width: first, height: height), + Rect(x: x + first + 12, y: y, width: width - first - 12, height: height), + ] } diff --git a/Tests/ParcelUITests/MenuWorkspaceTests.swift b/Tests/ParcelUITests/MenuWorkspaceTests.swift index c5488257..122ff652 100644 --- a/Tests/ParcelUITests/MenuWorkspaceTests.swift +++ b/Tests/ParcelUITests/MenuWorkspaceTests.swift @@ -11,6 +11,8 @@ struct MenuWorkspaceTests { let left = DisplayID(rawValue: "left") let right = DisplayID(rawValue: "right") + init() { _ = NSApplication.shared } + @Test func pointerUsesPhysicalScreenIncludingMenuBarAndExactSpace() { let state = State( displays: [ @@ -22,16 +24,39 @@ struct MenuWorkspaceTests { ] #expect( MenuWorkspace.target(at: CGPoint(x: 1400, y: 740), screens: screens, state: state) - == WorkspaceKey(display: right, space: SpaceID(rawValue: 8))) - #expect(MenuWorkspace.target(at: CGPoint(x: 1000, y: 740), screens: screens, state: state)?.display == right) - #expect(MenuWorkspace.target(at: CGPoint(x: -1, y: 0), screens: screens, state: state) == nil) - #expect(MenuWorkspace.target(at: CGPoint(x: Double.nan, y: 0), screens: screens, state: state) == nil) + == .success(WorkspaceKey(display: right, space: SpaceID(rawValue: 8)))) + #expect( + MenuWorkspace.target(at: CGPoint(x: 1000, y: 740), screens: screens, state: state) + == .success(WorkspaceKey(display: right, space: SpaceID(rawValue: 8)))) + #expect( + MenuWorkspace.target(at: CGPoint(x: -1, y: 0), screens: screens, state: state) == .failure(.disconnected)) + #expect( + MenuWorkspace.target(at: CGPoint(x: Double.nan, y: 0), screens: screens, state: state) + == .failure(.disconnected)) var disconnected = state disconnected.displays[right] = nil - #expect(MenuWorkspace.target(at: CGPoint(x: 1400, y: 740), screens: screens, state: disconnected) == nil) + #expect( + MenuWorkspace.target(at: CGPoint(x: 1400, y: 740), screens: screens, state: disconnected) + == .failure(.disconnected)) var unknownSpace = state unknownSpace.activeSpaces[right] = nil - #expect(MenuWorkspace.target(at: CGPoint(x: 1400, y: 740), screens: screens, state: unknownSpace) == nil) + #expect( + MenuWorkspace.target(at: CGPoint(x: 1400, y: 740), screens: screens, state: unknownSpace) + == .failure(.unmanagedSpace)) + var unmanaged = state + unmanaged.workspaces[WorkspaceKey(display: right, space: SpaceID(rawValue: 8))] = nil + #expect( + MenuWorkspace.target(at: CGPoint(x: 1400, y: 740), screens: screens, state: unmanaged) + == .failure(.unmanagedSpace)) + #expect( + MenuWorkspace.target(at: CGPoint(x: 1400, y: 750), screens: screens, state: state) + == .success(WorkspaceKey(display: right, space: SpaceID(rawValue: 8)))) + #expect( + MenuWorkspace.target(at: CGPoint(x: 1000, y: 750), screens: screens, state: state) + == .success(WorkspaceKey(display: right, space: SpaceID(rawValue: 8)))) + #expect( + MenuWorkspace.target(at: CGPoint(x: 2000, y: 750), screens: screens, state: state) + == .success(WorkspaceKey(display: right, space: SpaceID(rawValue: 8)))) } @Test func menuCapturesTargetAndUsesItsCapabilitiesAndPreviews() throws { @@ -43,8 +68,9 @@ struct MenuWorkspaceTests { let original = MenuWorkspace( key: key, snapshot: LayoutSnapshot( - layout: .rows, bounds: CGRect(x: 0, y: 0, width: 1440, height: 900), tiles: [], windowCap: 2)) - controller.workspaceAtPointer = { original } + layout: .rows, bounds: CGRect(x: 0, y: 0, width: 1440, height: 900), tiles: [], windowCap: 2), + displayName: "Studio Display", desktopNumber: 3) + controller.workspaceForActivation = { _ in .success(original) } controller.invokeInWorkspace = { targeted.append(($0, $1)) } controller.update( snapshot: .preview, configuration: .defaults, permission: .granted, reduceMotion: true, @@ -58,8 +84,12 @@ struct MenuWorkspaceTests { #expect(counts.items.allSatisfy { $0.image != nil }) let layouts = try #require(controller.menu.items.first { $0.title == "Layout" }?.submenu) #expect(layouts.items.allSatisfy { $0.image != nil }) - let moved = MenuWorkspace(key: WorkspaceKey(display: left, space: SpaceID(rawValue: 9)), snapshot: .preview) - controller.workspaceAtPointer = { moved } + #expect(controller.menu.items.contains { $0.title == "Studio Display · Desktop 3" }) + #expect(!controller.menu.items.contains { $0.title.contains("Space 8") }) + let moved = MenuWorkspace( + key: WorkspaceKey(display: left, space: SpaceID(rawValue: 9)), snapshot: .preview, + displayName: "Built-in Display") + controller.workspaceForActivation = { _ in .success(moved) } counts.performActionForItem(at: 0) #expect(targeted.count == 1) #expect(targeted.first?.0 == .setWindowCap(1)) @@ -71,7 +101,7 @@ struct MenuWorkspaceTests { var commands: [ConfigCommand] = [] let controller = try MenuBarController { commands.append($0) } defer { controller.stop() } - controller.workspaceAtPointer = { nil } + controller.workspaceForActivation = { _ in .failure(.disconnected) } controller.update( snapshot: .preview, configuration: .defaults, permission: .granted, reduceMotion: true, increaseContrast: false) @@ -88,7 +118,7 @@ struct MenuWorkspaceTests { @Test func prepermissionMenuDoesNotInventDisplayPreviews() throws { let controller = try MenuBarController { _ in Issue.record("An unavailable display must not receive commands") } defer { controller.stop() } - controller.workspaceAtPointer = { nil } + controller.workspaceForActivation = { _ in .failure(.disconnected) } controller.update( snapshot: LayoutSnapshot(layout: .grid, bounds: CGRect(x: 0, y: 0, width: 1, height: 1), tiles: []), configuration: .defaults, permission: .missing, reduceMotion: true, increaseContrast: false) @@ -107,6 +137,15 @@ struct MenuWorkspaceTests { #expect(preview.tiles.allSatisfy { $0.frame.width > 0 && $0.frame.height > 0 }) } + @Test func portraitColumnPreviewUsesAdaptedVerticalPlacement() { + let preview = MenuLayoutPreview.snapshot( + layout: .columns, count: 3, bounds: CGRect(x: 0, y: 0, width: 600, height: 1000), ratio: 0.5) + #expect(preview.tiles.count == 3) + #expect(preview.tiles.allSatisfy { $0.frame.minX == 0 && $0.frame.width == 600 }) + #expect(preview.tiles.map(\.frame.minY) == [0, 333, 667]) + #expect(preview.tiles.last?.frame.maxY == 1000) + } + @Test(arguments: [false, true]) func quickSwitchesReflectEffectiveStateAndUseConfiguredCommands(enabled: Bool) throws { var commands: [ConfigCommand] = [] @@ -130,6 +169,155 @@ struct MenuWorkspaceTests { #expect(commands == [.toggleBorders, .toggleHoverFocus, .toggleNoPeek, .toggleCleanSpace]) } + @Test func nonPointerOpenUsesStatusScreenThenActiveWorkspace() { + let state = State( + displays: [ + Display(id: left, frame: Rect(width: 1000, height: 700)), + Display(id: right, frame: Rect(x: 1000, width: 1000, height: 700)), + ], + activeSpaces: [left: SpaceID(rawValue: 2), right: SpaceID(rawValue: 8)], activeDisplay: left) + let screens = [ + left: CGRect(x: 0, y: 0, width: 1000, height: 750), right: CGRect(x: 1000, y: 0, width: 1000, height: 750), + ] + #expect( + MenuWorkspace.target(at: nil, statusDisplay: right, screens: screens, state: state) + == .success(WorkspaceKey(display: right, space: SpaceID(rawValue: 8)))) + #expect( + MenuWorkspace.target(at: nil, screens: screens, state: state) + == .success(WorkspaceKey(display: left, space: SpaceID(rawValue: 2)))) + #expect( + MenuWorkspace.target(at: nil, statusDisplay: DisplayID(rawValue: "removed"), screens: screens, state: state) + == .success(WorkspaceKey(display: left, space: SpaceID(rawValue: 2)))) + var unmanaged = state + unmanaged.workspaces[WorkspaceKey(display: right, space: SpaceID(rawValue: 8))] = nil + #expect( + MenuWorkspace.target(at: nil, statusDisplay: right, screens: screens, state: unmanaged) + == .failure(.unmanagedSpace)) + } + + @Test func providerOnlyReceivesPointerForConsumedRealClick() throws { + let controller = try MenuBarController { _ in } + defer { controller.stop() } + let window = try #require(controller.statusItem.button?.window) + let location = CGPoint(x: 4, y: 6) + let click = try #require( + NSEvent.mouseEvent( + with: .leftMouseUp, location: location, modifierFlags: [], timestamp: 0, + windowNumber: window.windowNumber, context: nil, eventNumber: 1, clickCount: 1, pressure: 0)) + var received: [MenuWorkspaceActivation] = [] + controller.workspaceForActivation = { activation in + received.append(activation) + return .failure(.disconnected) + } + controller.update( + snapshot: .preview, configuration: .defaults, permission: .granted, reduceMotion: true, + increaseContrast: false) + controller.recordPointerActivation(click) + controller.menuNeedsUpdate(controller.consumeActivationMenu()) + #expect(received.last?.pointer == window.convertPoint(toScreen: location)) + controller.menuNeedsUpdate(controller.consumeActivationMenu()) + #expect(received.count == 2) + #expect(received.last?.pointer == nil) + #expect(received.last?.statusScreen === window.screen) + } + + @Test func unmanagedSpaceExplainsWhyItsActionsAreDisabled() throws { + let controller = try MenuBarController { _ in Issue.record("Unmanaged commands must stay disabled") } + defer { controller.stop() } + controller.workspaceForActivation = { _ in .failure(.unmanagedSpace) } + controller.update( + snapshot: .preview, configuration: .defaults, permission: .granted, reduceMotion: true, + increaseContrast: false) + controller.menuNeedsUpdate(controller.menu) + #expect(controller.menu.items.first?.title == "Space not arranged") + #expect( + controller.menu.items.contains { + $0.title == "Parcel doesn’t arrange this Space (for example, a full-screen app)." + }) + #expect(!controller.menu.items.contains { $0.title == "Display unavailable" }) + let retile = try #require(controller.menu.items.first { ($0 as? CommandMenuItem)?.command == .retile }) + #expect(!retile.isEnabled) + #expect(retile.accessibilityHelp() == "Parcel doesn’t arrange this Space (for example, a full-screen app).") + } + + @Test(arguments: [false, true], [false, true]) + func modesRequireTargetFocusOnlyWhenEnabling(hasFocusedWindow: Bool, enabled: Bool) throws { + var commands: [ConfigCommand] = [] + let controller = try MenuBarController { _ in Issue.record("Workspace modes need a target") } + defer { controller.stop() } + controller.workspaceForActivation = { _ in + .success( + MenuWorkspace( + key: WorkspaceKey(display: self.right, space: SpaceID(rawValue: 8)), + snapshot: LayoutSnapshot( + layout: .grid, bounds: LayoutSnapshot.preview.bounds, tiles: [], isFocused: enabled, + noPeek: enabled, cleanSpace: enabled), + displayName: "Display 2", hasFocusedWindow: hasFocusedWindow)) + } + controller.invokeInWorkspace = { command, _ in commands.append(command) } + var configuration = ParcelConfiguration.defaults + configuration.keybindings[.toggleFocus] = try KeyChord(parsing: "cmd-f") + configuration.keybindings[.toggleNoPeek] = try KeyChord(parsing: "cmd-n") + configuration.keybindings[.toggleCleanSpace] = try KeyChord(parsing: "cmd-k") + controller.update( + snapshot: .preview, configuration: configuration, permission: .granted, reduceMotion: true, + increaseContrast: false) + controller.menuNeedsUpdate(controller.menu) + let routing = try #require((controller.menu as? CommandMenu)?.routing) + let allowed = enabled || hasFocusedWindow + for command in [ConfigCommand.toggleFocus, .toggleNoPeek, .toggleCleanSpace] { + let item = try #require( + controller.menu.items.compactMap { $0 as? CommandMenuItem }.first { $0.command == command }) + #expect(item.isEnabled == allowed) + #expect((routing.bindings[command] != nil) == allowed) + #expect(item.accessibilityHelp() == (allowed ? nil : "Focus a window on this display first.")) + item.invoke(command) + } + #expect(commands.count == (allowed ? 3 : 0)) + } + + @Test func previewCountHandlesAutomaticEmptyAndCappedLayouts() { + func snapshot(_ cap: Int?, tiles: Int) -> LayoutSnapshot { + LayoutSnapshot( + layout: .grid, bounds: LayoutSnapshot.preview.bounds, + tiles: (0.. Date: Sat, 31 Oct 2026 12:48:07 -0400 Subject: [PATCH 7/7] Make setup nonblocking and Tidy reversible --- Sources/ParcelApp/AppTourIntegration.swift | 158 ++++++---- Sources/ParcelApp/TourTidyTransaction.swift | 178 +++++++++++ .../ParcelUI/ParcelUI.docc/ControlCenter.md | 12 +- .../ParcelUI/Resources/TourSetup.xcstrings | 158 +++++++++- Sources/ParcelUI/Tour/TourSetup.swift | 72 ++++- Sources/ParcelUI/Tour/TourSetupView.swift | 39 ++- .../Tour/WindowLearningController.swift | 5 +- Tests/ParcelAppTests/TourLoginTests.swift | 62 ++++ .../TourTidyTransactionTests.swift | 290 ++++++++++++++++++ .../TourTidyEndToEndTests.swift | 108 ++++++- .../Tour/LearningLocalizationTests.swift | 38 ++- Tests/ParcelUITests/Tour/TourSetupTests.swift | 83 ++++- 12 files changed, 1101 insertions(+), 102 deletions(-) create mode 100644 Sources/ParcelApp/TourTidyTransaction.swift create mode 100644 Tests/ParcelAppTests/TourLoginTests.swift create mode 100644 Tests/ParcelAppTests/TourTidyTransactionTests.swift diff --git a/Sources/ParcelApp/AppTourIntegration.swift b/Sources/ParcelApp/AppTourIntegration.swift index e0a4740b..a9764b94 100644 --- a/Sources/ParcelApp/AppTourIntegration.swift +++ b/Sources/ParcelApp/AppTourIntegration.swift @@ -9,6 +9,8 @@ import ServiceManagement @MainActor enum AppTourIntegration { + private static var fixtureTidyFailure = false + static func actions(settings: SettingsModel, services: EngineShellServices) -> TourSetupActions { TourSetupActions( checkShortcuts: { @@ -25,16 +27,10 @@ enum AppTourIntegration { checkSystem: { try checkSystem() }, loginStatus: { try loginStatus() }, setOpenAtLogin: { enabled in - let service = SMAppService.mainApp - if enabled, service.status != .enabled { try service.register() } - if !enabled, service.status == .enabled || service.status == .requiresApproval { - try await service.unregister() - } - try await settings.setValue(.bool(enabled), for: .launchAtLogin) - try await reload(services) - let status = try loginStatus() - guard enabled ? status != .disabled : status == .disabled else { throw TourSetupFailure.applyFailed } - return status + try await applyLoginChoice( + enabled, + save: { try await settings.setValue(.bool($0), for: .launchAtLogin) }, + reload: { try await reload(services) }, status: loginStatus) }, personalization: { guard let engine = services.engine, engine.isRunning, @@ -43,7 +39,8 @@ enum AppTourIntegration { UUID(uuidString: key.display.rawValue) != nil else { throw TourSetupFailure.workspaceUnavailable } return TourPersonalization( - workspace: key, displayName: key.display.rawValue, configuration: settings.configuration, + workspace: key, displayName: try DisplayNaming.name(for: key.display, in: engine.snapshot.state), + configuration: settings.configuration, portrait: display.frame.size.height > display.frame.size.width) }, tidy: { draft in try await tidy(draft, settings: settings, services: services) }, @@ -59,6 +56,17 @@ enum AppTourIntegration { openLoginSettings: { SMAppService.openSystemSettingsLoginItems() }) } + static func applyLoginChoice( + _ enabled: Bool, save: (Bool) async throws -> Void, reload: () async throws -> Void, + status: () throws -> TourLoginStatus + ) async throws -> TourLoginStatus { + try await save(enabled) + try await reload() + let result = try status() + guard enabled ? result != .disabled : result == .disabled else { throw TourSetupFailure.applyFailed } + return result + } + static func checkSystem() throws -> TourSystemCheck { let preferences = try SystemWindowPreferences() defer { preferences.stop() } @@ -84,61 +92,83 @@ enum AppTourIntegration { } } - static func tidy(_ draft: TourPersonalization, settings: SettingsModel, services: EngineShellServices) async throws - { - guard draft.isValid, let displayID = UUID(uuidString: draft.workspace.display.rawValue), - let engine = services.engine, engine.isRunning, - engine.snapshot.state.activeSpaces[draft.workspace.display] == draft.workspace.space, - let display = engine.snapshot.state.displays[draft.workspace.display] + static func tidy( + _ draft: TourPersonalization, settings: SettingsModel, services: EngineShellServices + ) async throws -> TourTidyUndo { + let snapshot = await settings.store.snapshot + guard draft.isValid, let engine = services.engine, engine.isRunning, + let display = engine.snapshot.state.displays[draft.workspace.display], + let layout = Layout(rawValue: draft.layout.rawValue) else { throw TourSetupFailure.workspaceUnavailable } - guard try checkSystem().isClear, engine.systemWindowConflict == nil else { - throw TourSetupFailure.systemConflict + guard snapshot.loadState == .loaded || snapshot.loadState == .missingFileUsingDefaults, + snapshot.activeSource == .file(settings.store.fileURL) || snapshot.activeSource == .defaults, + engine.configuration == snapshot.activeConfiguration + else { throw TourSetupFailure.applyFailed } + try requireClearSystem(engine) + let point: EngineWorkspaceRestorePoint + do { point = try engine.captureWorkspaceRestorePoint(in: draft.workspace) } catch { + throw describe(error, state: engine.snapshot.state) } - let layoutField: SettingsLayoutField = - display.frame.size.height > display.frame.size.width ? .portraitLayout : .defaultLayout - try await settings.setValues([ - (.layout(layoutField, display: displayID), .string(draft.layout.rawValue)), - (.layout(.windowCap, display: displayID), .integer(Int64(draft.windowCount))), - (.layout(.whenFull, display: displayID), .string(draft.whenFull.rawValue)), - (.motion(.highlight), .string(draft.highlight.rawValue)), - (.motion(.highlightWidth), .float(draft.highlightWidth)), - ]) - try await reload(services) + let configuration = try TourConfigurationTransaction( + fileURL: settings.store.fileURL, source: snapshot.lastGoodDocument?.source, draft: draft, + portrait: display.frame.size.height > display.frame.size.width) + let transaction = TourTidyTransaction( + operations: .init( + saveConfiguration: { + try await Task.detached { try configuration.save() }.value + }, + reloadConfiguration: { + await settings.reload() + try await reload(services) + }, + arrange: { + try requireClearSystem(engine) + let count = + draft.windowCount == 0 + ? 0 : min(draft.windowCount, layout.capabilities(in: display.frame).maximumWindowCount) + do { + guard try await engine.perform(.setLayout(layout), in: draft.workspace).isAccepted else { + throw TourSetupFailure.tidyFailed + } + if fixtureTidyFailure { throw TourSetupFailure.tidyFailed } + guard try await engine.perform(.setWindowCap(count), in: draft.workspace).isAccepted else { + throw TourSetupFailure.tidyFailed + } + services.setPaused(false) + guard try await engine.perform(.retile, in: draft.workspace).isAccepted else { + throw TourSetupFailure.tidyFailed + } + try await engine.awaitWorkspaceSettled(in: draft.workspace) + } catch { throw describe(error, state: engine.snapshot.state) } + }, + restoreConfiguration: { + try await Task.detached { try configuration.restore() }.value + }, + restoreWorkspace: { + defer { services.setPaused(point.isPaused) } + do { try await engine.restoreWorkspace(point) } catch { + throw describe(error, state: engine.snapshot.state) + } + })) + return try await transaction.run() + } + + private static func requireClearSystem(_ engine: ParcelEngine) throws { guard try checkSystem().isClear, engine.systemWindowConflict == nil else { throw TourSetupFailure.systemConflict } - guard let layout = Layout(rawValue: draft.layout.rawValue) else { throw TourSetupFailure.invalidDraft } - let count = - draft.windowCount == 0 - ? Int.max : min(draft.windowCount, layout.capabilities(in: display.frame).maximumWindowCount) - for command in [Command.setLayout(layout), .setWindowCap(count)] { - guard try await engine.perform(command, in: draft.workspace).isAccepted else { - throw TourSetupFailure.tidyFailed - } - } - services.setPaused(false) - guard try await engine.perform(.retile, in: draft.workspace).isAccepted else { - throw TourSetupFailure.tidyFailed - } - let deadline = ContinuousClock.now + .seconds(15) - while ContinuousClock.now < deadline { - try Task.checkCancellation() - guard engine.isRunning, !engine.isPaused, engine.systemWindowConflict == nil, - engine.snapshot.state.activeSpaces[draft.workspace.display] == draft.workspace.space, - let workspace = engine.snapshot.state.workspaces[draft.workspace] - else { throw TourSetupFailure.workspaceUnavailable } - let state = engine.snapshot.state - if workspace.visibleWindows.allSatisfy({ id in - guard let target = state.frames[id], let actual = state.observedFrames[id] else { return false } - return abs(target.minX - actual.minX) < 2 && abs(target.minY - actual.minY) < 2 - && abs(target.size.width - actual.size.width) < 2 - && abs(target.size.height - actual.size.height) < 2 - }) { - return - } - try await Task.sleep(for: .milliseconds(50)) + } + + static func describe(_ error: any Error, state: State) -> any Error { + guard let failure = error as? EngineWorkspaceFailure else { return error } + switch failure { + case .workspaceUnavailable: return TourSetupFailure.workspaceUnavailable + case .systemConflict: return TourSetupFailure.systemConflict + case .busy: return TourSetupFailure.busy + case .paused: return TourSetupFailure.tidyFailed + case .unsettled(let windows): + return TourSetupFailure.unsettledWindows(windows, titles: state.windows.mapValues(\.title)) } - throw TourSetupFailure.tidyFailed } static func fixtureAction(_ arguments: [String], controller: WindowLearningController) async throws -> JSONValue { @@ -149,6 +179,8 @@ enum AppTourIntegration { setup.begin(.keyboard) try await setup.checkCurrentStep() case "next" where arguments.count == 1: try await setup.next() + case "continue-anyway" where arguments.count == 1: try await setup.continueAnyway() + case "skip-tidy" where arguments.count == 1: try setup.continueWithoutTidying() case "draft" where arguments.count == 6: guard var draft = setup.draft, let layout = ConfigLayout(rawValue: arguments[1]), let count = Int(arguments[2]), @@ -162,6 +194,12 @@ enum AppTourIntegration { draft.whenFull = overflow try setup.updateDraft(draft) case "tidy" where arguments.count == 1: try await setup.tidyWorkspace() + case "tidy-fail-after-layout" where arguments.count == 1: + guard !setup.isBusy else { throw TourSetupFailure.busy } + fixtureTidyFailure = true + defer { fixtureTidyFailure = false } + try await setup.tidyWorkspace() + case "undo-tidy" where arguments.count == 1: try await setup.undoTidy() default: throw TourSetupFailure.notReady } return .object(["accepted": .bool(true), "step": .string(setup.step.rawValue)]) diff --git a/Sources/ParcelApp/TourTidyTransaction.swift b/Sources/ParcelApp/TourTidyTransaction.swift new file mode 100644 index 00000000..3313e84f --- /dev/null +++ b/Sources/ParcelApp/TourTidyTransaction.swift @@ -0,0 +1,178 @@ +import Foundation +import ParcelConfig +import ParcelUI + +@MainActor +final class TourTidyTransaction { + struct Operations { + let saveConfiguration: @MainActor () async throws -> Void + let reloadConfiguration: @MainActor () async throws -> Void + let arrange: @MainActor () async throws -> Void + let restoreConfiguration: @MainActor () async throws -> Void + let restoreWorkspace: @MainActor () async throws -> Void + } + + private let operations: Operations + private var configurationRestored = false + private var workspaceRestored = false + private var isBusy = false + + init(operations: Operations) { self.operations = operations } + + func run() async throws -> TourTidyUndo { + guard !isBusy else { throw TourSetupFailure.busy } + try Task.checkCancellation() + isBusy = true + defer { isBusy = false } + do { + try await operations.saveConfiguration() + try await operations.reloadConfiguration() + try Task.checkCancellation() + try await operations.arrange() + try Task.checkCancellation() + } catch { + let original = error + // Recovery must run even when the tour action was cancelled. + do { try await Task { @MainActor in try await self.restore() }.value } catch { + throw TourSetupFailure.restorationFailed( + operation: original.localizedDescription, restoration: error.localizedDescription) + } + throw original + } + return TourTidyUndo { [self] in + guard !isBusy else { throw TourSetupFailure.busy } + isBusy = true + defer { isBusy = false } + try await Task { @MainActor in try await self.restore() }.value + } + } + + private func restore() async throws { + var failures: [String] = [] + if !configurationRestored { + do { + try await operations.restoreConfiguration() + try await operations.reloadConfiguration() + configurationRestored = true + } catch { failures.append(error.localizedDescription) } + } + if !workspaceRestored { + do { + try await operations.restoreWorkspace() + workspaceRestored = true + } catch { failures.append(error.localizedDescription) } + } + if !failures.isEmpty { + throw TourSetupFailure.restorationIncomplete(failures.joined(separator: "\n")) + } + } +} + +struct TourConfigurationTransaction: Sendable { + let fileURL: URL + let target: URL + let original: Data? + let saved: Data + + init(fileURL: URL, source: String?, draft: TourPersonalization, portrait: Bool) throws { + guard fileURL.isFileURL, draft.isValid, + let display = UUID(uuidString: draft.workspace.display.rawValue) + else { throw TourSetupFailure.invalidDraft } + self.fileURL = fileURL + target = fileURL.resolvingSymlinksInPath() + original = source.map { Data($0.utf8) } + var document = try TOMLDocument(parsing: source ?? "") + try Self.validate(document) + let displayKey: String + if case .table(let entries) = document.node(forKey: ["layout", "displays"])?.value, + let existing = entries.keys.first(where: { UUID(uuidString: $0) == display }) + { + displayKey = existing + } else { + displayKey = display.uuidString + } + let layout = ["layout", "displays", displayKey] + for (path, value) in [ + (layout + [portrait ? "portrait-layout" : "default"], TOMLValue.string(draft.layout.rawValue)), + (layout + ["window-cap"], .integer(Int64(draft.windowCount))), + (layout + ["when-full"], .string(draft.whenFull.rawValue)), + (["motion", "highlight"], .string(draft.highlight.rawValue)), + (["motion", SettingsMotionField.highlightWidth.rawValue], .float(draft.highlightWidth)), + ] { + try document.setValue(value, forKey: path) + } + try Self.validate(document) + saved = Data(document.source.utf8) + } + + func save() throws { try replace(expected: original, replacement: saved) } + + func restore() throws { + // Once a file was loaded, deleting it intentionally retains the last good configuration. + try replace(expected: saved, replacement: original ?? Data(), allowAlreadyRestored: true) + } + + private static func validate(_ document: TOMLDocument) throws { + let result = ConfigValidator.validate(document) + guard result.configuration != nil, !result.diagnostics.contains(where: { $0.severity == .error }) else { + throw TourSetupFailure.applyFailed + } + } + + private func replace(expected: Data?, replacement: Data, allowAlreadyRestored: Bool = false) throws { + guard fileURL.resolvingSymlinksInPath() == target else { throw TourSetupFailure.configurationChanged } + try FileManager.default.createDirectory( + at: target.deletingLastPathComponent(), withIntermediateDirectories: true) + var coordinationError: NSError? + var result: Result? + NSFileCoordinator().coordinate(writingItemAt: target, options: .forReplacing, error: &coordinationError) { + url in + result = Result { + let current = try Self.contents(at: url) + if allowAlreadyRestored, current == replacement || (original == nil && current == nil) { return } + guard current == expected, fileURL.resolvingSymlinksInPath() == target else { + throw TourSetupFailure.configurationChanged + } + if current == nil { + try Self.create(replacement, at: url) + } else if current != replacement { + try replacement.write(to: url, options: .atomic) + } + } + } + if let coordinationError { throw coordinationError } + guard let result else { throw TourSetupFailure.applyFailed } + try result.get() + } + + private static func contents(at url: URL) throws -> Data? { + do { + guard try url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true else { + throw TourSetupFailure.applyFailed + } + return try Data(contentsOf: url) + } catch let error as CocoaError where error.code == .fileReadNoSuchFile { + return nil + } + } + + private static func create(_ data: Data, at url: URL) throws { + let temporary = url.deletingLastPathComponent().appendingPathComponent(".parcel-tour-\(UUID().uuidString).tmp") + do { + try data.write(to: temporary, options: .withoutOverwriting) + try FileManager.default.linkItem(at: temporary, to: url) + } catch { + let original = error + do { + if FileManager.default.fileExists(atPath: temporary.path) { + try FileManager.default.removeItem(at: temporary) + } + } catch { + throw TourSetupFailure.restorationFailed( + operation: original.localizedDescription, restoration: error.localizedDescription) + } + throw original + } + try FileManager.default.removeItem(at: temporary) + } +} diff --git a/Sources/ParcelUI/ParcelUI.docc/ControlCenter.md b/Sources/ParcelUI/ParcelUI.docc/ControlCenter.md index 4db2702c..b7542418 100644 --- a/Sources/ParcelUI/ParcelUI.docc/ControlCenter.md +++ b/Sources/ParcelUI/ParcelUI.docc/ControlCenter.md @@ -1,13 +1,15 @@ # Menu and setup -The menu captures the display under the pointer and its current native Space when it opens. Layout, count, size, Retile, and mode actions keep that target. A disconnected display or changed Space is rejected; no other screen is substituted. Window actions still address the focused window. +A mouse click targets the display under the pointer. Keyboard and VoiceOver opens target the status item’s screen, or the active workspace if that screen is unknown. Layout, count, size, Retile, and mode actions keep that target. A disconnected display or changed desktop is rejected; no other screen is substituted. Window actions still address the focused window. -Layout and count choices include miniature previews. Unavailable counts explain the layout’s limit. Borders writes `motion.highlight`; the Hover Focus switch appears only when its runtime supplies a state. Secure Input and update actions use the existing feedback and update services. +Layout and count choices include miniature previews. Unavailable counts explain the layout’s limit. Window Highlights writes `motion.highlight` and remembers the last enabled style during the session; the Hover Focus switch appears only when its runtime supplies a state. Secure Input and update actions use the existing feedback and update services. -The setup tour checks shortcuts and macOS window settings, offers open at login, and keeps layout, count, highlight, and overflow choices in a draft. **Tidy My Workspace** saves that draft and arranges the captured workspace. Layout choices become defaults for other Spaces on that display too; highlights are global. The keyboard/mouse learning tour remains available afterward. What’s New is available from both app menus. +The setup tour checks shortcuts and macOS window settings, offers open at login, and keeps preferences in a draft. Warnings offer **Continue anyway**, and learning does not require Tidy. **Tidy My Workspace** saves the draft and arranges the captured workspace, accepting app-clamped frames verified by the engine. Failure restores the prior configuration and arrangement; success offers **Undo Tidy**. External config edits are never overwritten during recovery. If no config file existed, rollback leaves an empty file containing the original defaults. Layout choices become defaults for other desktops on that display too; highlights and pause are global. What’s New is available from both app menus. -Highlights use `motion.highlight = "none" | "active" | "all" | "glow"` and `motion.highlight-width = 2…6`. The old `focus_border` key remains readable; an explicit highlight style takes precedence. Content is cut out of the highlight layer, and accessibility settings disable translucent glow. +Highlights use `motion.highlight = "none" | "active" | "all" | "glow"` and `motion.highlight-width = 2…6`. An explicit highlight style takes precedence over the legacy `focus-border` switch. Content is cut out of the highlight layer, and accessibility settings disable translucent glow. + +Multiword motion keys use dashes: `focus-border`, `menu-bar-icon`, `drop-hints`, `experimental-dimming`, and `highlight-width`. Underscore spellings remain readable as deprecated aliases with a warning. If both spellings are present, the dashed key wins, but both values must be valid. Settings writes dashed keys and preserves existing aliases and comments. When window controls supply their own Hover Focus item, leave `LayoutSnapshot.hoverFocus` nil to avoid duplicate switches. -`MenuWorkspace`, `MenuBarController.workspaceAtPointer`, and `invokeInWorkspace` connect the UI to the engine. `Event.workspaceCommandIssued` and `ParcelEngine.perform(_:in:)` validate the target when executing, without changing keyboard focus. +`MenuWorkspace`, `MenuBarController.workspaceForActivation`, and `invokeInWorkspace` connect the UI to the engine. `Event.workspaceCommandIssued` and `ParcelEngine.perform(_:in:)` carry an explicit target without changing keyboard focus. Tidy uses `captureWorkspaceRestorePoint(in:)`, `awaitWorkspaceSettled(in:timeout:)`, and `restoreWorkspace(_:)`; these validate the display and desktop throughout the operation. diff --git a/Sources/ParcelUI/Resources/TourSetup.xcstrings b/Sources/ParcelUI/Resources/TourSetup.xcstrings index 1f105b63..291b0eb9 100644 --- a/Sources/ParcelUI/Resources/TourSetup.xcstrings +++ b/Sources/ParcelUI/Resources/TourSetup.xcstrings @@ -1,12 +1,12 @@ { "sourceLanguage": "en", "strings": { - "%@ points": { + "%@ Restoring your previous setup also failed: %@. Review Settings and your windows before trying again.": { "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "%@ points" + "value": "%@ Restoring your previous setup also failed: %@. Review Settings and your windows before trying again." } } } @@ -31,22 +31,54 @@ } } }, - "A place for everything.": { + "%g points": { "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "A place for everything." + "value": "%g points" } } } }, - "All tidied up.": { + "%lld points": { "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "All tidied up." + "value": "%#@points@" + }, + "substitutions": { + "points": { + "argNum": 1, + "formatSpecifier": "lld", + "variations": { + "plural": { + "one": { + "stringUnit": { + "state": "translated", + "value": "%lld point" + } + }, + "other": { + "stringUnit": { + "state": "translated", + "value": "%lld points" + } + } + } + } + } + } + } + } + }, + "A place for everything.": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "A place for everything." } } } @@ -131,6 +163,26 @@ } } }, + "Continue anyway": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Continue anyway" + } + } + } + }, + "Continue without tidying": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Continue without tidying" + } + } + } + }, "Float in the middle": { "localizations": { "en": { @@ -181,6 +233,16 @@ } } }, + "Keep learning.": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Keep learning." + } + } + } + }, "Layout": { "localizations": { "en": { @@ -321,12 +383,12 @@ } } }, - "Ready? Save your choices and arrange the windows on your selected screen. Paused tiling will resume.": { + "Ready? Save your choices and arrange the windows on your selected screen. Paused tiling will resume on all screens.": { "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Ready? Save your choices and arrange the windows on your selected screen. Paused tiling will resume." + "value": "Ready? Save your choices and arrange the windows on your selected screen. Paused tiling will resume on all screens." } } } @@ -401,6 +463,16 @@ } } }, + "The configuration changed after Tidy started. Your newer edits were not overwritten. Review Settings before trying again.": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The configuration changed after Tidy started. Your newer edits were not overwritten. Review Settings before trying again." + } + } + } + }, "The layout may use fewer tiles when a screen or window needs more room.": { "localizations": { "en": { @@ -431,6 +503,16 @@ } } }, + "These windows could not settle: %@. Review Parcel’s notice, then try again.": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "These windows could not settle: %@. Review Parcel’s notice, then try again." + } + } + } + }, "Tidy My Workspace": { "localizations": { "en": { @@ -451,6 +533,16 @@ } } }, + "Try a few things with your own windows. You can return to setup whenever you’re ready.": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Try a few things with your own windows. You can return to setup whenever you’re ready." + } + } + } + }, "Try an alternative: %@": { "localizations": { "en": { @@ -481,6 +573,26 @@ } } }, + "Undo Tidy": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Undo Tidy" + } + } + } + }, + "Undo restores your previous settings, window arrangement, and paused state.": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Undo restores your previous settings, window arrangement, and paused state." + } + } + } + }, "Unlimited": { "localizations": { "en": { @@ -511,6 +623,16 @@ } } }, + "Window %lld": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Window %lld" + } + } + } + }, "Windows per screen": { "localizations": { "en": { @@ -541,6 +663,16 @@ } } }, + "You can continue learning without changing these settings. Tidy stays unavailable until both checks are verified off.": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "You can continue learning without changing these settings. Tidy stays unavailable until both checks are verified off." + } + } + } + }, "Your choices could not be applied. Review the configuration in Settings.": { "localizations": { "en": { @@ -551,6 +683,16 @@ } } }, + "Your previous setup could not be fully restored: %@. Review Settings and your windows before trying again.": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Your previous setup could not be fully restored: %@. Review Settings and your windows before trying again." + } + } + } + }, "Your workspace is ready. Next, try a few things with your own windows.": { "localizations": { "en": { diff --git a/Sources/ParcelUI/Tour/TourSetup.swift b/Sources/ParcelUI/Tour/TourSetup.swift index 5efdb1c8..76f27ec0 100644 --- a/Sources/ParcelUI/Tour/TourSetup.swift +++ b/Sources/ParcelUI/Tour/TourSetup.swift @@ -72,6 +72,13 @@ public struct TourPersonalization: Equatable, Sendable { } } +@MainActor +public struct TourTidyUndo { + public let restore: () async throws -> Void + + public init(restore: @escaping () async throws -> Void) { self.restore = restore } +} + @MainActor public struct TourSetupActions { public var checkShortcuts: () async throws -> TourShortcutCheck @@ -79,7 +86,7 @@ public struct TourSetupActions { public var loginStatus: () throws -> TourLoginStatus public var setOpenAtLogin: (Bool) async throws -> TourLoginStatus public var personalization: () throws -> TourPersonalization - public var tidy: (TourPersonalization) async throws -> Void + public var tidy: (TourPersonalization) async throws -> TourTidyUndo public var openShortcuts: () throws -> Void public var openSystemSettings: () throws -> Void public var openLoginSettings: () throws -> Void @@ -90,7 +97,7 @@ public struct TourSetupActions { loginStatus: @escaping () throws -> TourLoginStatus, setOpenAtLogin: @escaping (Bool) async throws -> TourLoginStatus, personalization: @escaping () throws -> TourPersonalization, - tidy: @escaping (TourPersonalization) async throws -> Void, + tidy: @escaping (TourPersonalization) async throws -> TourTidyUndo, openShortcuts: @escaping () throws -> Void, openSystemSettings: @escaping () throws -> Void, openLoginSettings: @escaping () throws -> Void @@ -118,6 +125,10 @@ public final class TourSetupController { public private(set) var draft: TourPersonalization? public private(set) var isBusy = false public private(set) var errorMessage: String? + public private(set) var didTidy = false + private var undo: TourTidyUndo? + public var canUndoTidy: Bool { undo != nil && !isBusy } + public var needsSystemAcknowledgment: Bool { step == .system && system?.isClear != true } @ObservationIgnored public var actions: TourSetupActions? public init() {} @@ -192,6 +203,28 @@ public final class TourSetupController { } } + public func continueAnyway() async throws { + guard step == .system, !isBusy, needsSystemAcknowledgment else { throw TourSetupFailure.notReady } + step = .login + try await checkCurrentStep() + } + + public func continueWithoutTidying() throws { + guard !isBusy, step != .complete else { throw TourSetupFailure.notReady } + didTidy = false + errorMessage = nil + step = .complete + } + + public func undoTidy() async throws { + guard let undo else { throw TourSetupFailure.notReady } + try await perform { + try await undo.restore() + self.undo = nil + didTidy = false + } + } + public func next() async throws { guard canContinue, let index = TourSetupStep.allCases.firstIndex(of: step) else { throw TourSetupFailure.notReady @@ -218,7 +251,8 @@ public final class TourSetupController { let actions = try requireActions() system = try await actions.checkSystem() guard system?.isClear == true else { throw TourSetupFailure.systemConflict } - try await actions.tidy(draft) + undo = try await actions.tidy(draft) + didTidy = true step = .complete } } @@ -256,6 +290,10 @@ public final class TourSetupController { public enum TourSetupFailure: LocalizedError { case unavailable, notReady, invalidDraft, busy, systemConflict, workspaceUnavailable, applyFailed, tidyFailed + case configurationChanged + case unsettledWindows([WindowID], titles: [WindowID: String]) + case restorationFailed(operation: String, restoration: String) + case restorationIncomplete(String) public var errorDescription: String? { switch self { @@ -268,11 +306,39 @@ public enum TourSetupFailure: LocalizedError { 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.") + case .configurationChanged: + TourText.text( + "The configuration changed after Tidy started. Your newer edits were not overwritten. Review Settings before trying again." + ) + case .unsettledWindows(let windows, let titles): + String( + format: TourText.text("These windows could not settle: %@. Review Parcel’s notice, then try again."), + windows.map { id in + if let title = titles[id], !title.isEmpty { return title } + return String.localizedStringWithFormat(TourText.text("Window %lld"), Int64(id.rawValue)) + }.formatted(.list(type: .and))) + case .restorationIncomplete(let reason): + String( + format: TourText.text( + "Your previous setup could not be fully restored: %@. Review Settings and your windows before trying again." + ), 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." + ), operation, restoration) } } } enum TourText { + static func points(_ width: Double) -> String { + if width.rounded() == width, let integer = Int(exactly: width) { + return String.localizedStringWithFormat(text("%lld points"), integer) + } + return String.localizedStringWithFormat(text("%g points"), width) + } + static func text(_ key: String) -> String { Bundle.module.localizedString(forKey: key, value: nil, table: "TourSetup") } diff --git a/Sources/ParcelUI/Tour/TourSetupView.swift b/Sources/ParcelUI/Tour/TourSetupView.swift index e7bc4ce8..44506d50 100644 --- a/Sources/ParcelUI/Tour/TourSetupView.swift +++ b/Sources/ParcelUI/Tour/TourSetupView.swift @@ -15,9 +15,18 @@ struct TourSetupView: View { case .personalize: personalization case .tidy: tidy case .complete: - Text(TourText.text("Your workspace is ready. Next, try a few things with your own windows.")) + Text( + TourText.text( + setup.didTidy + ? "Your workspace is ready. Next, try a few things with your own windows." + : "Try a few things with your own windows. You can return to setup whenever you’re ready.")) + if setup.canUndoTidy { + Button(TourText.text("Undo Tidy")) { controller.runSetup { try await setup.undoTidy() } } + .accessibilityIdentifier("tour.undoTidy") + Text(TourText.text("Undo restores your previous settings, window arrangement, and paused state.")) + .font(.caption) + } Button(TourText.text("Try the hands-on tour")) { controller.finishSetup() } - .disabled(!controller.active) Text(TourText.text("Parcel’s menu bar icon is always there for layouts, settings, and another tour.")) } if setup.isBusy { @@ -31,11 +40,28 @@ struct TourSetupView: View { if setup.step != .shortcuts && setup.step != .complete { Button(TourText.text("Back")) { controller.runSetup { try await setup.back() } } } - if setup.step != .tidy && setup.step != .complete { + if setup.needsSystemAcknowledgment { + Text( + TourText.text( + "You can continue learning without changing these settings. Tidy stays unavailable until both checks are verified off." + ) + ) + .font(.callout) + Button(TourText.text("Continue anyway")) { + controller.runSetup { try await setup.continueAnyway() } + } + .accessibilityIdentifier("tour.continueAnyway") + } else if setup.step != .tidy && setup.step != .complete { Button(TourText.text("Continue")) { controller.runSetup { try await setup.next() } } .disabled(!setup.canContinue) .accessibilityIdentifier("tour.continue") } + if setup.step != .complete { + Button(TourText.text("Continue without tidying")) { + controller.changeSetup { try setup.continueWithoutTidying() } + } + .accessibilityIdentifier("tour.skipTidy") + } } .disabled(setup.isBusy) } @@ -143,7 +169,8 @@ struct TourSetupView: View { Text(TourText.text("Highlight width")) Slider(value: binding(\.highlightWidth, fallback: draft.highlightWidth), in: 2...6, step: 1) .accessibilityLabel(TourText.text("Highlight width")) - Text(String(format: TourText.text("%@ points"), draft.highlightWidth.formatted())) + .accessibilityValue(TourText.points(draft.highlightWidth)) + Text(TourText.points(draft.highlightWidth)) } Picker(TourText.text("When this Space is full"), selection: binding(\.whenFull, fallback: draft.whenFull)) { Text(TourText.text("Stack in the active tile")).tag(ConfigWhenFull.stack) @@ -158,7 +185,7 @@ struct TourSetupView: View { VStack(alignment: .leading, spacing: 10) { Text( TourText.text( - "Ready? Save your choices and arrange the windows on your selected screen. Paused tiling will resume." + "Ready? Save your choices and arrange the windows on your selected screen. Paused tiling will resume on all screens." )) if let draft = setup.draft { Text(String(format: TourText.text("%@ · %@"), draft.displayName, draft.layout.settingsTitle)) @@ -215,7 +242,7 @@ extension TourSetupStep { case .login: "Ready when you are." case .personalize: "Make it yours." case .tidy: "A place for everything." - case .complete: "All tidied up." + case .complete: "Keep learning." } } } diff --git a/Sources/ParcelUI/Tour/WindowLearningController.swift b/Sources/ParcelUI/Tour/WindowLearningController.swift index 7848dd3c..f91331fc 100644 --- a/Sources/ParcelUI/Tour/WindowLearningController.swift +++ b/Sources/ParcelUI/Tour/WindowLearningController.swift @@ -16,10 +16,11 @@ public final class WindowLearningController { } public func finishSetup() { - guard setup.step == .complete else { return } + guard setup.step == .complete, !setup.isBusy else { return } let track = setup.track setup.dismiss() - begin(track) + tour.start(track: track, state: state, configuration: configuration) + persist() } func runSetup(_ operation: @escaping @MainActor () async throws -> Void) { diff --git a/Tests/ParcelAppTests/TourLoginTests.swift b/Tests/ParcelAppTests/TourLoginTests.swift new file mode 100644 index 00000000..dbe05cd8 --- /dev/null +++ b/Tests/ParcelAppTests/TourLoginTests.swift @@ -0,0 +1,62 @@ +import ParcelUI +import Testing + +@testable import ParcelApp + +@Suite @MainActor +struct TourLoginTests { + @Test(arguments: [TourLoginStatus.enabled, .requiresApproval]) + func enablingLoginUsesOnlyTheSettingsReloadOwner(_ status: TourLoginStatus) async throws { + var calls: [String] = [] + let result = try await AppTourIntegration.applyLoginChoice( + true, + save: { enabled in + #expect(enabled) + calls.append("save") + }, + reload: { calls.append("reload") }, + status: { + calls.append("read-status") + return status + }) + #expect(result == status) + #expect(calls == ["save", "reload", "read-status"]) + } + + @Test func failedSaveDoesNotRegisterOrReloadLoginItem() async { + var reloads = 0 + var reads = 0 + await #expect(throws: TourSetupFailure.self) { + _ = try await AppTourIntegration.applyLoginChoice( + true, save: { _ in throw TourSetupFailure.applyFailed }, + reload: { reloads += 1 }, + status: { + reads += 1 + return .enabled + }) + } + #expect(reloads == 0) + #expect(reads == 0) + } + + @Test func reloadFailureAndStatusMismatchAreSurfaced() async { + await #expect(throws: TourSetupFailure.self) { + _ = try await AppTourIntegration.applyLoginChoice( + true, save: { _ in }, reload: { throw TourSetupFailure.applyFailed }, status: { .enabled }) + } + for (enabled, status) in [(true, TourLoginStatus.disabled), (false, .enabled), (false, .requiresApproval)] { + await #expect(throws: TourSetupFailure.self) { + _ = try await AppTourIntegration.applyLoginChoice( + enabled, save: { _ in }, reload: {}, status: { status }) + } + } + } + + @Test func disablingReadsBackDisabledAfterSaving() async throws { + var saved: Bool? + let result = try await AppTourIntegration.applyLoginChoice( + false, save: { saved = $0 }, reload: {}, status: { .disabled }) + #expect(saved == false) + #expect(result == .disabled) + } +} diff --git a/Tests/ParcelAppTests/TourTidyTransactionTests.swift b/Tests/ParcelAppTests/TourTidyTransactionTests.swift new file mode 100644 index 00000000..6831377a --- /dev/null +++ b/Tests/ParcelAppTests/TourTidyTransactionTests.swift @@ -0,0 +1,290 @@ +import Foundation +import ParcelConfig +import ParcelCore +import ParcelEngine +import ParcelUI +import Testing + +@testable import ParcelApp + +@Suite @MainActor +struct TourTidyTransactionTests { + @Test func successfulTidySavesDraftAndUndoRestoresConfigurationAndEngine() async throws { + let fixture = try TourTransactionFixture() + defer { fixture.remove() } + let undo = try await fixture.transaction.run() + let saved = try fixture.loadedConfiguration() + let display = try #require(UUID(uuidString: fixture.draft.workspace.display.rawValue)) + #expect(saved.layout.values(for: display).defaultLayout == .rows) + #expect(saved.layout.values(for: display).windowCap == 2) + #expect(saved.layout.values(for: display).whenFull == .stack) + #expect(saved.motion.highlight == .none) + #expect(saved.motion.highlightWidth == 4) + #expect(fixture.engine.layout == .rows) + #expect(!fixture.engine.paused) + #expect(fixture.calls == ["save", "reload", "arrange"]) + try await undo.restore() + #expect(try String(contentsOf: fixture.url, encoding: .utf8) == fixture.original) + #expect(fixture.engine == fixture.previousEngine) + #expect(fixture.calls.suffix(3) == ["restore-config", "reload", "restore-engine"]) + let calls = fixture.calls + try await undo.restore() + #expect(fixture.calls == calls) + } + + @Test(arguments: TourFailurePoint.allCases) + private func failureAtEveryStageRollsBackSavedChoicesAndPartialArrangement(_ point: TourFailurePoint) async throws { + let fixture = try TourTransactionFixture() + defer { fixture.remove() } + fixture.failurePoint = point + await #expect(throws: TourTestFailure.self) { _ = try await fixture.transaction.run() } + #expect(try String(contentsOf: fixture.url, encoding: .utf8) == fixture.original) + #expect(fixture.engine == fixture.previousEngine) + #expect(fixture.calls.suffix(3) == ["restore-config", "reload", "restore-engine"]) + #expect(fixture.reloads >= 1) + } + + @Test func cancellationStillRestoresConfigurationAndEngineOutsideCancelledTask() async throws { + let fixture = try TourTransactionFixture() + defer { fixture.remove() } + let (stream, continuation) = AsyncStream.makeStream() + fixture.onArrange = { + continuation.yield(()) + try await Task.sleep(for: .seconds(60)) + } + let task = Task { try await fixture.transaction.run() } + var iterator = stream.makeAsyncIterator() + _ = await iterator.next() + task.cancel() + await #expect(throws: CancellationError.self) { _ = try await task.value } + continuation.finish() + #expect(try String(contentsOf: fixture.url, encoding: .utf8) == fixture.original) + #expect(fixture.engine == fixture.previousEngine) + #expect(!fixture.restorationWasCancelled) + } + + @Test func externalEditIsNotOverwrittenAndEngineRecoveryStillRuns() async throws { + let fixture = try TourTransactionFixture() + defer { fixture.remove() } + let external = "[layout]\ndefault = \"bsp\"\n" + fixture.onArrange = { + try Data(external.utf8).write(to: fixture.url, options: .atomic) + throw TourTestFailure.injected("layout failed") + } + do { + _ = try await fixture.transaction.run() + Issue.record("Expected failed arrangement and protected external edit") + } catch { + #expect(error.localizedDescription.contains("layout failed")) + #expect(error.localizedDescription.contains("newer edits were not overwritten")) + } + #expect(try String(contentsOf: fixture.url, encoding: .utf8) == external) + #expect(fixture.engine == fixture.previousEngine) + } + + @Test func failedUndoRetainsSuccessfulRecoveryStagesForRetry() async throws { + let fixture = try TourTransactionFixture() + defer { fixture.remove() } + let undo = try await fixture.transaction.run() + fixture.failRestoreEngine = true + await #expect(throws: TourSetupFailure.self) { try await undo.restore() } + #expect(try String(contentsOf: fixture.url, encoding: .utf8) == fixture.original) + #expect(fixture.engine != fixture.previousEngine) + fixture.failRestoreEngine = false + try await undo.restore() + #expect(fixture.engine == fixture.previousEngine) + #expect(fixture.calls.filter { $0 == "restore-config" }.count == 1) + #expect(fixture.calls.filter { $0 == "restore-engine" }.count == 2) + } + + @Test func rollbackReportsBothConfigurationAndEngineFailures() async throws { + let fixture = try TourTransactionFixture() + defer { fixture.remove() } + fixture.failurePoint = .settle + fixture.failRestoreEngine = true + fixture.failRestoreConfiguration = true + do { + _ = try await fixture.transaction.run() + Issue.record("Expected recovery failures") + } catch { + #expect(error.localizedDescription.contains("settle")) + #expect(error.localizedDescription.contains("config restore failed")) + #expect(error.localizedDescription.contains("engine restore failed")) + } + } + + @Test func firstTimeFailureLeavesAnEmptyValidFileSoReloadActuallyRestoresDefaults() async throws { + let fixture = try TourTransactionFixture(source: nil) + defer { fixture.remove() } + let store = ConfigStore(fileURL: fixture.url) + #expect(await store.reload().activeConfiguration == .defaults) + fixture.onReload = { _ = await store.reload() } + fixture.failurePoint = .layout + await #expect(throws: TourTestFailure.self) { _ = try await fixture.transaction.run() } + #expect(try Data(contentsOf: fixture.url).isEmpty) + let restored = await store.reload() + #expect(restored.loadState == .loaded) + #expect(restored.activeConfiguration == .defaults) + } + + @Test func cancellationBeforeSaveDoesNotCreateAnAbsentFile() async throws { + let fixture = try TourTransactionFixture(source: nil) + defer { fixture.remove() } + let task = Task { try await fixture.transaction.run() } + task.cancel() + await #expect(throws: CancellationError.self) { _ = try await task.value } + #expect(!FileManager.default.fileExists(atPath: fixture.url.path)) + #expect(fixture.engine == fixture.previousEngine) + } + + @Test func portraitChangesRespectExistingDisplayKeyCasingAndRestoreComments() throws { + let fixture = try TourTransactionFixture() + defer { fixture.remove() } + let key = fixture.draft.workspace.display.rawValue.lowercased() + let source = + "# Preserve this\n[layout.displays.\"\(key)\"]\ndefault = \"columns\"\nportrait-layout = \"grid\"\n" + try Data(source.utf8).write(to: fixture.url) + let transaction = try TourConfigurationTransaction( + fileURL: fixture.url, source: source, draft: fixture.draft, portrait: true) + try transaction.save() + let saved = try String(contentsOf: fixture.url, encoding: .utf8) + #expect(saved.contains(key)) + #expect(saved.contains("# Preserve this")) + let configuration = try fixture.loadedConfiguration() + let display = try #require(UUID(uuidString: key)) + #expect(configuration.layout.values(for: display).defaultLayout == .columns) + #expect(configuration.layout.values(for: display).portraitLayout == .rows) + try transaction.restore() + #expect(try String(contentsOf: fixture.url, encoding: .utf8) == source) + } + + @Test func staleSourceAndSymlinkRetargetingRefuseToOverwriteNewerFiles() throws { + let fixture = try TourTransactionFixture() + defer { fixture.remove() } + let transaction = try TourConfigurationTransaction( + fileURL: fixture.url, source: fixture.original, draft: fixture.draft, portrait: false) + let external = "# User changed this\n" + try Data(external.utf8).write(to: fixture.url) + #expect(throws: TourSetupFailure.self) { try transaction.save() } + #expect(try String(contentsOf: fixture.url, encoding: .utf8) == external) + let link = fixture.directory.appendingPathComponent("link.toml") + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: fixture.url) + let linked = try TourConfigurationTransaction( + fileURL: link, source: external, draft: fixture.draft, portrait: false) + try FileManager.default.removeItem(at: link) + let other = fixture.directory.appendingPathComponent("other.toml") + try Data(external.utf8).write(to: other) + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: other) + #expect(throws: TourSetupFailure.self) { try linked.save() } + #expect(try String(contentsOf: other, encoding: .utf8) == external) + } + + @Test func engineSettleFailureNamesOnlyAffectedWindows() { + let known = WindowID(rawValue: 1) + let unnamed = WindowID(rawValue: 2) + var state = State() + state.windows[known] = ManagedWindow( + id: known, app: AppID(pid: 10, bundleID: "test.terminal"), title: "Small Terminal") + let error = AppTourIntegration.describe(EngineWorkspaceFailure.unsettled([known, unnamed]), state: state) + #expect(error.localizedDescription.contains("Small Terminal")) + #expect(error.localizedDescription.contains("Window 2")) + } +} + +private enum TourFailurePoint: CaseIterable, Sendable { case save, reload, layout, count, settle } +private enum TourTestFailure: LocalizedError { + case injected(String) + var errorDescription: String? { + switch self { + case .injected(let text): text + } + } +} + +@MainActor +private final class TourTransactionFixture { + struct FakeEngine: Equatable { + var layout = ConfigLayout.columns + var count = 3 + var paused = true + } + + let directory: URL + let url: URL + let original: String + let draft: TourPersonalization + let configuration: TourConfigurationTransaction + let previousEngine = FakeEngine() + var engine = FakeEngine() + var failurePoint: TourFailurePoint? + var failRestoreConfiguration = false + var failRestoreEngine = false + var calls: [String] = [] + var reloads = 0 + var restorationWasCancelled = false + var onArrange: (@MainActor () async throws -> Void)? + var onReload: (@MainActor () async -> Void)? + + init(source: String? = "version = 1\n# Keep this note\n[layout]\ndefault = \"columns\"\nwindow-cap = 3\n") throws { + directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + url = directory.appendingPathComponent("config.toml") + original = source ?? "" + if let source { try Data(source.utf8).write(to: url) } + var draft = TourPersonalization( + workspace: WorkspaceKey(display: DisplayID(rawValue: UUID().uuidString), space: SpaceID(rawValue: 1)), + displayName: "Desk", configuration: .defaults, portrait: false) + draft.layout = .rows + draft.windowCount = 2 + draft.highlight = .none + draft.highlightWidth = 4 + draft.whenFull = .stack + self.draft = draft + configuration = try TourConfigurationTransaction(fileURL: url, source: source, draft: draft, portrait: false) + } + + lazy var transaction = TourTidyTransaction( + operations: .init( + saveConfiguration: { [unowned self] in + calls.append("save") + if failurePoint == .save { throw TourTestFailure.injected("save") } + try configuration.save() + }, + reloadConfiguration: { [unowned self] in + calls.append("reload") + reloads += 1 + if failurePoint == .reload, reloads == 1 { throw TourTestFailure.injected("reload") } + await onReload?() + }, + arrange: { [unowned self] in + calls.append("arrange") + engine.layout = .rows + if failurePoint == .layout { throw TourTestFailure.injected("layout") } + engine.count = 2 + if failurePoint == .count { throw TourTestFailure.injected("count") } + engine.paused = false + if failurePoint == .settle { throw TourTestFailure.injected("settle") } + try await onArrange?() + }, + restoreConfiguration: { [unowned self] in + calls.append("restore-config") + restorationWasCancelled = restorationWasCancelled || Task.isCancelled + if failRestoreConfiguration { throw TourTestFailure.injected("config restore failed") } + try configuration.restore() + }, + restoreWorkspace: { [unowned self] in + calls.append("restore-engine") + restorationWasCancelled = restorationWasCancelled || Task.isCancelled + if failRestoreEngine { throw TourTestFailure.injected("engine restore failed") } + engine = previousEngine + })) + + func loadedConfiguration() throws -> ParcelConfiguration { + let document = try TOMLDocument(parsing: String(contentsOf: url, encoding: .utf8)) + return try #require(ConfigValidator.validate(document).configuration) + } + + func remove() { + do { try FileManager.default.removeItem(at: directory) } catch { Issue.record(error) } + } +} diff --git a/Tests/ParcelE2ETests/TourTidyEndToEndTests.swift b/Tests/ParcelE2ETests/TourTidyEndToEndTests.swift index 697e35a5..6c0326ee 100644 --- a/Tests/ParcelE2ETests/TourTidyEndToEndTests.swift +++ b/Tests/ParcelE2ETests/TourTidyEndToEndTests.swift @@ -1,4 +1,6 @@ +import AppKit import Foundation +import ParcelConfig import ParcelCore import Testing @@ -9,6 +11,7 @@ extension RealAppEndToEndTests { try await session.startApp() let windows = try await session.settledWindows(for: fixture, count: 3) let before = try session.frames(for: fixture) + let originalWorkspace = try await session.workspace(for: windows) let originalConfiguration = try Data(contentsOf: session.configURL) try await session.command("pause") try await session.command("e2e-tour", "begin") @@ -29,19 +32,27 @@ extension RealAppEndToEndTests { #expect(workspace.windows.count == 3) #expect(workspace.tiles?.stacks.count == 2) #expect(Set(after.map(\.id)) == Set(windows.map(\.id))) - let displays: [AppDisplay] = try await session.query("displays") - let display = try #require(displays.first { $0.id == workspace.id.display }) - let outer = session.configuration.outerGap - let inner = session.configuration.innerGap - let width = display.frame.size.width - 2 * outer - let availableHeight = display.frame.size.height - 2 * outer - inner - let firstHeight = floor(availableHeight / 2) + let usable = try E2EScreenGeometry.visibleFrame(displayID: workspace.id.display) + let width = usable.size.width - 40 + let availableHeight = usable.size.height - 40 - 12 + let firstHeight = (availableHeight / 2).rounded() let expected = [ - Rect(x: display.frame.minX + outer, y: display.frame.minY + outer, width: width, height: firstHeight), + Rect(x: usable.minX + 20, y: usable.minY + 20, width: width, height: firstHeight), Rect( - x: display.frame.minX + outer, y: display.frame.minY + outer + firstHeight + inner, + x: usable.minX + 20, y: usable.minY + 20 + firstHeight + 12, width: width, height: availableHeight - firstHeight), ] + let document = try TOMLDocument(parsing: String(contentsOf: session.configURL, encoding: .utf8)) + let displayKey = try #require(UUID(uuidString: workspace.id.display)).uuidString + let layoutPath = ["layout", "displays", displayKey] + #expect( + document.node( + forKey: layoutPath + [usable.size.height > usable.size.width ? "portrait-layout" : "default"])? + .value == .string("rows")) + #expect(document.node(forKey: layoutPath + ["window-cap"])?.value == .integer(2)) + #expect(document.node(forKey: layoutPath + ["when-full"])?.value == .string("stack")) + #expect(document.node(forKey: ["motion", "highlight"])?.value == .string("none")) + #expect(document.node(forKey: ["motion", "highlight-width"])?.value == .float(4)) let actual = try session.frames(for: fixture) for frame in actual.values { #expect(expected.contains { framesMatch(frame, $0) }) @@ -52,6 +63,85 @@ extension RealAppEndToEndTests { #expect(actual != before) let resumed: AppConfig = try await session.query("config") #expect(!resumed.paused) + + try await session.command("e2e-tour", "undo-tidy") + let restored = try await session.settledWindows(for: fixture, count: 3) + let restoredWorkspace = try await session.workspace(for: restored) + #expect(restoredWorkspace.layout == originalWorkspace.layout) + #expect(restoredWorkspace.tiles == originalWorkspace.tiles) + #expect(try Data(contentsOf: session.configURL) == originalConfiguration) + let restoredFrames = try session.frames(for: fixture) + #expect(restoredFrames.count == before.count) + for (id, frame) in before { #expect(restoredFrames[id].map { framesMatch($0, frame) } == true) } + let pausedAgain: AppConfig = try await session.query("config") + #expect(pausedAgain.paused) + } + } + + @Test func tourTidyAcceptsLearnedClampingWithoutWaitingForImpossibleSlots() async throws { + let screen = try #require(NSScreen.screens.first) + let minimumHeight = Int((screen.visibleFrame.height * 0.6).rounded(.down)) + var configuration = E2EConfiguration() + configuration.windowCap = 1 + try await withSession(configuration: configuration) { session in + let (fixture, _) = try await session.addFixture(arguments: [ + "--windows", "2", "--title", "Tour Clamp Fixture", "--clamp-size", "200x\(minimumHeight)", + ]) + try await session.startApp() + _ = try await session.settledWindows(for: fixture, count: 2) + try await session.command("e2e-tour", "begin") + for _ in 0..<3 { try await session.command("e2e-tour", "next") } + try await session.command("e2e-tour", "draft", "rows", "2", "none", "4", "stack") + try await session.command("e2e-tour", "next") + let deadline = E2EDeadline("tour accepts learned clamp", timeout: .seconds(5)) + try await session.command("e2e-tour", "tidy") + _ = try deadline.remaining() + let windows = try await session.windows(for: fixture) + #expect(windows.contains { $0.minimum?.size.height == Double(minimumHeight) }) + let baseline = try await fixture.snapshot() + #expect(baseline.windows.contains { $0.clampedWrites > 0 }) + try await remainTrue("tour clamp does not keep rewriting", duration: .milliseconds(300)) { + let current = try await fixture.snapshot() + return current.windows.map(\.frameWrites) == baseline.windows.map(\.frameWrites) + } + } + } + + @Test(arguments: [false, true]) + func tourFailureAfterChangingLayoutRollsBackConfigWindowsAndPause(paused: Bool) async throws { + try await withSession { session in + let (fixture, _) = try await session.addFixture(arguments: [ + "--windows", "3", "--title", "Rollback Fixture", + ]) + try await session.startApp() + let windows = try await session.settledWindows(for: fixture, count: 3) + let workspace = try await session.workspace(for: windows) + let frames = try session.frames(for: fixture) + let configuration = try Data(contentsOf: session.configURL) + if paused { try await session.command("pause") } + try await session.command("e2e-tour", "begin") + for _ in 0..<3 { try await session.command("e2e-tour", "next") } + let differentLayout = workspace.layout == .rows ? "columns" : "rows" + try await session.command("e2e-tour", "draft", differentLayout, "2", "none", "4", "stack") + try await session.command("e2e-tour", "next") + await #expect(throws: E2EError.self) { + try await session.command("e2e-tour", "tidy-fail-after-layout") + } + let restored = try await session.settledWindows(for: fixture, count: 3) + let restoredWorkspace = try await session.workspace(for: restored) + #expect(restoredWorkspace.layout == workspace.layout) + #expect(restoredWorkspace.tiles == workspace.tiles) + #expect(try Data(contentsOf: session.configURL) == configuration) + let restoredFrames = try session.frames(for: fixture) + #expect(restoredFrames.count == frames.count) + for (id, frame) in frames { #expect(restoredFrames[id].map { framesMatch($0, frame) } == true) } + let restoredConfig: AppConfig = try await session.query("config") + #expect(restoredConfig.paused == paused) + + try await session.command("e2e-tour", "tidy") + let retried: AppConfig = try await session.query("config") + #expect(!retried.paused) + #expect(try Data(contentsOf: session.configURL) != configuration) } } } diff --git a/Tests/ParcelUITests/Tour/LearningLocalizationTests.swift b/Tests/ParcelUITests/Tour/LearningLocalizationTests.swift index 5c0818f2..de56dd26 100644 --- a/Tests/ParcelUITests/Tour/LearningLocalizationTests.swift +++ b/Tests/ParcelUITests/Tour/LearningLocalizationTests.swift @@ -12,14 +12,13 @@ struct LearningLocalizationTests { let runtime = try PropertyListDecoder().decode([String: String].self, from: Data(contentsOf: runtimeURL)) let pluralURL = try #require( Bundle.module.url(forResource: "UI", withExtension: "stringsdict", subdirectory: "en.lproj")) - let plurals = - try PropertyListSerialization.propertyList(from: Data(contentsOf: pluralURL), format: nil) as? [String: Any] + let plurals = try PropertyListDecoder().decode([String: CompiledPlural].self, from: Data(contentsOf: pluralURL)) for (key, entry) in catalog.strings { let english = try #require(entry.localizations["en"]) if english.substitutions == nil { #expect(runtime[key] == english.stringUnit?.value, "Missing compiled key: \(key)") } else { - #expect(plurals?[key] != nil, "Missing compiled plural: \(key)") + #expect(plurals[key] != nil, "Missing compiled plural: \(key)") } } } @@ -31,9 +30,33 @@ struct LearningLocalizationTests { Bundle.module.url(forResource: table, withExtension: "strings", subdirectory: "en.lproj")) let runtime = try PropertyListDecoder().decode([String: String].self, from: Data(contentsOf: runtimeURL)) for (key, entry) in catalog.strings { - let value = try #require(entry.localizations["en"]?.stringUnit?.value) + let english = try #require(entry.localizations["en"]) + let value = try #require(english.stringUnit?.value) #expect(!value.isEmpty) - #expect(runtime[key] == value) + if let substitutions = english.substitutions { + let url = try #require( + Bundle.module.url(forResource: table, withExtension: "stringsdict", subdirectory: "en.lproj")) + let plurals = try PropertyListDecoder().decode( + [String: CompiledPlural].self, from: Data(contentsOf: url)) + let expected = normalizedPluralFormat(value, arguments: substitutions.mapValues(\.argNum)) + #expect(plurals[key]?.format == expected) + } else { + #expect(runtime[key] == value) + } + } + } + + @Test func pluralFormatNormalizationKeepsArgumentPositions() { + #expect(normalizedPluralFormat("%#@points@", arguments: ["points": 1]) == "%1$#@points@") + #expect( + normalizedPluralFormat("%1$@ layout, %#@windows@", arguments: ["windows": 2]) + == "%1$@ layout, %2$#@windows@") + #expect(normalizedPluralFormat("%2$#@points@", arguments: ["points": 1]) == "%2$#@points@") + } + + private func normalizedPluralFormat(_ value: String, arguments: [String: Int]) -> String { + arguments.reduce(value) { format, argument in + format.replacingOccurrences(of: "%#@\(argument.key)@", with: "%\(argument.value)$#@\(argument.key)@") } } @@ -247,6 +270,11 @@ private func normalizeInterpolations(_ argument: String, integers: Set) } private enum CatalogScanError: Error, Equatable { case invalidRange, unclosedCall, unclosedInterpolation } +private struct CompiledPlural: Decodable { + let format: String + enum CodingKeys: String, CodingKey { case format = "NSStringLocalizedFormatKey" } +} + private struct Catalog: Decodable { struct Entry: Decodable { struct Localization: Decodable { diff --git a/Tests/ParcelUITests/Tour/TourSetupTests.swift b/Tests/ParcelUITests/Tour/TourSetupTests.swift index 3708c2cc..90d05694 100644 --- a/Tests/ParcelUITests/Tour/TourSetupTests.swift +++ b/Tests/ParcelUITests/Tour/TourSetupTests.swift @@ -40,7 +40,7 @@ struct TourSetupTests { #expect(fixture.tidied == [draft]) } - @Test func systemSettingsMustBeVerifiedAndDisabled() async throws { + @Test func systemWarningsRequireExplicitAcknowledgmentButNeverAuthorizeTidy() async throws { for check in [ TourSystemCheck(stageManager: true, nativeTiling: false), TourSystemCheck(stageManager: false, nativeTiling: true), @@ -55,12 +55,79 @@ struct TourSetupTests { #expect(fixture.controller.step == .system) #expect(!fixture.controller.canContinue) await #expect(throws: TourSetupFailure.self) { try await fixture.controller.next() } - fixture.system = .init(stageManager: false, nativeTiling: false) - try await fixture.controller.checkCurrentStep() - #expect(fixture.controller.canContinue) + #expect(fixture.controller.needsSystemAcknowledgment) + try await fixture.controller.continueAnyway() + #expect(fixture.controller.step == .login) + #expect(fixture.controller.system == check) + try await fixture.controller.next() + try await fixture.controller.next() + await #expect(throws: TourSetupFailure.self) { try await fixture.controller.tidyWorkspace() } + #expect(fixture.tidied.isEmpty) + try fixture.controller.continueWithoutTidying() + #expect(fixture.controller.step == .complete) + #expect(!fixture.controller.didTidy) + #expect(!fixture.controller.canUndoTidy) } } + @Test func failedSystemCheckCanBeAcknowledgedWithoutPretendingSuccess() async throws { + let fixture = TourSetupFixture() + fixture.controller.begin(.keyboard) + try await fixture.controller.checkCurrentStep() + fixture.failSystem = true + await #expect(throws: TourSetupFailure.self) { try await fixture.controller.next() } + #expect(fixture.controller.system == nil) + #expect(fixture.controller.needsSystemAcknowledgment) + #expect(fixture.controller.errorMessage != nil) + try await fixture.controller.continueAnyway() + #expect(fixture.controller.step == .login) + #expect(fixture.controller.system == nil) + } + + @Test func undoIsExplicitAndRetryableAndOnlyConsumedAfterSuccess() async throws { + let fixture = TourSetupFixture() + fixture.controller.begin(.keyboard) + try await fixture.reachPersonalization() + try await fixture.controller.next() + await #expect(throws: TourSetupFailure.self) { try await fixture.controller.undoTidy() } + try await fixture.controller.tidyWorkspace() + #expect(fixture.controller.didTidy) + #expect(fixture.controller.canUndoTidy) + #expect(fixture.undoCount == 0) + fixture.failUndo = true + await #expect(throws: TourSetupFailure.self) { try await fixture.controller.undoTidy() } + #expect(fixture.controller.canUndoTidy) + #expect(fixture.controller.errorMessage != nil) + fixture.failUndo = false + try await fixture.controller.undoTidy() + #expect(fixture.undoCount == 1) + #expect(!fixture.controller.canUndoTidy) + #expect(!fixture.controller.didTidy) + #expect(fixture.controller.errorMessage == nil) + } + + @Test func learningIsReachableWithoutTidyEvenWhilePaused() throws { + let suite = "tour-skip-tests.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let learning = try WindowLearningController(defaults: defaults, onFailure: { Issue.record($0) }) + defer { learning.stop() } + learning.setup.begin(.keyboard) + #expect(!learning.active) + try learning.setup.continueWithoutTidying() + learning.finishSetup() + #expect(!learning.setup.isPresented) + #expect(learning.tour.progress.phase == .running) + #expect(learning.tour.progress.track == .keyboard) + } + + @Test func widthValueUsesPointsWithSingularPluralAndFractionalValues() { + #expect(TourText.points(1) == "1 point") + #expect(TourText.points(2) == "2 points") + #expect(TourText.points(6) == "6 points") + #expect(TourText.points(2.5) == "2.5 points") + } + @Test func systemPreferenceUnknownsNeverBecomeSuccess() { let snapshot = SystemWindowPreferencesSnapshot( stageManagerGloballyEnabled: .disabled, edgeDragTilingEnabled: .disabled, @@ -235,6 +302,9 @@ struct TourSetupTests { var failChecks = false var failLogin = false var failTidy = false + var failUndo = false + var undoCount = 0 + var failSystem = false init() { controller.actions = TourSetupActions( @@ -244,6 +314,7 @@ struct TourSetupTests { }, checkSystem: { [unowned self] in systemChecks += 1 + if failSystem { throw TourSetupFailure.unavailable } return system }, loginStatus: { .disabled }, @@ -261,6 +332,10 @@ struct TourSetupTests { tidy: { [unowned self] draft in if failTidy { throw TourSetupFailure.tidyFailed } tidied.append(draft) + return TourTidyUndo { [unowned self] in + if failUndo { throw TourSetupFailure.applyFailed } + undoCount += 1 + } }, openShortcuts: {}, openSystemSettings: {}, openLoginSettings: {}) } -- knotmirror 0.0.1