From 1d194f39b7f7cd85ec2006608719229be278a6f1 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 10:57:26 -0400 Subject: [PATCH 1/6] Count only writes caused by each retile --- Sources/ParcelCore/Reducer.swift | 37 +++- Tests/ParcelCoreTests/RoomFeedbackTests.swift | 184 ++++++++++++++++++ .../ParcelEngineTests/ParcelEngineTests.swift | 4 +- 3 files changed, 219 insertions(+), 6 deletions(-) diff --git a/Sources/ParcelCore/Reducer.swift b/Sources/ParcelCore/Reducer.swift index 53feb5a0..69b22571 100644 --- a/Sources/ParcelCore/Reducer.swift +++ b/Sources/ParcelCore/Reducer.swift @@ -3,12 +3,16 @@ public func reduce(_ state: State, _ event: Event) -> (State, [Effect]) { return (next, effects.first ?? []) } -/// Applies observations in order, then computes one layout. Effects retain their event index. +/// Applies observations in order and emits one coalesced layout. Effects retain their event index. public func reduce(_ state: State, _ events: [Event]) -> (State, [[Effect]]) { guard !events.isEmpty else { return (state, []) } var next = state var effectsByEvent = Array(repeating: [Effect](), count: events.count) var baseline = state.frames + var feedbackFrames = events.contains(.commandIssued(.retile)) ? state.frames : nil + var feedbackLayout: LayoutResult? + var retileEvents: [Int] = [] + var retileChanges: [WindowID: (event: Int, workspace: WorkspaceKey, frame: Rect)] = [:] var accepted = false for (index, event) in events.enumerated() { var candidate = next @@ -16,6 +20,25 @@ public func reduce(_ state: State, _ events: [Event]) -> (State, [[Effect]]) { if let issue = candidate.handle(event, baseline: &candidateBaseline, effects: &effectsByEvent[index]) { effectsByEvent[index] = [.report(issue)] } else { + if let previousFrames = feedbackFrames { + let layout = candidate.layoutFrames() + retileChanges = retileChanges.filter { window, change in + layout.frames[window] == change.frame && candidate.windows[window]?.isFloating == false + && candidate.workspaces[change.workspace]?.order.contains(window) == true + } + if event == .commandIssued(.retile), let key = next.activeWorkspace, next.isActive(key), + let workspace = next.workspaces[key] + { + retileEvents.append(index) + for window in workspace.tree?.windows ?? [] { + if let frame = layout.frames[window], frame != previousFrames[window] { + retileChanges[window] = (index, key, frame) + } + } + } + feedbackFrames = previousFrames.merging(layout.frames) { _, target in target } + feedbackLayout = layout + } next = candidate baseline = candidateBaseline accepted = true @@ -24,7 +47,7 @@ public func reduce(_ state: State, _ events: [Event]) -> (State, [[Effect]]) { guard accepted else { return (state, effectsByEvent) } var effects = events.count == 1 ? effectsByEvent[0] : [] if events.count == 1 { effectsByEvent[0] = [] } - let desired = next.layoutFrames() + let desired = feedbackLayout ?? next.layoutFrames() let writes = desired.frames.keys.sorted().compactMap { window -> WindowFrame? in guard let frame = desired.frames[window], frame != baseline[window] else { return nil } return WindowFrame(window: window, frame: frame) @@ -45,8 +68,14 @@ public func reduce(_ state: State, _ events: [Event]) -> (State, [[Effect]]) { effectsByEvent[0].insert(contentsOf: effects.filter { if case .setFrames = $0 { true } else { false } }, at: 0) effectsByEvent[events.count - 1].append( contentsOf: effects.filter { if case .setFrames = $0 { false } else { true } }) - for (index, event) in events.enumerated() where event == .commandIssued(.retile) && next.activeWorkspace != nil { - effectsByEvent[index].append(.report(.retiled(moved: writes.count))) + var retileCounts: [Int: Int] = [:] + for write in writes { + if let change = retileChanges[write.window], change.frame == write.frame { + retileCounts[change.event, default: 0] += 1 + } + } + for index in retileEvents { + effectsByEvent[index].append(.report(.retiled(moved: retileCounts[index, default: 0]))) } return (next, effectsByEvent) } diff --git a/Tests/ParcelCoreTests/RoomFeedbackTests.swift b/Tests/ParcelCoreTests/RoomFeedbackTests.swift index dbffa701..d8244f2c 100644 --- a/Tests/ParcelCoreTests/RoomFeedbackTests.swift +++ b/Tests/ParcelCoreTests/RoomFeedbackTests.swift @@ -268,4 +268,188 @@ struct RoomFeedbackTests { #expect(resolve(before, action: .useWindowCap(2)).0 == before) #expect(resolve(before, action: .moveToDisplay(destinationDisplay)).0 == before) } + + private func unbalancedForRetile(_ state: State, workspace key: WorkspaceKey = primaryKey) throws -> State { + var state = state + let tree = try #require(state.workspaces[key]?.tree) + state.workspaces[key]?.tree = try #require(tree.replacingFraction(at: [], with: 0.75)) + return reduce(state, .relayout).0 + } + + private func retileCounts(_ effects: [Effect]) -> [Int] { + effects.compactMap { effect in + if case .report(.retiled(let count)) = effect { return count } + return nil + } + } + + @Test(arguments: [false, true]) + func retileCountsOnlyChangedFramesInItsWorkspace(primaryChanged: Bool) { + var before = withDestination(populated()) + let expectedFrames = before.frames + let displaced = Rect(x: 10, y: 20, width: 100, height: 100) + before.observedFrames[windowID(1)] = displaced + before.frames[windowID(10)] = displaced + if primaryChanged { before.frames[windowID(2)] = displaced } + + let (after, effects) = command(.retile, in: before) + + #expect(after.frames == expectedFrames) + #expect(frameWrites(effects).map(\.window) == (primaryChanged ? [windowID(2), windowID(10)] : [windowID(10)])) + #expect(retileCounts(effects) == [primaryChanged ? 1 : 0]) + } + + @Test(arguments: [false, true]) + func retileDoesNotClaimAnEarlierOrLaterLayoutCommand(retileFirst: Bool) { + let events: [Event] = + retileFirst + ? [.commandIssued(.retile), .commandIssued(.setLayout(.rows))] + : [.commandIssued(.setLayout(.rows)), .commandIssued(.retile)] + let (after, effects) = reduce(populated(2), events) + + #expect(after.workspaces[primaryKey]?.layout == .rows) + #expect(frameWrites(effects[0]).count == 2) + #expect(frameWrites(effects[1]).isEmpty) + #expect(retileCounts(effects[retileFirst ? 0 : 1]) == [0]) + #expect(retileCounts(effects[retileFirst ? 1 : 0]).isEmpty) + } + + @Test(arguments: [false, true]) + func retileDoesNotClaimAnEarlierOrLaterAppearance(retileFirst: Bool) { + let appearance = Event.windowAppeared( + managed(2), workspace: primaryKey, frame: Rect(width: 100, height: 100)) + let events: [Event] = + retileFirst ? [.commandIssued(.retile), appearance] : [appearance, .commandIssued(.retile)] + let (after, effects) = reduce(populated(1), events) + + #expect(after.workspaces[primaryKey]?.order == [windowID(1), windowID(2)]) + #expect(frameWrites(effects[0]).map(\.window) == [windowID(1), windowID(2)]) + #expect(frameWrites(effects[1]).isEmpty) + #expect(retileCounts(effects[retileFirst ? 0 : 1]) == [0]) + } + + @Test(arguments: [false, true]) + func retileDoesNotClaimAnEarlierOrLaterFrameObservation(retileFirst: Bool) { + let observation = Event.windowMovedByUser(windowID(1), frame: Rect(width: 100, height: 100)) + let events: [Event] = + retileFirst ? [.commandIssued(.retile), observation] : [observation, .commandIssued(.retile)] + let (_, effects) = reduce(populated(1), events) + + #expect(frameWrites(effects[0]) == [WindowFrame(window: windowID(1), frame: testScreen)]) + #expect(retileCounts(effects[retileFirst ? 0 : 1]) == [0]) + } + + @Test func retileCountsOnlyChangesThatStillNeedAWrite() throws { + let before = try unbalancedForRetile(populated()) + let target = Rect(width: 400, height: 800) + let (_, effects) = reduce( + before, + [.commandIssued(.retile), .windowMovedByUser(windowID(1), frame: target)]) + + #expect(frameWrites(effects[0]).map(\.window) == [windowID(2), windowID(3)]) + #expect(retileCounts(effects[0]) == [2]) + #expect(effects[1].isEmpty) + } + + @Test(arguments: [false, true]) + func retileLosesAttributionWhenLaterCommandsReplaceItsFrames(returnToRetileLayout: Bool) throws { + let before = try unbalancedForRetile(populated()) + var events: [Event] = [.commandIssued(.retile), .commandIssued(.setLayout(.rows))] + if returnToRetileLayout { events.append(.commandIssued(.setLayout(.columns))) } + let (_, effects) = reduce(before, events) + + #expect(frameWrites(effects[0]).count == 3) + #expect(retileCounts(effects[0]) == [0]) + #expect(effects.dropFirst().allSatisfy { frameWrites($0).isEmpty && retileCounts($0).isEmpty }) + } + + @Test func retileRepeatedInOneBatchCountsEachChangedWriteOnlyOnce() throws { + let before = try unbalancedForRetile(populated()) + let (_, effects) = reduce(before, [.commandIssued(.retile), .commandIssued(.retile)]) + + #expect(frameWrites(effects[0]).count == 3) + #expect(retileCounts(effects[0]) == [3]) + #expect(effects[1] == [.report(.retiled(moved: 0))]) + } + + @Test func retileReportsStayWithEachActedOnDisplayAfterFocusSwitches() throws { + var before = try unbalancedForRetile(withDestination(populated(), count: 2)) + before = try unbalancedForRetile(before, workspace: destinationKey) + let (after, effects) = reduce( + before, + [ + .commandIssued(.retile), .focusChanged(windowID(10)), .commandIssued(.retile), + .focusChanged(windowID(1)), + ]) + + #expect(after.activeWorkspace == primaryKey) + #expect( + frameWrites(effects[0]).map(\.window) == [ + windowID(1), windowID(2), windowID(3), windowID(10), windowID(11), + ]) + #expect(retileCounts(effects[0]) == [3]) + #expect(retileCounts(effects[2]) == [2]) + #expect(effects.dropFirst().allSatisfy { frameWrites($0).isEmpty }) + #expect(retileCounts(effects[1]).isEmpty) + #expect(retileCounts(effects[3]).isEmpty) + } + + @Test func retileDoesNotCountWritesOnTheSpaceActivatedLaterInItsBatch() throws { + var before = try unbalancedForRetile(populated()) + let otherKey = WorkspaceKey(display: primaryDisplay, space: secondarySpace) + for number in 10...11 { + before = + reduce( + before, + .windowAppeared(managed(number), workspace: otherKey, frame: Rect(width: 100, height: 100)) + ).0 + } + before.workspaces[otherKey]?.changeLayout(.rows) + let tree = try #require(before.workspaces[otherKey]?.tree) + before.workspaces[otherKey]?.tree = try #require(tree.replacingFraction(at: [], with: 0.75)) + let (after, effects) = reduce( + before, + [ + .commandIssued(.retile), .activeSpaceChanged(display: primaryDisplay, space: secondarySpace), + .commandIssued(.retile), + ]) + + #expect(after.activeWorkspace == otherKey) + #expect(frameWrites(effects[0]).map(\.window) == [windowID(10), windowID(11)]) + #expect(retileCounts(effects[0]) == [0]) + #expect(retileCounts(effects[2]) == [2]) + #expect(after.frames[windowID(1)] == before.frames[windowID(1)]) + #expect(after.frames[windowID(10)] == Rect(width: 1200, height: 400)) + } + + @Test func retileWithoutAnActiveWorkspaceCannotSucceedAfterALaterSpaceActivation() { + var before = populated(1) + before.activeSpaces = [:] + let (_, effects) = reduce( + before, + [.commandIssued(.retile), .activeSpaceChanged(display: primaryDisplay, space: primarySpace)]) + + #expect(effects[0] == [.report(.noActiveWorkspace)]) + #expect(retileCounts(effects.flatMap { $0 }).isEmpty) + } + + @Test func retileStillReportsZeroWhenItsDisplayDisconnectsBeforeTheFinalWrite() throws { + let before = try unbalancedForRetile(populated()) + let (after, effects) = reduce(before, [.commandIssued(.retile), .displaySetChanged([])]) + + #expect(after.activeWorkspace == nil) + #expect(frameWrites(effects.flatMap { $0 }).isEmpty) + #expect(retileCounts(effects[0]) == [0]) + } + + @Test func retileAttributionSurvivesRejectedEventsWithoutCreditingTheNextRetile() throws { + let before = try unbalancedForRetile(populated()) + let (_, effects) = reduce( + before, [.commandIssued(.retile), .focusChanged(windowID(99)), .commandIssued(.retile)]) + + #expect(frameWrites(effects[0]).count == 3) + #expect(retileCounts(effects[0]) == [3]) + #expect(effects[1] == [.report(.unknownWindow(windowID(99)))]) + #expect(effects[2] == [.report(.retiled(moved: 0))]) + } } diff --git a/Tests/ParcelEngineTests/ParcelEngineTests.swift b/Tests/ParcelEngineTests/ParcelEngineTests.swift index 22d769a3..ebb37a1a 100644 --- a/Tests/ParcelEngineTests/ParcelEngineTests.swift +++ b/Tests/ParcelEngineTests/ParcelEngineTests.swift @@ -189,7 +189,7 @@ final class EngineCommandBatch { @Suite("Engine commands") @MainActor struct ParcelEngineCommandTests { - @Test func asyncCommandsCoalesceAndRetainIndividualReports() async throws { + @Test func asyncCommandsCoalesceWithoutCreditingPriorLayoutChangesToRetile() async throws { let harness = try EngineHarness() try await harness.start() try harness.add([1, 2]) @@ -210,7 +210,7 @@ struct ParcelEngineCommandTests { #expect(!results[1].isAccepted) #expect(results[1].reports == [.noNeighbor(.right)]) #expect(results[2].isAccepted) - #expect(results[2].reports == [.retiled(moved: 2)]) + #expect(results[2].reports == [.retiled(moved: 0)]) #expect(harness.engine.snapshot.layouts[engineDisplay] == .rows) #expect( harness.engine.snapshot.state.frames[WindowID(rawValue: 1)] == Rect(x: 0, y: 0, width: 1200, height: 400)) -- knotmirror 0.0.1 From 169516e4770781e4c3eca01d78886173d9f829ec Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 10:58:54 -0400 Subject: [PATCH 2/6] Make retile fixture unwrapping explicit --- Tests/ParcelCoreTests/RoomFeedbackTests.swift | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Tests/ParcelCoreTests/RoomFeedbackTests.swift b/Tests/ParcelCoreTests/RoomFeedbackTests.swift index d8244f2c..791b307c 100644 --- a/Tests/ParcelCoreTests/RoomFeedbackTests.swift +++ b/Tests/ParcelCoreTests/RoomFeedbackTests.swift @@ -272,7 +272,8 @@ struct RoomFeedbackTests { private func unbalancedForRetile(_ state: State, workspace key: WorkspaceKey = primaryKey) throws -> State { var state = state let tree = try #require(state.workspaces[key]?.tree) - state.workspaces[key]?.tree = try #require(tree.replacingFraction(at: [], with: 0.75)) + let unbalanced: TileTree = try #require(tree.replacingFraction(at: [], with: 0.75)) + state.workspaces[key]?.tree = unbalanced return reduce(state, .relayout).0 } @@ -406,7 +407,8 @@ struct RoomFeedbackTests { } before.workspaces[otherKey]?.changeLayout(.rows) let tree = try #require(before.workspaces[otherKey]?.tree) - before.workspaces[otherKey]?.tree = try #require(tree.replacingFraction(at: [], with: 0.75)) + let unbalanced: TileTree = try #require(tree.replacingFraction(at: [], with: 0.75)) + before.workspaces[otherKey]?.tree = unbalanced let (after, effects) = reduce( before, [ -- knotmirror 0.0.1 From 75898c9bae15f693db1862718827140e2ff24451 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 11:00:02 -0400 Subject: [PATCH 3/6] Keep Carbon shortcuts active during Secure Input --- Sources/ParcelApp/NativeAppRuntime.swift | 65 ++++--- .../ParcelPlatform/Input/HotKeyCenter.swift | 31 ++-- Sources/ParcelPlatform/SecureInput.swift | 54 +++++- Tests/ParcelE2ETests/AppFeedbackTests.swift | 45 +++-- .../Input/SecureInputGateTests.swift | 158 +++++++++++++----- .../SecureInputTests.swift | 137 +++++++++++++++ 6 files changed, 403 insertions(+), 87 deletions(-) diff --git a/Sources/ParcelApp/NativeAppRuntime.swift b/Sources/ParcelApp/NativeAppRuntime.swift index df18758a..7c4ca2e0 100644 --- a/Sources/ParcelApp/NativeAppRuntime.swift +++ b/Sources/ParcelApp/NativeAppRuntime.swift @@ -59,6 +59,7 @@ final class NativeAppRuntime: AppRuntime { private var hotkeyMode: String? private var hotkeyGate = HotkeyDispatchGate() private var effectiveShortcuts: [ConfigCommand: KeyChord]? + private var registeredShortcutConfiguration: ParcelConfiguration? private var notice: String? private let logger = Logger(subsystem: "dev.vinnymac.parcel", category: "app") @@ -247,7 +248,7 @@ final class NativeAppRuntime: AppRuntime { if hotkeyBindings == nil { let center = HotKeyCenter( onPress: { [weak self] press in - guard let self, !self.secureInput.refresh(), !self.synchronizeMode(), + guard let self, self.permitsHotkey(press), !self.synchronizeMode(), let action = self.hotkeyBindings?.action(for: press) else { return @@ -267,7 +268,7 @@ final class NativeAppRuntime: AppRuntime { self.dispatch { defer { self.hotkeyGate.finish(action) } try Task.checkCancellation() - guard !self.secureInput.refresh(), !self.synchronizeMode(), self.hotkeyGate.allows(ticket) + guard self.permitsHotkey(press), !self.synchronizeMode(), self.hotkeyGate.allows(ticket) else { return } switch action { case .command(let command): @@ -286,7 +287,7 @@ final class NativeAppRuntime: AppRuntime { } } }, onFailure: { [weak self] error in self?.services.composition?.report(error, kind: .input) }, - isInputAllowed: { [weak self] in self?.secureInput.refresh() == false }) + isEventTapInputAllowed: { [weak self] in self?.secureInput.refresh(checkOwner: false) == false }) hotkeys = center hotkeyBindings = AppHotkeys( register: { key, repeats in _ = try center.register(key, repeats: repeats) }, @@ -296,6 +297,11 @@ final class NativeAppRuntime: AppRuntime { return refreshHotkeys(configuration, mode: services.engine?.snapshot.state.activeMode) } + private func permitsHotkey(_ press: HotKeyPress) -> Bool { + secureInput.refresh(checkOwner: false) + return hotkeys?.isAvailable(press.hotKey) == true + } + @discardableResult private func synchronizeMode() -> Bool { let mode = services.engine?.snapshot.state.activeMode @@ -312,12 +318,9 @@ final class NativeAppRuntime: AppRuntime { let result = hotkeyBindings.reload(configuration, mode: mode) hotkeyMode = mode hotkeyGate.invalidate() - let active = secureInput.isEnabled ? [:] : result.active - effectiveShortcuts = active - shell?.setEffectiveShortcuts(active) - learningConfiguration = Self.shortcutPresentation(configuration, secureInput: secureInput.isEnabled) - learningConfiguration.keybindings = active - refreshLearning() + registeredShortcutConfiguration = configuration + registeredShortcutConfiguration?.keybindings = result.active + let active = refreshShortcutPresentation() services.composition?.clearNotice(.hotkeys) if !result.conflicts.isEmpty { for conflict in result.conflicts { @@ -330,22 +333,39 @@ final class NativeAppRuntime: AppRuntime { return active } - static func shortcutPresentation(_ configuration: ParcelConfiguration, secureInput: Bool) -> ParcelConfiguration { + private func refreshShortcutPresentation() -> [ConfigCommand: KeyChord] { + guard let configuration = registeredShortcutConfiguration, let hotkeys else { + preconditionFailure("Shortcut presentation requires a registered configuration") + } + let routes = Dictionary(uniqueKeysWithValues: hotkeys.registrations.map { ($0.hotKey, $0.route) }) + learningConfiguration = Self.shortcutPresentation( + configuration, secureInput: secureInput.isEnabled, routes: routes) + let active = learningConfiguration.keybindings + effectiveShortcuts = active + shell?.setEffectiveShortcuts(active) + refreshLearning() + return active + } + + static func shortcutPresentation( + _ configuration: ParcelConfiguration, secureInput: Bool, routes: [HotKey: HotKeyRoute] = [:] + ) -> ParcelConfiguration { guard secureInput else { return configuration } - var suspended = configuration - suspended.keybindings = [:] - suspended.defaultModeEntries = [:] - suspended.modes = configuration.modes.mapValues { _ in [:] } - return suspended + func available(_ chord: KeyChord) -> Bool { + let key = hotkey(chord) + return (routes[key] ?? HotKeyRoute.preferred(for: key)) == .carbon + } + var presented = configuration + presented.keybindings = configuration.keybindings.filter { available($0.value) } + presented.defaultModeEntries = configuration.defaultModeEntries.filter { available($0.value) } + presented.modes = configuration.modes.mapValues { $0.filter { available($0.value) } } + return presented } private func secureInputChanged(_ enabled: Bool) { - hotkeyGate.invalidate() - hotkeys?.resetPressedState() - feedback?.controller.setSecureInput(enabled) - if hotkeyBindings != nil, let configuration = services.engine?.configuration { - _ = refreshHotkeys(configuration, mode: services.engine?.snapshot.state.activeMode) - } + hotkeys?.resetEventTapPressedState() + feedback?.controller.setSecureInput(enabled, ownerName: secureInput.ownerName) + if registeredShortcutConfiguration != nil { _ = refreshShortcutPresentation() } } static func minimumStore(configURL: URL, fixtureOnly: Bool) -> MinimumSizeStore { @@ -362,7 +382,7 @@ final class NativeAppRuntime: AppRuntime { onFailure: { [weak self] in self?.services.composition?.report($0, kind: .feedback) }) self.feedback = feedback settings.feedback = feedback.model - feedback.controller.setSecureInput(secureInput.isEnabled) + feedback.controller.setSecureInput(secureInput.isEnabled, ownerName: secureInput.ownerName) } private func postFixtureKey(_ request: AppFixtureKeyInput) async throws { @@ -630,6 +650,7 @@ extension NativeAppRuntime { hotkeyBindings = nil hotkeyMode = nil effectiveShortcuts = nil + registeredShortcutConfiguration = nil shell?.setEffectiveShortcuts(nil) hotkeyGate.invalidate() shell?.setActiveMode(nil) diff --git a/Sources/ParcelPlatform/Input/HotKeyCenter.swift b/Sources/ParcelPlatform/Input/HotKeyCenter.swift index fd856053..1a6b47e0 100644 --- a/Sources/ParcelPlatform/Input/HotKeyCenter.swift +++ b/Sources/ParcelPlatform/Input/HotKeyCenter.swift @@ -24,7 +24,7 @@ public final class HotKeyCenter { private let backend: any HotKeyBackend private let onPress: @MainActor (HotKeyPress) -> Void private let onFailure: @MainActor (InputError) -> Void - private let isInputAllowed: @MainActor () -> Bool + private let isEventTapInputAllowed: @MainActor () -> Bool private var bindings: [HotKey: Binding] = [:] private var carbonState = HotKeyState() private var tapState = HotKeyState() @@ -36,16 +36,17 @@ public final class HotKeyCenter { public convenience init( onPress: @escaping @MainActor (HotKeyPress) -> Void, onFailure: @escaping @MainActor (InputError) -> Void, - isInputAllowed: @escaping @MainActor () -> Bool = { true } + isEventTapInputAllowed: @escaping @MainActor () -> Bool = { true } ) { self.init( - backend: NativeHotKeyBackend(), onPress: onPress, onFailure: onFailure, isInputAllowed: isInputAllowed) + backend: NativeHotKeyBackend(), onPress: onPress, onFailure: onFailure, + isEventTapInputAllowed: isEventTapInputAllowed) } init( backend: any HotKeyBackend, onPress: @escaping @MainActor (HotKeyPress) -> Void, onFailure: @escaping @MainActor (InputError) -> Void, - isInputAllowed: @escaping @MainActor () -> Bool = { true }, + isEventTapInputAllowed: @escaping @MainActor () -> Bool = { true }, scheduleRepeat: @escaping @MainActor (@escaping @MainActor () -> Void) -> (@MainActor () -> Void) = HotKeyCenter .systemRepeat ) { @@ -53,7 +54,7 @@ public final class HotKeyCenter { self.backend = backend self.onPress = onPress self.onFailure = onFailure - self.isInputAllowed = isInputAllowed + self.isEventTapInputAllowed = isEventTapInputAllowed backend.onCarbonEvent = { [weak self] id, down in self?.carbonEvent(id: id, down: down) } backend.onTapEvent = { [weak self] type, event in self?.tapEvent(type, event) ?? false } backend.onFailure = { [weak self, onFailure] error in @@ -166,16 +167,25 @@ public final class HotKeyCenter { tapState.reset() } - private func permitsInput() -> Bool { - guard isInputAllowed() else { - resetPressedState() + public func resetEventTapPressedState() { + tapState.reset() + stopIdleTap() + } + + public func isAvailable(_ hotKey: HotKey) -> Bool { + guard let registration = bindings[hotKey]?.registration else { return false } + return registration.route == .carbon || permitsEventTapInput() + } + + private func permitsEventTapInput() -> Bool { + guard isEventTapInputAllowed() else { + resetEventTapPressedState() return false } return true } private func carbonEvent(id: UInt32, down: Bool) { - guard permitsInput() else { return } guard let binding = bindings.values.first(where: { $0.id == id }) else { return } let key = binding.registration.hotKey if down { @@ -188,7 +198,6 @@ public final class HotKeyCenter { guard let self, self.repeatGeneration == generation, self.repeats[key] != nil, self.bindings[key]?.id == id else { return } - guard self.permitsInput() else { return } guard self.backend.isPressed(key) else { self.repeats.removeValue(forKey: key)?() _ = self.carbonState.up(keyCode: key.keyCode) @@ -210,7 +219,7 @@ public final class HotKeyCenter { stopIdleTap() return false } - guard permitsInput() else { return false } + guard permitsEventTapInput() else { return false } let code = event.getIntegerValueField(.keyboardEventKeycode) guard let keyCode = UInt16(exactly: code) else { return false } if type == .keyUp { diff --git a/Sources/ParcelPlatform/SecureInput.swift b/Sources/ParcelPlatform/SecureInput.swift index 034e33d5..fcea8b61 100644 --- a/Sources/ParcelPlatform/SecureInput.swift +++ b/Sources/ParcelPlatform/SecureInput.swift @@ -1,41 +1,49 @@ import AppKit import Carbon +import IOKit @MainActor public final class SecureInputMonitor { public private(set) var isEnabled: Bool + public private(set) var ownerName: String? public var isRunning: Bool { generation != nil } private let reader: @MainActor () -> Bool + private let ownerReader: @MainActor () -> String? private let onChange: @MainActor (Bool) -> Void private let activityCenter: NotificationCenter private var observers: [any NSObjectProtocol] = [] private var generation: UUID? public convenience init(onChange: @escaping @MainActor (Bool) -> Void) { - self.init(reader: { IsSecureEventInputEnabled() }, onChange: onChange) + self.init( + reader: { IsSecureEventInputEnabled() }, ownerReader: SecureInputOwner.currentName, onChange: onChange) } /// Reads the initial state without calling onChange or starting observation. public convenience init( reader: @escaping @MainActor () -> Bool, + ownerReader: @escaping @MainActor () -> String? = { nil }, onChange: @escaping @MainActor (Bool) -> Void ) { self.init( - reader: reader, onChange: onChange, + reader: reader, ownerReader: ownerReader, onChange: onChange, activityCenter: NSWorkspace.shared.notificationCenter ) } init( reader: @escaping @MainActor () -> Bool, + ownerReader: @escaping @MainActor () -> String? = { nil }, onChange: @escaping @MainActor (Bool) -> Void, activityCenter: NotificationCenter ) { self.reader = reader + self.ownerReader = ownerReader self.onChange = onChange self.activityCenter = activityCenter isEnabled = reader() + ownerName = isEnabled ? ownerReader() : nil } isolated deinit { stop() } @@ -73,13 +81,51 @@ public final class SecureInputMonitor { /// Synchronously reads state for hotkey callbacks and menu opening, even while stopped. @discardableResult - public func refresh() -> Bool { + public func refresh(checkOwner: Bool = true) -> Bool { let enabled = reader() - if enabled != isEnabled { + let owner = enabled ? (checkOwner || enabled != isEnabled ? ownerReader() : ownerName) : nil + if enabled != isEnabled || owner != ownerName { isEnabled = enabled + ownerName = owner onChange(enabled) } return isEnabled } +} + +@MainActor +enum SecureInputOwner { + static func currentName() -> String? { + let service = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("IOResources")) + guard service != 0 else { return nil } + defer { IOObjectRelease(service) } + guard let property = IORegistryEntryCreateCFProperty(service, "IOConsoleUsers" as CFString, nil, 0), + let sessions = property.takeRetainedValue() as? [NSDictionary] + else { return nil } + return name(in: sessions, userID: getuid()) { NSRunningApplication(processIdentifier: $0)?.localizedName } + } + static func name(in sessions: [NSDictionary], userID: uid_t, applicationName: (pid_t) -> String?) -> String? { + guard let pid = processID(in: sessions, userID: userID), let name = applicationName(pid), + !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + else { return nil } + return name + } + + static func processID(in sessions: [NSDictionary], userID: uid_t) -> pid_t? { + var owners: Set = [] + for session in sessions { + guard let console = session[kCGSessionOnConsoleKey] as? NSNumber, + CFGetTypeID(console) == CFBooleanGetTypeID(), console.boolValue, + let user = session[kCGSessionUserIDKey] as? NSNumber, + CFGetTypeID(user) == CFNumberGetTypeID(), uid_t(exactly: user) == userID + else { continue } + // This optional OS field identifies the owner; the foreground app does not. + guard let number = session["kCGSSessionSecureInputPID"] as? NSNumber, + CFGetTypeID(number) == CFNumberGetTypeID(), let pid = pid_t(exactly: number), pid > 0 + else { return nil } + owners.insert(pid) + } + return owners.count == 1 ? owners.first : nil + } } diff --git a/Tests/ParcelE2ETests/AppFeedbackTests.swift b/Tests/ParcelE2ETests/AppFeedbackTests.swift index 78891d06..78b05e1c 100644 --- a/Tests/ParcelE2ETests/AppFeedbackTests.swift +++ b/Tests/ParcelE2ETests/AppFeedbackTests.swift @@ -11,18 +11,41 @@ import Testing @Suite("App feedback wiring") @MainActor struct AppFeedbackTests { - @Test func secureInputOnlyHidesPresentedShortcutsAndRestoresTheSameConfiguration() throws { + @Test func secureInputOnlyHidesEventTapShortcutsAndRestoresTheSameConfiguration() throws { var configuration = ParcelConfiguration.defaults - configuration.modes = ["resize": [.exitMode: try KeyChord(parsing: "escape")]] - configuration.defaultModeEntries = ["resize": try KeyChord(parsing: "ctrl-alt-m")] - let suspended = NativeAppRuntime.shortcutPresentation(configuration, secureInput: true) - #expect(suspended.keybindings.isEmpty) - #expect(suspended.defaultModeEntries.isEmpty) - #expect(suspended.modes["resize"]?.isEmpty == true) - #expect(suspended.layout == configuration.layout) - #expect(suspended.mouse == configuration.mouse) - #expect(suspended.motion == configuration.motion) - #expect(NativeAppRuntime.shortcutPresentation(configuration, secureInput: false) == configuration) + let carbon = try KeyChord(parsing: "ctrl-alt-a") + let tap = try KeyChord(parsing: "ctrl-alt-cmd-shift-s") + let fallback = try KeyChord(parsing: "ctrl-alt-d") + configuration.keybindings = [.focusLeft: carbon, .focusRight: tap, .retile: fallback] + configuration.modes = [ + "resize": [.exitMode: carbon, .command(.ratioIncrease): tap, .command(.ratioDecrease): fallback] + ] + configuration.defaultModeEntries = ["resize": carbon, "tap": tap, "fallback": fallback] + let routes: [HotKey: HotKeyRoute] = [ + NativeAppRuntime.hotkey(carbon): .carbon, + NativeAppRuntime.hotkey(tap): .eventTap, + NativeAppRuntime.hotkey(fallback): .eventTap, + ] + let presented = NativeAppRuntime.shortcutPresentation(configuration, secureInput: true, routes: routes) + #expect(presented.keybindings == [.focusLeft: carbon]) + #expect(presented.defaultModeEntries == ["resize": carbon]) + #expect(presented.modes == ["resize": [.exitMode: carbon]]) + #expect(presented.layout == configuration.layout) + #expect(presented.mouse == configuration.mouse) + #expect(presented.motion == configuration.motion) + #expect(presented.focusModes == configuration.focusModes) + #expect( + NativeAppRuntime.shortcutPresentation(configuration, secureInput: false, routes: routes) == configuration) + } + + @Test func inactiveModeHintsUsePreferredRoutesUntilRegistered() throws { + var configuration = ParcelConfiguration.defaults + let carbon = try KeyChord(parsing: "escape") + let tap = try KeyChord(parsing: "ctrl-alt-cmd-shift-s") + configuration.modes = ["resize": [.exitMode: carbon, .command(.ratioIncrease): tap]] + let presented = NativeAppRuntime.shortcutPresentation(configuration, secureInput: true) + #expect(presented.modes == ["resize": [.exitMode: carbon]]) + #expect(configuration.modes["resize"]?.count == 2) } @Test func secureInputStatusIsQueryableWithoutPausingTiling() async throws { diff --git a/Tests/ParcelPlatformTests/Input/SecureInputGateTests.swift b/Tests/ParcelPlatformTests/Input/SecureInputGateTests.swift index 1b170c39..b97ad3c8 100644 --- a/Tests/ParcelPlatformTests/Input/SecureInputGateTests.swift +++ b/Tests/ParcelPlatformTests/Input/SecureInputGateTests.swift @@ -10,42 +10,49 @@ struct SecureInputGateTests { init(allowed: Bool) { self.allowed = allowed } } - @Test func carbonDispatchResumesOnTheFirstAllowedKeyWithoutReregistration() throws { + @Test func carbonPressesAndReleasesDispatchWhileEventTapInputIsBlocked() throws { let backend = HotKeyCenterTests.Backend() - let permission = Permission(allowed: false) var presses: [HotKeyPress] = [] var scheduled = 0 + var cancelled = 0 let center = HotKeyCenter( backend: backend, onPress: { presses.append($0) }, onFailure: { Issue.record($0) }, - isInputAllowed: { permission.allowed }, + isEventTapInputAllowed: { + Issue.record("Carbon must not consult the event-tap gate") + return false + }, scheduleRepeat: { _ in scheduled += 1 - return {} + return { cancelled += 1 } }) let key = HotKey(keyCode: 0, modifiers: .command) try center.register(key, repeats: true) defer { do { try center.stop() } catch { Issue.record(error) } } let id = try #require(backend.carbon.keys.first) backend.onCarbonEvent?(id, true) - #expect(presses.isEmpty) - #expect(scheduled == 0) - #expect(center.registrations.map(\.hotKey) == [key]) - permission.allowed = true backend.onCarbonEvent?(id, true) #expect(presses == [HotKeyPress(hotKey: key, isRepeat: false)]) #expect(scheduled == 1) + backend.onCarbonEvent?(id, false) + #expect(cancelled == 1) + backend.onCarbonEvent?(id, true) + #expect(presses.map(\.isRepeat) == [false, false]) + #expect(scheduled == 2) + #expect(center.registrations.map(\.hotKey) == [key]) #expect(backend.carbon.keys.first == id) } - @Test func blockedTapEventsPassThroughAndResumeWithoutApplicationActivity() throws { + @Test(arguments: [HotKey.Modifiers.hyper, .option]) + func blockedTapBindingsPassThroughAndResumeWithoutReregistration(modifiers: HotKey.Modifiers) throws { let backend = HotKeyCenterTests.Backend() + backend.status = -9868 let permission = Permission(allowed: false) var presses = 0 let center = HotKeyCenter( backend: backend, onPress: { _ in presses += 1 }, onFailure: { Issue.record($0) }, - isInputAllowed: { permission.allowed }) - let key = HotKey(keyCode: 0, modifiers: .hyper) - try center.register(key) + isEventTapInputAllowed: { permission.allowed }) + let key = HotKey(keyCode: 0, modifiers: modifiers) + #expect(try center.register(key).route == .eventTap) defer { do { try center.stop() } catch { Issue.record(error) } } let events = try HotKeyPoster.events(for: key) #expect(backend.onTapEvent?(.keyDown, events[0]) == false) @@ -56,47 +63,120 @@ struct SecureInputGateTests { #expect(backend.onTapEvent?(.keyDown, events[0]) == true) #expect(backend.onTapEvent?(.keyUp, events[1]) == true) #expect(presses == 1) + #expect(backend.attempts.count == (modifiers == .hyper ? 0 : 1)) } - @Test func secureTransitionStopsHeldRepeatsAndStaleTicksCannotResumeThem() throws { + @Test func secureTransitionsAndBlockedTapEventsPreserveHeldCarbonRepeats() throws { let backend = HotKeyCenterTests.Backend() let permission = Permission(allowed: true) - var ticks: [@MainActor () -> Void] = [] + var tick: (@MainActor () -> Void)? var cancellations = 0 - var presses = 0 - var reads = 0 + var presses: [HotKeyPress] = [] let center = HotKeyCenter( - backend: backend, onPress: { _ in presses += 1 }, onFailure: { Issue.record($0) }, - isInputAllowed: { - reads += 1 - return permission.allowed - }, - scheduleRepeat: { tick in - ticks.append(tick) + backend: backend, onPress: { presses.append($0) }, onFailure: { Issue.record($0) }, + isEventTapInputAllowed: { permission.allowed }, + scheduleRepeat: { action in + tick = action return { cancellations += 1 } }) - try center.register(HotKey(keyCode: 0, modifiers: .command), repeats: true) + let carbon = HotKey(keyCode: 0, modifiers: .command) + let tap = HotKey(keyCode: 1, modifiers: .hyper) + try center.register(carbon, repeats: true) + try center.register(tap, repeats: true) defer { do { try center.stop() } catch { Issue.record(error) } } let id = try #require(backend.carbon.keys.first) backend.onCarbonEvent?(id, true) - let tick = try #require(ticks.first) + let repeatTick = try #require(tick) + repeatTick() permission.allowed = false - tick() - #expect(presses == 1) + center.resetEventTapPressedState() + let events = try HotKeyPoster.events(for: tap) + #expect(backend.onTapEvent?(.keyDown, events[0]) == false) + #expect(backend.onTapEvent?(.keyUp, events[1]) == false) + repeatTick() + backend.onCarbonEvent?(id, true) + #expect(presses.map(\.isRepeat) == [false, true, true]) + #expect(cancellations == 0) + permission.allowed = true + center.resetEventTapPressedState() + repeatTick() + #expect(presses.map(\.isRepeat) == [false, true, true, true]) + #expect(presses.allSatisfy { $0.hotKey == carbon }) + #expect(cancellations == 0) + permission.allowed = false + backend.onCarbonEvent?(id, false) #expect(cancellations == 1) - let pausedReads = reads - tick() + repeatTick() + #expect(presses.count == 4) + } + + @Test func blockedTapRepeatsClearHeldStateWithoutConsumingEvents() throws { + let backend = HotKeyCenterTests.Backend() + let permission = Permission(allowed: true) + var presses: [HotKeyPress] = [] + let center = HotKeyCenter( + backend: backend, onPress: { presses.append($0) }, onFailure: { Issue.record($0) }, + isEventTapInputAllowed: { permission.allowed }) + let key = HotKey(keyCode: 0, modifiers: .hyper) + try center.register(key, repeats: true) + defer { do { try center.stop() } catch { Issue.record(error) } } + let events = try HotKeyPoster.events(for: key) + #expect(backend.onTapEvent?(.keyDown, events[0]) == true) + events[0].setIntegerValueField(.keyboardEventAutorepeat, value: 1) + #expect(backend.onTapEvent?(.keyDown, events[0]) == true) + permission.allowed = false + #expect(backend.onTapEvent?(.keyDown, events[0]) == false) + #expect(backend.onTapEvent?(.keyUp, events[1]) == false) + #expect(presses.map(\.isRepeat) == [false, true]) permission.allowed = true - tick() - #expect(reads == pausedReads) - #expect(presses == 1) - backend.onCarbonEvent?(id, true) - #expect(presses == 2) - #expect(ticks.count == 2) - tick() - #expect(presses == 2) - ticks[1]() - #expect(presses == 3) + events[0].setIntegerValueField(.keyboardEventAutorepeat, value: 0) + #expect(backend.onTapEvent?(.keyDown, events[0]) == true) + #expect(presses.map(\.isRepeat) == [false, true, false]) + } + + @Test func availabilityRechecksTheActualRouteForQueuedDispatch() throws { + let backend = HotKeyCenterTests.Backend() + let permission = Permission(allowed: true) + let center = HotKeyCenter( + backend: backend, onPress: { _ in }, onFailure: { Issue.record($0) }, + isEventTapInputAllowed: { permission.allowed }) + let carbon = HotKey(keyCode: 0, modifiers: .command) + let fallback = HotKey(keyCode: 1, modifiers: .command) + let tap = HotKey(keyCode: 2, modifiers: .hyper) + try center.register(carbon) + backend.status = -9868 + try center.register(fallback) + try center.register(tap) + defer { do { try center.stop() } catch { Issue.record(error) } } + #expect(center.isAvailable(carbon)) + #expect(center.isAvailable(fallback)) + #expect(center.isAvailable(tap)) + permission.allowed = false + #expect(center.isAvailable(carbon)) + #expect(!center.isAvailable(fallback)) + #expect(!center.isAvailable(tap)) + #expect(!center.isAvailable(HotKey(keyCode: 3))) + permission.allowed = true + #expect(center.isAvailable(fallback)) + #expect(center.isAvailable(tap)) + try center.unregister(carbon) + #expect(!center.isAvailable(carbon)) + } + + @Test func activityResetClearsMissingTapReleasesButKeepsRegistrations() throws { + let backend = HotKeyCenterTests.Backend() + var presses: [HotKeyPress] = [] + let center = HotKeyCenter( + backend: backend, onPress: { presses.append($0) }, onFailure: { Issue.record($0) }) + let key = HotKey(keyCode: 0, modifiers: .hyper) + try center.register(key) + defer { do { try center.stop() } catch { Issue.record(error) } } + let events = try HotKeyPoster.events(for: key) + #expect(backend.onTapEvent?(.keyDown, events[0]) == true) + center.resetEventTapPressedState() + #expect(backend.onTapEvent?(.keyDown, events[0]) == true) + #expect(presses.map(\.isRepeat) == [false, false]) + #expect(center.registrations.map(\.hotKey) == [key]) } @Test func resetPressedStatePreservesRegistrationsAndClearsMissingReleases() throws { diff --git a/Tests/ParcelPlatformTests/SecureInputTests.swift b/Tests/ParcelPlatformTests/SecureInputTests.swift index 7e4f4ca1..58c4a42b 100644 --- a/Tests/ParcelPlatformTests/SecureInputTests.swift +++ b/Tests/ParcelPlatformTests/SecureInputTests.swift @@ -9,6 +9,8 @@ struct SecureInputTests { let activityCenter = NotificationCenter() var enabled = false var reads = 0 + var owner: String? + var ownerReads = 0 var changes: [Bool] = [] func makeMonitor(onChange: (@MainActor (Bool) -> Void)? = nil) -> SecureInputMonitor { @@ -17,6 +19,10 @@ struct SecureInputTests { self.reads += 1 return self.enabled }, + ownerReader: { + self.ownerReads += 1 + return self.owner + }, onChange: { self.changes.append($0) onChange?($0) @@ -143,6 +149,137 @@ struct SecureInputTests { monitor = nil } + @Test func ownerChangesPublishWithoutChangingEnabledStateAndClearWhenDisabled() { + let fixture = Fixture() + fixture.enabled = true + fixture.owner = "Fixture" + var changes: [String?] = [] + var monitor: SecureInputMonitor? + monitor = fixture.makeMonitor { current in + #expect(current == fixture.enabled) + changes.append(monitor?.ownerName) + #expect(monitor?.refresh() == fixture.enabled) + } + #expect(monitor?.ownerName == "Fixture") + #expect(changes.isEmpty) + fixture.owner = "Other Fixture" + #expect(monitor?.refresh() == true) + #expect(changes == ["Other Fixture"]) + fixture.owner = nil + #expect(monitor?.refresh() == true) + #expect(changes == ["Other Fixture", nil]) + fixture.owner = "Fixture" + #expect(monitor?.refresh() == true) + fixture.enabled = false + #expect(monitor?.refresh() == false) + #expect(monitor?.ownerName == nil) + #expect(changes == ["Other Fixture", nil, "Fixture", nil]) + monitor = nil + } + + @Test func hotkeyRefreshReadsOwnerOnlyOnEnableAndMenuRefreshUpdatesIt() { + let fixture = Fixture() + fixture.owner = "Fixture" + let monitor = fixture.makeMonitor() + #expect(fixture.ownerReads == 0) + #expect(!monitor.refresh()) + #expect(fixture.ownerReads == 0) + fixture.enabled = true + #expect(monitor.refresh(checkOwner: false)) + #expect(monitor.ownerName == "Fixture") + #expect(fixture.ownerReads == 1) + fixture.owner = "Other Fixture" + for _ in 0..<5 { #expect(monitor.refresh(checkOwner: false)) } + #expect(fixture.ownerReads == 1) + #expect(monitor.ownerName == "Fixture") + #expect(monitor.refresh()) + #expect(fixture.ownerReads == 2) + #expect(monitor.ownerName == "Other Fixture") + fixture.enabled = false + #expect(!monitor.refresh(checkOwner: false)) + #expect(monitor.ownerName == nil) + #expect(fixture.ownerReads == 2) + } + + @Test func activityRefreshesOwnerWhileSecureInputStaysEnabled() { + let fixture = Fixture() + fixture.enabled = true + fixture.owner = "Fixture" + let monitor = fixture.makeMonitor() + monitor.start() + defer { monitor.stop() } + fixture.owner = "Other Fixture" + fixture.activityCenter.post(name: NSWorkspace.didActivateApplicationNotification, object: nil) + #expect(monitor.ownerName == "Other Fixture") + #expect(fixture.changes == [true]) + } + + private func session( + owner: NSObject?, user: NSObject = NSNumber(value: 501), console: NSObject = NSNumber(value: true) + ) + -> NSDictionary + { + let session = NSMutableDictionary() + session[kCGSessionUserIDKey] = user + session[kCGSessionOnConsoleKey] = console + if let owner { session["kCGSSessionSecureInputPID"] = owner } + return session + } + + @Test func ownerLookupUsesOnlyTheCurrentUsersConsoleSession() { + let sessions = [ + session(owner: NSNumber(value: 31), user: NSNumber(value: 502)), + session(owner: NSNumber(value: 32), console: NSNumber(value: false)), + session(owner: NSNumber(value: 33)), + ] + var lookedUp: [pid_t] = [] + #expect( + SecureInputOwner.name(in: sessions, userID: 501) { pid in + lookedUp.append(pid) + return "Background Fixture" + } == "Background Fixture") + #expect(lookedUp == [33]) + #expect(SecureInputOwner.processID(in: [], userID: 501) == nil) + #expect(SecureInputOwner.processID(in: [sessions[0], sessions[1]], userID: 501) == nil) + } + + @Test func ownerLookupRejectsMissingMalformedOrAmbiguousMetadata() { + let invalid: [NSObject?] = [ + nil, NSString(string: "33"), NSNumber(value: true), NSNumber(value: 0), NSNumber(value: -1), + NSNumber(value: 33.5), NSNumber(value: Int64(Int32.max) + 1), NSNumber(value: Double.nan), + ] + for owner in invalid { + #expect(SecureInputOwner.processID(in: [session(owner: owner)], userID: 501) == nil) + } + #expect( + SecureInputOwner.processID( + in: [session(owner: NSNumber(value: 33)), session(owner: NSNumber(value: 34))], userID: 501) == nil) + #expect( + SecureInputOwner.processID( + in: [session(owner: NSNumber(value: 33)), session(owner: nil)], userID: 501) == nil) + #expect( + SecureInputOwner.processID( + in: [session(owner: NSNumber(value: 33)), session(owner: NSNumber(value: 33))], userID: 501) == 33) + for user: NSObject in [NSString(string: "501"), NSNumber(value: 501.5), NSNumber(value: true)] { + #expect( + SecureInputOwner.processID(in: [session(owner: NSNumber(value: 33), user: user)], userID: 501) == nil) + } + #expect( + SecureInputOwner.processID( + in: [session(owner: NSNumber(value: 33), console: NSNumber(value: 1))], userID: 501) == nil) + } + + @Test func absentOrUnnamedOwnerNeverInventsAnApplicationName() { + for name: String? in [nil, "", " \n "] { + #expect(SecureInputOwner.name(in: [session(owner: NSNumber(value: 33))], userID: 501) { _ in name } == nil) + } + #expect( + SecureInputOwner.name(in: [session(owner: nil)], userID: 501) { _ in + Issue.record("No application should be consulted without an owner PID") + return "Unrelated Fixture" + } == nil) + } + @Test func destructionRemovesObservers() { let fixture = Fixture() var monitor: SecureInputMonitor? = fixture.makeMonitor() -- knotmirror 0.0.1 From 54657593b7069920338b77cec881dfbd3365cdf9 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 11:04:18 -0400 Subject: [PATCH 4/6] Preserve Carbon repeats during protected input --- .../ParcelPlatform/Input/HotKeyCenter.swift | 17 ++++-- .../AppRuntimeRegressionTests.swift | 2 +- .../Input/InputServiceTests.swift | 9 ++- .../Input/SecureInputGateTests.swift | 61 +++++++++++++++++++ 4 files changed, 82 insertions(+), 7 deletions(-) diff --git a/Sources/ParcelPlatform/Input/HotKeyCenter.swift b/Sources/ParcelPlatform/Input/HotKeyCenter.swift index 1a6b47e0..1994ac38 100644 --- a/Sources/ParcelPlatform/Input/HotKeyCenter.swift +++ b/Sources/ParcelPlatform/Input/HotKeyCenter.swift @@ -9,7 +9,7 @@ protocol HotKeyBackend: AnyObject { var onFailure: (@MainActor (InputError) -> Void)? { get set } func registerCarbon(_ key: HotKey, id: UInt32) throws -> Int32 func unregisterCarbon(id: UInt32) throws - func isPressed(_ key: HotKey) -> Bool + func isPressed(_ key: HotKey) -> Bool? func startTap() throws func stopTap() } @@ -81,6 +81,10 @@ public final class HotKeyCenter { repeats.removeAll() } + static func sampledPressedState(secureInput: Bool, read: () -> Bool) -> Bool? { + secureInput ? nil : read() + } + private static func systemRepeat(_ tick: @escaping @MainActor () -> Void) -> (@MainActor () -> Void) { let timer = Timer(timeInterval: max(0.01, NSEvent.keyRepeatInterval), repeats: true) { _ in MainActor.assumeIsolated { tick() } @@ -198,7 +202,8 @@ public final class HotKeyCenter { guard let self, self.repeatGeneration == generation, self.repeats[key] != nil, self.bindings[key]?.id == id else { return } - guard self.backend.isPressed(key) else { + // Protected input hides sampled state, but Carbon still reports releases. + if self.backend.isPressed(key) == false { self.repeats.removeValue(forKey: key)?() _ = self.carbonState.up(keyCode: key.keyCode) return @@ -286,9 +291,11 @@ private final class NativeHotKeyBackend: HotKeyBackend { } } - func isPressed(_ key: HotKey) -> Bool { - CGEventSource.keyState(.combinedSessionState, key: key.keyCode) - && HotKey.Modifiers(eventFlags: CGEventSource.flagsState(.combinedSessionState)) == key.modifiers + func isPressed(_ key: HotKey) -> Bool? { + HotKeyCenter.sampledPressedState(secureInput: IsSecureEventInputEnabled()) { + CGEventSource.keyState(.combinedSessionState, key: key.keyCode) + && HotKey.Modifiers(eventFlags: CGEventSource.flagsState(.combinedSessionState)) == key.modifiers + } } func startTap() throws { diff --git a/Tests/ParcelE2ETests/AppRuntimeRegressionTests.swift b/Tests/ParcelE2ETests/AppRuntimeRegressionTests.swift index 64db6484..e95ffea4 100644 --- a/Tests/ParcelE2ETests/AppRuntimeRegressionTests.swift +++ b/Tests/ParcelE2ETests/AppRuntimeRegressionTests.swift @@ -380,7 +380,7 @@ private final class CarbonBackend: HotKeyBackend { return status } func unregisterCarbon(id: UInt32) throws {} - func isPressed(_ key: HotKey) -> Bool { true } + func isPressed(_ key: HotKey) -> Bool? { true } func startTap() throws { tapStarts += 1 } func stopTap() {} } diff --git a/Tests/ParcelPlatformTests/Input/InputServiceTests.swift b/Tests/ParcelPlatformTests/Input/InputServiceTests.swift index 559fcecd..adf719a4 100644 --- a/Tests/ParcelPlatformTests/Input/InputServiceTests.swift +++ b/Tests/ParcelPlatformTests/Input/InputServiceTests.swift @@ -19,6 +19,8 @@ struct HotKeyCenterTests { var carbon: [UInt32: HotKey] = [:] var tapRunning = false var physicallyHeld = true + var secureInput = false + var keyStateReads = 0 var attempts: [HotKey] = [] func registerCarbon(_ key: HotKey, id: UInt32) throws -> Int32 { @@ -31,7 +33,12 @@ struct HotKeyCenterTests { if let unregisterError { throw unregisterError } carbon.removeValue(forKey: id) } - func isPressed(_ key: HotKey) -> Bool { physicallyHeld } + func isPressed(_ key: HotKey) -> Bool? { + HotKeyCenter.sampledPressedState(secureInput: secureInput) { + keyStateReads += 1 + return physicallyHeld + } + } func startTap() throws { if let tapError { throw tapError } tapRunning = true diff --git a/Tests/ParcelPlatformTests/Input/SecureInputGateTests.swift b/Tests/ParcelPlatformTests/Input/SecureInputGateTests.swift index b97ad3c8..b5c9209b 100644 --- a/Tests/ParcelPlatformTests/Input/SecureInputGateTests.swift +++ b/Tests/ParcelPlatformTests/Input/SecureInputGateTests.swift @@ -110,6 +110,67 @@ struct SecureInputGateTests { #expect(presses.count == 4) } + @Test(arguments: [false, true]) + func protectedKeyStateIsUnavailableRatherThanUpOrDown(pressed: Bool) { + var reads = 0 + let read = { + reads += 1 + return pressed + } + #expect(HotKeyCenter.sampledPressedState(secureInput: true, read: read) == nil) + #expect(reads == 0) + #expect(HotKeyCenter.sampledPressedState(secureInput: false, read: read) == pressed) + #expect(reads == 1) + } + + @Test(arguments: [false, true]) + func carbonRepeatsUseReleaseCallbacksWhileSampledKeyStateIsProtected(initiallySecure: Bool) throws { + let backend = HotKeyCenterTests.Backend() + backend.secureInput = initiallySecure + backend.physicallyHeld = !initiallySecure + var tick: (@MainActor () -> Void)? + var cancellations = 0 + var presses: [HotKeyPress] = [] + let center = HotKeyCenter( + backend: backend, onPress: { presses.append($0) }, onFailure: { Issue.record($0) }, + isEventTapInputAllowed: { !backend.secureInput }, + scheduleRepeat: { action in + tick = action + return { cancellations += 1 } + }) + let key = HotKey(keyCode: 0, modifiers: .command) + try center.register(key, repeats: true) + defer { do { try center.stop() } catch { Issue.record(error) } } + let id = try #require(backend.carbon.keys.first) + backend.onCarbonEvent?(id, true) + let repeatTick = try #require(tick) + repeatTick() + let readsBeforeSecureInput = backend.keyStateReads + backend.secureInput = true + backend.physicallyHeld = false + repeatTick() + repeatTick() + #expect(presses.map(\.isRepeat) == [false, true, true, true]) + #expect(backend.keyStateReads == readsBeforeSecureInput) + #expect(cancellations == 0) + backend.onCarbonEvent?(id, false) + #expect(cancellations == 1) + repeatTick() + #expect(presses.count == 4) + + backend.onCarbonEvent?(id, true) + let nextTick = try #require(tick) + nextTick() + #expect(presses.map(\.isRepeat) == [false, true, true, true, false, true]) + backend.secureInput = false + nextTick() + #expect(cancellations == 2) + #expect(backend.keyStateReads == readsBeforeSecureInput + 1) + #expect(presses.count == 6) + nextTick() + #expect(presses.count == 6) + } + @Test func blockedTapRepeatsClearHeldStateWithoutConsumingEvents() throws { let backend = HotKeyCenterTests.Backend() let permission = Permission(allowed: true) -- knotmirror 0.0.1 From b40e8d30dd7bb04b47000ba2f964f4fd47015de3 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 11:20:48 -0400 Subject: [PATCH 5/6] Keep feedback calm and restore card focus --- .../Feedback/FeedbackController.swift | 110 +++++++++++----- Sources/ParcelUI/Feedback/FeedbackModel.swift | 15 ++- .../ParcelUI/Feedback/FeedbackNotice.swift | 13 +- .../ParcelUI/Feedback/FeedbackPlacement.swift | 20 +++ Sources/ParcelUI/Resources/Feedback.xcstrings | 44 ++++++- Tests/ParcelUITests/FeedbackTests.swift | 123 +++++++++++++++++- 6 files changed, 277 insertions(+), 48 deletions(-) create mode 100644 Sources/ParcelUI/Feedback/FeedbackPlacement.swift diff --git a/Sources/ParcelUI/Feedback/FeedbackController.swift b/Sources/ParcelUI/Feedback/FeedbackController.swift index 57ac1dd9..c4dd9e61 100644 --- a/Sources/ParcelUI/Feedback/FeedbackController.swift +++ b/Sources/ParcelUI/Feedback/FeedbackController.swift @@ -9,6 +9,9 @@ public final class FeedbackController { public var onResolve: (@MainActor (FeedbackNotice, RoomResolution) async throws -> Void)? private let onFailure: @MainActor (any Error) -> Void private let sensory: FeedbackSensory + private let announce: @MainActor (String) -> Void + private let dismissDelay: Duration + private var restoreFocus: (@MainActor () -> Void)? private var state = ParcelCore.State() private var configuration = MotionConfiguration() private var panel: LearningPanel? @@ -17,17 +20,22 @@ public final class FeedbackController { private var dismissTask: Task? private var actionTask: Task? private var secureInput = false + private var secureInputOwner: String? private var renderedOptions: RoomOptions? private var renderedConfiguration: MotionConfiguration? - private var renderedScreen: Rect? + private var renderedScreen: CGRect? public var isVisible: Bool { panel?.isVisible == true } + public var isKeyWindow: Bool { panel?.isKeyWindow == true } public init( model: FeedbackModel, sensory: FeedbackSensory = FeedbackSensory(), + announce: (@MainActor (String) -> Void)? = nil, dismissDelay: Duration = .seconds(4), onFailure: @escaping @MainActor (any Error) -> Void ) { self.model = model self.sensory = sensory + self.announce = announce ?? Self.announce + self.dismissDelay = dismissDelay self.onFailure = onFailure model.onChange = { [weak self] in self?.render() } } @@ -47,16 +55,10 @@ public final class FeedbackController { NSRunningApplication(processIdentifier: window.app.pid)?.localizedName ?? window.app.bundleID }) { - if try model.receive(notice, explicitlyRequested: explicitlyRequested) { - sensory.notice( - configuration: configuration, - reduceMotion: NSWorkspace.shared.accessibilityDisplayShouldReduceMotion) - NSAccessibility.post( - element: NSApplication.shared, notification: .announcementRequested, - userInfo: [ - .announcement: [notice.title, notice.detail].compactMap { $0 }.joined(separator: " "), - .priority: NSAccessibilityPriorityLevel.medium.rawValue, - ]) + if try model.receive(notice, explicitlyRequested: explicitlyRequested), + let current = model.current, current.coalesces(with: notice) + { + scheduleDismissal(current) } } } @@ -66,13 +68,17 @@ public final class FeedbackController { configuration: configuration, reduceMotion: NSWorkspace.shared.accessibilityDisplayShouldReduceMotion) } - public func setSecureInput(_ enabled: Bool) { secureInput = enabled } + public func setSecureInput(_ enabled: Bool, ownerName: String? = nil) { + secureInput = enabled + secureInputOwner = enabled ? ownerName : nil + } public func installMenuItems(in menu: NSMenu, at index: Int) { var insertion = index if secureInput { - let item = NSMenuItem(title: Self.secureInputNotice, action: nil, keyEquivalent: "") - item.setAccessibilityLabel(Self.secureInputNotice) + let status = Self.secureInputNotice(ownerName: secureInputOwner) + let item = NSMenuItem(title: status, action: nil, keyEquivalent: "") + item.setAccessibilityLabel(status) item.isEnabled = false menu.insertItem(item, at: insertion) insertion += 1 @@ -87,14 +93,34 @@ public final class FeedbackController { at: insertion) } - public static var secureInputNotice: String { - FeedbackText.string("Shortcuts are paused during Secure Input. They resume when secure entry ends.") + public static var secureInputNotice: String { secureInputNotice(ownerName: nil) } + + public static func secureInputNotice(ownerName: String?) -> String { + if let ownerName { + FeedbackText.format( + "%@ is using Secure Input. Some shortcuts are unavailable; standard shortcuts still work.", ownerName) + } else { + FeedbackText.string("Secure Input is on. Some shortcuts are unavailable; standard shortcuts still work.") + } } public func showCurrent() { render() + guard let panel, panel.isVisible else { return } dismissTask?.cancel() - panel?.makeKeyAndOrderFront(nil) + if restoreFocus == nil { + let application = NSWorkspace.shared.frontmostApplication + let window = NSApplication.shared.keyWindow + restoreFocus = { + if let application, application.processIdentifier != ProcessInfo.processInfo.processIdentifier { + guard !application.isTerminated else { return } + application.activate() + } else { + window?.makeKeyAndOrderFront(nil) + } + } + } + panel.makeKeyAndOrderFront(nil) } public func showPreferences() { @@ -122,6 +148,7 @@ public final class FeedbackController { actionTask?.cancel() dismissTask = nil actionTask = nil + hidePanel() panel?.close() panel = nil preferencesWindow?.close() @@ -132,19 +159,21 @@ public final class FeedbackController { private func render() { guard let notice = model.current else { dismissTask?.cancel() - panel?.orderOut(nil) + hidePanel() visibleID = nil return } let changed = visibleID != notice.id if changed { dismissTask?.cancel() + hidePanel() visibleID = notice.id } let options = notice.window.flatMap { state.roomOptions(for: $0) } - let screen = + let display = notice.workspace.flatMap { state.displays[$0.display]?.frame } ?? state.activeDisplay.flatMap { state.displays[$0]?.frame } + let screen = FeedbackPlacement.visibleFrame(for: display) guard changed || renderedOptions != options || renderedConfiguration != configuration || renderedScreen != screen else { return } @@ -177,8 +206,7 @@ public final class FeedbackController { panel.contentView = hosting let size = hosting.fittingSize if let screen { - panel.place( - CGRect(x: screen.maxX - size.width - 20, y: screen.minY + 20, width: size.width, height: size.height)) + panel.setFrame(FeedbackPlacement.frame(size: size, visibleFrame: screen), display: false) } else { panel.setContentSize(size) panel.center() @@ -187,15 +215,37 @@ public final class FeedbackController { panel.orderFrontRegardless() hosting.wantsLayer = true if let layer = hosting.layer { LearningMotion.show(layer, token: .pop, configuration: configuration) } - if notice.kind != .needsRoom { - dismissTask = Task { @MainActor [weak self] in - do { try await Task.sleep(for: .seconds(4)) } catch { return } - self?.model.dismiss(notice.id) - } - } + sensory.notice( + configuration: configuration, + reduceMotion: NSWorkspace.shared.accessibilityDisplayShouldReduceMotion) + announce([notice.title, notice.detail].compactMap { $0 }.joined(separator: " ")) + scheduleDismissal(notice) } } + private func hidePanel() { + let hadFocus = panel?.isKeyWindow == true + panel?.orderOut(nil) + if hadFocus { restoreFocus?() } + restoreFocus = nil + } + + private func scheduleDismissal(_ notice: FeedbackNotice) { + guard notice.kind != .needsRoom else { return } + dismissTask?.cancel() + let delay = dismissDelay + dismissTask = Task { @MainActor [weak self] in + do { try await Task.sleep(for: delay) } catch { return } + self?.model.dismiss(notice.id) + } + } + + private static func announce(_ text: String) { + NSAccessibility.post( + element: NSApplication.shared, notification: .announcementRequested, + userInfo: [.announcement: text, .priority: NSAccessibilityPriorityLevel.medium.rawValue]) + } + deinit { dismissTask?.cancel() actionTask?.cancel() @@ -235,11 +285,7 @@ private struct FeedbackCard: View { Button(FeedbackText.format("Move to %@", displayName(display))) { resolve(.moveToDisplay(display)) } } ForEach(options.windowCaps, id: \.self) { count in - Button( - count == 1 - ? FeedbackText.string("Use one window here") - : FeedbackText.format("Use %lld windows here", Int64(count)) - ) { resolve(.useWindowCap(count)) } + Button(FeedbackText.format("Use %lld windows here", Int64(count))) { resolve(.useWindowCap(count)) } } Button(FeedbackText.string("Keep floating")) { resolve(.keepFloating) } .accessibilityIdentifier("feedback.keep-floating") diff --git a/Sources/ParcelUI/Feedback/FeedbackModel.swift b/Sources/ParcelUI/Feedback/FeedbackModel.swift index c614d83f..5949e9c5 100644 --- a/Sources/ParcelUI/Feedback/FeedbackModel.swift +++ b/Sources/ParcelUI/Feedback/FeedbackModel.swift @@ -9,7 +9,12 @@ public final class FeedbackModel { public private(set) var recent: [FeedbackNotice] = [] public private(set) var pending: [FeedbackNotice] = [] public private(set) var historyError: String? - public var current: FeedbackNotice? { pending.first } + public var current: FeedbackNotice? { + pending.first { notice in + notice.workspace.map { !inactiveWorkspaces.contains($0) } ?? true + } + } + private var inactiveWorkspaces: Set = [] public var onChange: (@MainActor () -> Void)? public var onShowAgain: (@MainActor (String) -> Void)? public var onForgetMinimum: (@MainActor (String) async throws -> Void)? @@ -31,6 +36,9 @@ public final class FeedbackModel { @discardableResult public func receive(_ notice: FeedbackNotice, explicitlyRequested: Bool = false) throws -> Bool { + if notice.kind != .needsRoom, let current, current.coalesces(with: notice) { + return true + } if notice.kind == .needsRoom, let bundle = notice.bundleID, !bundle.isEmpty { guard historyError == nil else { throw FeedbackHistoryError.invalidEntry } guard explicitlyRequested || history.shouldShow(for: bundle, at: now(), calendar: calendar) else { @@ -63,15 +71,16 @@ public final class FeedbackModel { public func reconcile(_ state: State, active: Bool) { let before = pending + let previous = current pending.removeAll { notice in guard active else { return true } guard notice.kind == .needsRoom, let window = notice.window, let workspace = notice.workspace else { return false } return state.windows[window]?.isFloating != false || state.workspace(containing: window) != workspace - || !state.isActive(workspace) } - if pending != before { onChange?() } + inactiveWorkspaces = Set(pending.compactMap(\.workspace).filter { !state.isActive($0) }) + if pending != before || previous != current { onChange?() } } public func showAgain(_ bundleID: String) { diff --git a/Sources/ParcelUI/Feedback/FeedbackNotice.swift b/Sources/ParcelUI/Feedback/FeedbackNotice.swift index de3f0660..f27f2038 100644 --- a/Sources/ParcelUI/Feedback/FeedbackNotice.swift +++ b/Sources/ParcelUI/Feedback/FeedbackNotice.swift @@ -17,11 +17,9 @@ public struct FeedbackNotice: Identifiable, Equatable, Codable, Sendable { public var title: String { switch kind { case .retiled: - switch count { - case 0: FeedbackText.string("Everything is already in place.") - case 1: FeedbackText.string("Retiled one window.") - default: FeedbackText.format("Retiled %lld windows.", Int64(count)) - } + count == 0 + ? FeedbackText.string("Everything is already in place.") + : FeedbackText.format("Retiled %lld windows.", Int64(count)) case .needsRoom: FeedbackText.string("Needs more room") case .spaceFull: FeedbackText.string("This Space is full") case .maximumSizeReached: FeedbackText.string("Maximum size reached") @@ -40,6 +38,11 @@ public struct FeedbackNotice: Identifiable, Equatable, Codable, Sendable { } } + func coalesces(with other: FeedbackNotice) -> Bool { + kind != .needsRoom && kind == other.kind && count == other.count + && window == other.window && workspace == other.workspace && bundleID == other.bundleID + } + public static func map( _ report: Report, state: State, applicationName: (ManagedWindow) -> String = { $0.app.bundleID } ) -> [FeedbackNotice] { diff --git a/Sources/ParcelUI/Feedback/FeedbackPlacement.swift b/Sources/ParcelUI/Feedback/FeedbackPlacement.swift new file mode 100644 index 00000000..ea51e8f0 --- /dev/null +++ b/Sources/ParcelUI/Feedback/FeedbackPlacement.swift @@ -0,0 +1,20 @@ +import AppKit +import ParcelCore + +@MainActor +enum FeedbackPlacement { + static func frame(size: CGSize, visibleFrame: CGRect) -> CGRect { + let margin = min(20, min(visibleFrame.width, visibleFrame.height) / 4) + let available = visibleFrame.insetBy(dx: margin, dy: margin) + let width = min(size.width, available.width) + let height = min(size.height, available.height) + return CGRect(x: available.maxX - width, y: available.minY, width: width, height: height) + } + + static func visibleFrame(for display: Rect?) -> CGRect? { + guard let display else { return NSScreen.main?.visibleFrame } + let height = NSScreen.screens.first?.frame.maxY ?? 0 + let center = NSPoint(x: display.center.xCoordinate, y: height - display.center.yCoordinate) + return NSScreen.screens.first { $0.frame.contains(center) }?.visibleFrame + } +} diff --git a/Sources/ParcelUI/Resources/Feedback.xcstrings b/Sources/ParcelUI/Resources/Feedback.xcstrings index dd16bacc..879b4e9c 100644 --- a/Sources/ParcelUI/Resources/Feedback.xcstrings +++ b/Sources/ParcelUI/Resources/Feedback.xcstrings @@ -1,23 +1,55 @@ { "sourceLanguage": "en", "strings": { - "Retiled one window.": {}, - "Use one window here": {}, "Everything is already in place.": {}, - "Retiled %lld windows.": {}, + "Retiled %lld windows.": { + "localizations": { + "en": { + "variations": { + "plural": { + "one": { "stringUnit": { "state": "translated", "value": "Retiled one window." } }, + "other": { "stringUnit": { "state": "translated", "value": "Retiled %lld windows." } } + } + } + } + } + }, "Needs more room": {}, "This Space is full": {}, "Maximum size reached": {}, "Minimum size reached": {}, - "This Space is using its limit of %lld tiles.": {}, + "This Space is using its limit of %lld tiles.": { + "localizations": { + "en": { + "variations": { + "plural": { + "one": { "stringUnit": { "state": "translated", "value": "This Space is using its limit of %lld tile." } }, + "other": { "stringUnit": { "state": "translated", "value": "This Space is using its limit of %lld tiles." } } + } + } + } + } + }, "%@ cannot fit in its tile. Give it more room or keep it floating.": {}, "The new window is floating in the middle.": {}, "Room reminder history could not be loaded. Reset it in Feedback settings.": {}, "Feedback…": {}, "Feedback": {}, - "Shortcuts are paused during Secure Input. They resume when secure entry ends.": {}, + "Secure Input is on. Some shortcuts are unavailable; standard shortcuts still work.": {}, + "%@ is using Secure Input. Some shortcuts are unavailable; standard shortcuts still work.": {}, "Move to %@": {}, - "Use %lld windows here": {}, + "Use %lld windows here": { + "localizations": { + "en": { + "variations": { + "plural": { + "one": { "stringUnit": { "state": "translated", "value": "Use one window here" } }, + "other": { "stringUnit": { "state": "translated", "value": "Use %lld windows here" } } + } + } + } + } + }, "Keep floating": {}, "Dismiss": {}, "Room reminders": {}, diff --git a/Tests/ParcelUITests/FeedbackTests.swift b/Tests/ParcelUITests/FeedbackTests.swift index 305e5114..dc770d0c 100644 --- a/Tests/ParcelUITests/FeedbackTests.swift +++ b/Tests/ParcelUITests/FeedbackTests.swift @@ -16,6 +16,7 @@ struct FeedbackTests { (.maximumSizeReached, .maximumSizeReached, "Maximum size reached"), (.minimumSizeReached, .minimumSizeReached, "Minimum size reached"), (.atWindowCap(3), .windowCap, "This Space is using its limit of 3 tiles."), + (.atWindowCap(1), .windowCap, "This Space is using its limit of 1 tile."), (.spaceFull(WindowID(rawValue: 1)), .spaceFull, "This Space is full"), ]) func semanticReportsBecomeLocalizedNotices(report: Report, kind: FeedbackNotice.Kind, title: String) throws { @@ -122,7 +123,7 @@ struct FeedbackTests { #expect(model.current?.kind == .retiled) } - @Test func changingFocusDoesNotRetargetButClosingOrChangingSpacesClearsTheCard() throws { + @Test func changingSpacesHidesTheSameCardUntilReturningWithoutConsumingAnotherReminder() throws { let model = FeedbackModel() let notice = try roomNotice() try model.receive(notice) @@ -133,7 +134,11 @@ struct FeedbackTests { state.activeSpaces = [:] model.reconcile(state, active: true) #expect(model.current == nil) - try model.receive(notice, explicitlyRequested: true) + #expect(model.pending == [notice]) + let history = model.history + model.reconcile(scene(), active: true) + #expect(model.current == notice) + #expect(model.history == history) model.reconcile(scene(), active: false) #expect(model.current == nil) } @@ -194,6 +199,120 @@ struct FeedbackTests { #expect(menu.items.allSatisfy { $0.keyEquivalent.isEmpty }) } + @Test func repeatedIdenticalReportsKeepTheNoticeAndRefreshOnlyItsDeadline() async throws { + let model = FeedbackModel() + var speech: [String] = [] + var sounds = 0 + let controller = FeedbackController( + model: model, sensory: FeedbackSensory(playSound: { sounds += 1 }, performHaptic: {}), + announce: { speech.append($0) }, dismissDelay: .seconds(1), + onFailure: { Issue.record($0) }) + defer { controller.stop() } + controller.update(state: scene(), configuration: MotionConfiguration(sound: true), active: true) + try controller.receive(.maximumSizeReached, state: scene()) + let notice = try #require(model.current) + let panel = try #require(NSApplication.shared.windows.first { $0.title == notice.title }) + let content = try #require(panel.contentView) + try await Task.sleep(for: .milliseconds(600)) + for _ in 0..<40 { try controller.receive(.maximumSizeReached, state: scene()) } + #expect(model.current?.id == notice.id) + #expect(model.recent.count == 1) + #expect(panel.contentView === content) + #expect(speech == [notice.title]) + let expectedSound = NSWorkspace.shared.accessibilityDisplayShouldReduceMotion ? 0 : 1 + #expect(sounds == expectedSound) + try await Task.sleep(for: .milliseconds(600)) + #expect(controller.isVisible) + try await Task.sleep(for: .milliseconds(600)) + #expect(!controller.isVisible) + try controller.receive(.maximumSizeReached, state: scene()) + #expect(model.current?.id != notice.id) + #expect(speech.count == 2) + #expect(sounds == expectedSound * 2) + } + + @Test func differentKindsAndCountsStartNewNotices() throws { + let model = FeedbackModel() + for report in [Report.maximumSizeReached, .minimumSizeReached, .retiled(moved: 1), .retiled(moved: 2)] { + let previous = model.current?.id + try model.receive(#require(FeedbackNotice.map(report, state: scene()).first)) + #expect(model.current?.id != previous) + #expect(model.pending.count == 1) + } + } + + @Test func queuedNoticesAreAnnouncedAndSoundedOnlyWhenShown() throws { + let model = FeedbackModel() + var speech: [String] = [] + var sounds = 0 + let controller = FeedbackController( + model: model, sensory: FeedbackSensory(playSound: { sounds += 1 }, performHaptic: {}), + announce: { speech.append($0) }, onFailure: { Issue.record($0) }) + defer { controller.stop() } + controller.update(state: scene(), configuration: MotionConfiguration(sound: true), active: true) + try controller.receive(.cannotFit([WindowID(rawValue: 1)]), state: scene()) + let room = try #require(model.current) + for _ in 0..<10 { try controller.receive(.retiled(moved: 3), state: scene()) } + #expect(speech.count == 1) + #expect(model.pending.count == 2) + let expectedSound = NSWorkspace.shared.accessibilityDisplayShouldReduceMotion ? 0 : 1 + #expect(sounds == expectedSound) + model.dismiss(room.id) + #expect(speech.count == 2) + #expect(speech.last == "Retiled 3 windows.") + #expect(sounds == expectedSound * 2) + } + + @Test func aHiddenCardThatClosesDoesNotReturn() throws { + let model = FeedbackModel() + let notice = try roomNotice() + try model.receive(notice) + var state = scene() + state.activeSpaces = [:] + model.reconcile(state, active: true) + state.windows[notice.window!] = nil + model.reconcile(state, active: true) + #expect(model.pending.isEmpty) + model.reconcile(scene(), active: true) + #expect(model.current == nil) + } + + @Test func secureInputMenuNamesOnlyTheProvidedOwner() { + let controller = FeedbackController(model: FeedbackModel(), onFailure: { Issue.record($0) }) + defer { controller.stop() } + controller.setSecureInput(true, ownerName: "Fixture") + let menu = NSMenu() + controller.installMenuItems(in: menu, at: 0) + #expect(menu.items.first?.title == FeedbackController.secureInputNotice(ownerName: "Fixture")) + controller.setSecureInput(false) + menu.removeAllItems() + controller.installMenuItems(in: menu, at: 0) + #expect(menu.items.count == 1) + } + + @Test(arguments: [(1, "Use one window here"), (2, "Use 2 windows here"), (5, "Use 5 windows here")]) + func windowCountActionsUseCatalogPlurals(count: Int, title: String) { + #expect(FeedbackText.format("Use %lld windows here", Int64(count)) == title) + } + + @Test(arguments: [ + CGRect(x: 0, y: 72, width: 1512, height: 873), + CGRect(x: 0, y: 48, width: 1920, height: 1008), + CGRect(x: -1920, y: 1100, width: 1920, height: 1056), + CGRect(x: 1512, y: -600, width: 1280, height: 976), + CGRect(x: 0, y: 0, width: 240, height: 180), + ]) + func cardsFitVisibleGeometryBelowNotchesAndAwayFromTopRightBanners(visible: CGRect) { + let frame = FeedbackPlacement.frame(size: CGSize(width: 356, height: 260), visibleFrame: visible) + #expect(visible.contains(frame)) + #expect(frame.minY == visible.minY + 20) + #expect(frame.maxX == visible.maxX - 20) + if visible.height > 600 { + let banner = CGRect(x: visible.maxX - 400, y: visible.maxY - 160, width: 400, height: 160) + #expect(!frame.intersects(banner)) + } + } + private enum TestFailure: Error { case save } private func scene() -> ParcelCore.State { -- knotmirror 0.0.1 From c792b77081de9b0536249dd2fe2a2fc415f63c51 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 11:21:38 -0400 Subject: [PATCH 6/6] Store room reminders beside learned sizes --- Sources/ParcelApp/AppFeedback.swift | 20 +++--- Sources/ParcelApp/NativeAppRuntime.swift | 17 +++-- Sources/ParcelApp/Resources/App.xcstrings | 2 +- Sources/ParcelApp/RoomReminderStore.swift | 40 +++++++++++ Tests/ParcelE2ETests/AppFeedbackTests.swift | 66 ++++++++++++++----- Tests/ParcelE2ETests/FeedbackDropTests.swift | 56 ++++++++++++++++ .../FeedbackEndToEndTests.swift | 28 +++++++- 7 files changed, 195 insertions(+), 34 deletions(-) create mode 100644 Sources/ParcelApp/RoomReminderStore.swift create mode 100644 Tests/ParcelE2ETests/FeedbackDropTests.swift diff --git a/Sources/ParcelApp/AppFeedback.swift b/Sources/ParcelApp/AppFeedback.swift index fa631b6e..8a187906 100644 --- a/Sources/ParcelApp/AppFeedback.swift +++ b/Sources/ParcelApp/AppFeedback.swift @@ -8,14 +8,14 @@ import ParcelUI @MainActor final class AppFeedback { - static let historyKey = "roomReminderHistory" let controller: FeedbackController let model: FeedbackModel private let engine: @MainActor () -> ParcelEngine? private let onFailure: @MainActor (any Error) -> Void init( - defaults: UserDefaults, engine: @escaping @MainActor () -> ParcelEngine?, + store: RoomReminderStore, engine: @escaping @MainActor () -> ParcelEngine?, + sensory: FeedbackSensory = FeedbackSensory(), onFailure: @escaping @MainActor (any Error) -> Void ) { self.engine = engine @@ -23,20 +23,15 @@ final class AppFeedback { var history = FeedbackHistory() var historyError: String? do { - if let object = defaults.object(forKey: Self.historyKey) { - guard let data = object as? Data else { throw FeedbackHistoryError.invalidEntry } - history = try FeedbackHistory(data: data) - } + history = try store.load() } catch { historyError = error.localizedDescription onFailure(error) } model = FeedbackModel( history: history, historyError: historyError, - save: { history in - defaults.set(try JSONEncoder().encode(history), forKey: Self.historyKey) - }) - controller = FeedbackController(model: model, onFailure: onFailure) + save: { try store.save($0) }) + controller = FeedbackController(model: model, sensory: sensory, onFailure: onFailure) controller.onResolve = { [weak self] notice, action in guard let self, let engine = self.engine(), let window = notice.window, let workspace = notice.workspace else { @@ -71,6 +66,7 @@ final class AppFeedback { "options": try options.map(Self.json) ?? .null, "current": try model.current.map(Self.json) ?? .null, "visible": .bool(controller.isVisible), + "key": .bool(controller.isKeyWindow), "recent": try Self.json(model.recent), "room_history": try Self.json(model.history), ]) @@ -81,6 +77,8 @@ final class AppFeedback { try await model.forgetMinimum(args[1]) } else if args == ["reset-history"] { try model.resetHistory() + } else if args == ["show-current"], model.current != nil { + controller.showCurrent() } else if args == ["dismiss"], let current = model.current { model.dismiss(current.id) } else if args.count >= 2, let id = UUID(uuidString: args[0]), @@ -118,7 +116,7 @@ final class AppFeedback { IPCError( code: "invalid_command", message: AppText.string( - "Use feedback list, show-again APP, forget APP, reset-history, dismiss, or ID keep-floating|use-count N|move-to-display DISPLAY." + "Use feedback list, show-current, show-again APP, forget APP, reset-history, dismiss, or ID keep-floating|use-count N|move-to-display DISPLAY." )) } } diff --git a/Sources/ParcelApp/NativeAppRuntime.swift b/Sources/ParcelApp/NativeAppRuntime.swift index 7c4ca2e0..f388a619 100644 --- a/Sources/ParcelApp/NativeAppRuntime.swift +++ b/Sources/ParcelApp/NativeAppRuntime.swift @@ -21,6 +21,7 @@ final class NativeAppRuntime: AppRuntime { private let instance: SingleInstance private let defaults: UserDefaults private let fixtureOnly: Bool + private let feedbackSensory: FeedbackSensory private let makeWindowWorld: (@MainActor () -> any EngineWindowWorld)? private let makeDisplayLink: (@MainActor (DisplayID) throws -> any EngineDisplayLink)? private var world: RestoringWindowWorld? @@ -66,7 +67,8 @@ final class NativeAppRuntime: AppRuntime { init( store: ConfigStore, socketPath: String, defaults: UserDefaults = .standard, fixtureOnly: Bool = false, makeWindowWorld: (@MainActor () -> any EngineWindowWorld)? = nil, - makeDisplayLink: (@MainActor (DisplayID) throws -> any EngineDisplayLink)? = nil + makeDisplayLink: (@MainActor (DisplayID) throws -> any EngineDisplayLink)? = nil, + feedbackSensory: FeedbackSensory = FeedbackSensory() ) { self.store = store self.socketPath = socketPath @@ -75,6 +77,7 @@ final class NativeAppRuntime: AppRuntime { instance = SingleInstance( path: (NSTemporaryDirectory() as NSString).appendingPathComponent("parcel-\(getuid()).app-lock")) self.fixtureOnly = fixtureOnly + self.feedbackSensory = feedbackSensory self.makeWindowWorld = makeWindowWorld self.makeDisplayLink = makeDisplayLink log.failure = { [weak self] error, kind in self?.services.composition?.report(error, kind: kind) } @@ -375,13 +378,19 @@ final class NativeAppRuntime: AppRuntime { : MinimumSizeStore.defaultFileURL) } - private func prepareFeedback() { + func prepareFeedback() { guard feedback == nil else { return } let feedback = AppFeedback( - defaults: defaults, engine: { [weak self] in self?.services.engine }, + store: RoomReminderStore( + fileURL: Self.minimumStore(configURL: store.fileURL, fixtureOnly: fixtureOnly).fileURL + .deletingLastPathComponent().appendingPathComponent("room-reminders.json")), + engine: { [weak self] in self?.services.engine }, sensory: feedbackSensory, onFailure: { [weak self] in self?.services.composition?.report($0, kind: .feedback) }) self.feedback = feedback settings.feedback = feedback.model + feedback.controller.update( + state: services.engine?.snapshot.state ?? State(), + configuration: services.engine?.configuration.motion ?? learningConfiguration.motion, active: true) feedback.controller.setSecureInput(secureInput.isEnabled, ownerName: secureInput.ownerName) } @@ -424,7 +433,7 @@ final class NativeAppRuntime: AppRuntime { drag = monitor } - private func receive(_ feedback: EngineMouseFeedback) { + func receive(_ feedback: EngineMouseFeedback) { switch feedback { case .targetChanged(let target): overlays?.dragChanged(target: target.map { OverlayWindow(id: $0.window.rawValue, frame: $0.frame.cgRect) }) diff --git a/Sources/ParcelApp/Resources/App.xcstrings b/Sources/ParcelApp/Resources/App.xcstrings index e326824c..9c45de1e 100644 --- a/Sources/ParcelApp/Resources/App.xcstrings +++ b/Sources/ParcelApp/Resources/App.xcstrings @@ -3,7 +3,7 @@ "strings" : { "Feedback needs attention. Open Feedback from the menu to review room reminders." : {"localizations": {"en": {"stringUnit": {"state": "translated", "value": "Feedback needs attention. Open Feedback from the menu to review room reminders."}}}}, "That room reminder is no longer available. Check the window and its Space, then try again." : {"localizations": {"en": {"stringUnit": {"state": "translated", "value": "That room reminder is no longer available. Check the window and its Space, then try again."}}}}, - "Use feedback list, show-again APP, forget APP, reset-history, dismiss, or ID keep-floating|use-count N|move-to-display DISPLAY." : {"localizations": {"en": {"stringUnit": {"state": "translated", "value": "Use feedback list, show-again APP, forget APP, reset-history, dismiss, or ID keep-floating|use-count N|move-to-display DISPLAY."}}}}, + "Use feedback list, show-current, show-again APP, forget APP, reset-history, dismiss, or ID keep-floating|use-count N|move-to-display DISPLAY." : {"localizations": {"en": {"stringUnit": {"state": "translated", "value": "Use feedback list, show-current, show-again APP, forget APP, reset-history, dismiss, or ID keep-floating|use-count N|move-to-display DISPLAY."}}}}, "The focus mode could not change. Focus a window and try again." : {"localizations": {"en": {"stringUnit": {"state": "translated", "value": "The focus mode could not change. Focus a window and try again."}}}}, "Compositor dimming could not be verified. No peek is using the privacy overlay." : {"localizations": {"en": {"stringUnit": {"state": "translated", "value": "Compositor dimming could not be verified. No peek is using the privacy overlay."}}}}, "Focus is on." : {"localizations": {"en": {"stringUnit": {"state": "translated", "value": "Focus is on."}}}}, diff --git a/Sources/ParcelApp/RoomReminderStore.swift b/Sources/ParcelApp/RoomReminderStore.swift new file mode 100644 index 00000000..6d7f9b5b --- /dev/null +++ b/Sources/ParcelApp/RoomReminderStore.swift @@ -0,0 +1,40 @@ +import Foundation +import ParcelPlatform +import ParcelUI + +struct RoomReminderStore: Sendable { + static var defaultFileURL: URL { + MinimumSizeStore.defaultFileURL.deletingLastPathComponent().appendingPathComponent("room-reminders.json") + } + + let fileURL: URL + + init(fileURL: URL = Self.defaultFileURL) { + self.fileURL = fileURL + } + + func load() throws -> FeedbackHistory { + guard fileURL.isFileURL else { throw CocoaError(.fileReadUnsupportedScheme) } + let data: Data + do { + data = try Data(contentsOf: fileURL) + } catch let error as NSError + where error.domain == NSCocoaErrorDomain + && (error.code == CocoaError.fileReadNoSuchFile.rawValue + || error.code == CocoaError.fileNoSuchFile.rawValue) + { + return FeedbackHistory() + } + return try FeedbackHistory(data: data) + } + + func save(_ history: FeedbackHistory) throws { + guard fileURL.isFileURL else { throw CocoaError(.fileWriteUnsupportedScheme) } + let encoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + let data = try encoder.encode(history) + try FileManager.default.createDirectory( + at: fileURL.deletingLastPathComponent(), withIntermediateDirectories: true) + try data.write(to: fileURL, options: .atomic) + } +} diff --git a/Tests/ParcelE2ETests/AppFeedbackTests.swift b/Tests/ParcelE2ETests/AppFeedbackTests.swift index 78b05e1c..80358f60 100644 --- a/Tests/ParcelE2ETests/AppFeedbackTests.swift +++ b/Tests/ParcelE2ETests/AppFeedbackTests.swift @@ -75,14 +75,13 @@ struct AppFeedbackTests { } @Test func feedbackHistoryLoadsAndExplicitResetReplacesIt() async throws { - let name = "test.feedback.\(UUID().uuidString)" - let defaults = try #require(UserDefaults(suiteName: name)) - defer { defaults.removePersistentDomain(forName: name) } + let store = temporaryStore() + defer { removeStore(store) } var history = FeedbackHistory() history.record(bundleID: "test.fixture", applicationName: "Fixture", at: Date()) - defaults.set(try JSONEncoder().encode(history), forKey: AppFeedback.historyKey) + try store.save(history) let app = AppFeedback( - defaults: defaults, engine: { nil }, onFailure: { _ in Issue.record("Unexpected feedback failure") }) + store: store, engine: { nil }, onFailure: { _ in Issue.record("Unexpected feedback failure") }) defer { app.controller.stop() } #expect(app.model.history == history) guard case .object(let listing) = try await app.run(["list"]) else { @@ -92,27 +91,62 @@ struct AppFeedbackTests { #expect(listing["current"] == .null) #expect(listing["options"] == .null) #expect(listing["visible"] == .bool(false)) + #expect(listing["key"] == .bool(false)) #expect(listing["recent"] == .array([])) #expect(listing["room_history"] != nil) #expect(try await app.run(["reset-history"]) == .object(["accepted": .bool(true)])) - let data = try #require(defaults.data(forKey: AppFeedback.historyKey)) - #expect(try FeedbackHistory(data: data).entries.isEmpty) + #expect(try store.load().entries.isEmpty) #expect(app.model.history.entries.isEmpty) } @Test func corruptHistoryIsSurfacedAndRetainedUntilExplicitReset() async throws { - let name = "test.feedback.\(UUID().uuidString)" - let defaults = try #require(UserDefaults(suiteName: name)) - defer { defaults.removePersistentDomain(forName: name) } - defaults.set("bad history", forKey: AppFeedback.historyKey) + let store = temporaryStore() + defer { removeStore(store) } + try store.save(FeedbackHistory()) + let corrupt = Data("bad history".utf8) + try corrupt.write(to: store.fileURL) var failures = 0 - let app = AppFeedback(defaults: defaults, engine: { nil }, onFailure: { _ in failures += 1 }) + let app = AppFeedback(store: store, engine: { nil }, onFailure: { _ in failures += 1 }) defer { app.controller.stop() } #expect(failures == 1) #expect(app.model.historyError != nil) - #expect(defaults.string(forKey: AppFeedback.historyKey) == "bad history") + #expect(try Data(contentsOf: store.fileURL) == corrupt) _ = try await app.run(["reset-history"]) #expect(app.model.historyError == nil) + #expect(try store.load().entries.isEmpty) + } + + @Test func reminderStoreUsesApplicationSupportBesideLearnedSizes() { + #expect( + RoomReminderStore.defaultFileURL.deletingLastPathComponent() + == MinimumSizeStore.defaultFileURL.deletingLastPathComponent()) + #expect(RoomReminderStore.defaultFileURL.lastPathComponent == "room-reminders.json") + } + + @Test func missingReminderStoreStartsEmptyButInvalidAndUnwritableStoresThrow() throws { + let store = temporaryStore() + #expect(try store.load() == FeedbackHistory()) + try store.save(FeedbackHistory()) + defer { removeStore(store) } + let nested = RoomReminderStore(fileURL: store.fileURL.appendingPathComponent("blocked.json")) + #expect(throws: (any Error).self) { try nested.save(FeedbackHistory()) } + let directory = RoomReminderStore(fileURL: store.fileURL.deletingLastPathComponent()) + #expect(throws: (any Error).self) { try directory.load() } + try Data(#"{"schemaVersion":9,"entries":{}}"#.utf8).write(to: store.fileURL) + #expect(throws: FeedbackHistoryError.unsupportedVersion(9)) { try store.load() } + } + + private func temporaryStore() -> RoomReminderStore { + RoomReminderStore( + fileURL: FileManager.default.temporaryDirectory + .appendingPathComponent("test-feedback-\(UUID().uuidString)") + .appendingPathComponent("room-reminders.json")) + } + + private func removeStore(_ store: RoomReminderStore) { + do { try FileManager.default.removeItem(at: store.fileURL.deletingLastPathComponent()) } catch { + Issue.record(error) + } } @Test(arguments: [ @@ -120,11 +154,9 @@ struct AppFeedbackTests { [UUID().uuidString, "keep-floating"], ]) func feedbackRejectsUnknownOrStaleActions(arguments: [String]) async throws { - let name = "test.feedback.\(UUID().uuidString)" - let defaults = try #require(UserDefaults(suiteName: name)) - defer { defaults.removePersistentDomain(forName: name) } + let store = temporaryStore() let app = AppFeedback( - defaults: defaults, engine: { nil }, onFailure: { _ in Issue.record("Unexpected feedback failure") }) + store: store, engine: { nil }, onFailure: { _ in Issue.record("Unexpected feedback failure") }) defer { app.controller.stop() } await #expect(throws: IPCError.self) { try await app.run(arguments) } } diff --git a/Tests/ParcelE2ETests/FeedbackDropTests.swift b/Tests/ParcelE2ETests/FeedbackDropTests.swift new file mode 100644 index 00000000..02decf16 --- /dev/null +++ b/Tests/ParcelE2ETests/FeedbackDropTests.swift @@ -0,0 +1,56 @@ +import AppKit +import Foundation +import ParcelConfig +import ParcelCore +import ParcelEngine +import ParcelUI +import Testing + +@testable import ParcelApp + +@MainActor +struct FeedbackDropTests { + @Test(arguments: [false, true], [false, true]) + func runtimeDropRouteReachesSensoryFeedbackButRefusalDoesNot(motion: Bool, sound: Bool) async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + let configurationURL = directory.appendingPathComponent("config.toml") + var configuration = ParcelConfiguration.defaults + configuration.motion = MotionConfiguration(enabled: motion, sound: sound) + let engine = try ParcelEngine( + world: RecordingWorld(), clock: SystemEngineClock(), scheduler: RunLoopEngineScheduler(), + displayLink: { _ in throw AppFailure(message: "No display is available in this test") }, + announcer: DropAnnouncer(), log: DropLog(), configuration: configuration, + trace: nil, reduceMotionSource: nil) + var sounds = 0 + var haptics = 0 + let runtime = NativeAppRuntime( + store: ConfigStore(fileURL: configurationURL), + socketPath: directory.appendingPathComponent("ipc.sock").path, + fixtureOnly: true, + feedbackSensory: FeedbackSensory(playSound: { sounds += 1 }, performHaptic: { haptics += 1 })) + runtime.services.engine = engine + runtime.prepareFeedback() + runtime.receive(.targetChanged(nil)) + runtime.receive(.refused(.right)) + #expect(sounds == 0) + #expect(haptics == 0) + runtime.receive(.dropped(velocity: Point(x: 20, y: 0))) + let enabled = motion && !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion + #expect(sounds == (enabled && sound ? 1 : 0)) + #expect(haptics == (enabled ? 1 : 0)) + runtime.receive(.refused(.left)) + #expect(sounds == (enabled && sound ? 1 : 0)) + #expect(haptics == (enabled ? 1 : 0)) + await runtime.stopShell() + } +} + +@MainActor +private final class DropAnnouncer: EngineAnnouncer { + func announce(_ announcement: Announcement) {} +} + +@MainActor +private final class DropLog: EngineLogSink { + func record(_ diagnostic: EngineDiagnostic) {} +} diff --git a/Tests/ParcelE2ETests/FeedbackEndToEndTests.swift b/Tests/ParcelE2ETests/FeedbackEndToEndTests.swift index 43b2b443..3a21c6b2 100644 --- a/Tests/ParcelE2ETests/FeedbackEndToEndTests.swift +++ b/Tests/ParcelE2ETests/FeedbackEndToEndTests.swift @@ -28,10 +28,13 @@ extension RealAppEndToEndTests { let target = try #require(notice.window) #expect(ready.windows.contains { $0.number == target.rawValue }) #expect(NSWorkspace.shared.frontmostApplication?.processIdentifier == fixture.process.processIdentifier) - let focused = try await fixture.snapshot().focusedWindow + let focused = try #require(await fixture.snapshot().focusedWindow) + #expect(try await feedbackSnapshot(session).key == false) var previousFrames: [UInt32: Rect] = [:] var stableSince = ContinuousClock.now try await waitUntil("minimum-size writes settle before resolving the card") { + #expect(try await feedbackSnapshot(session).key == false) + #expect(try await fixture.snapshot().focusedWindow == focused) let frames = try session.frames(for: fixture) if frames != previousFrames { previousFrames = frames @@ -76,6 +79,28 @@ extension RealAppEndToEndTests { } } + @Test func explicitlyOpenedCardReturnsKeyFocusToTheFixtureWhenDismissed() async throws { + try await withSession { session in + let (fixture, _) = try await session.addFixture(arguments: ["--title", "Feedback Focus Fixture"]) + try await session.startApp() + _ = try await session.settledWindows(for: fixture, count: 1) + let focused = try #require(await fixture.snapshot().focusedWindow) + try await session.command("retile") + #expect(try await feedbackSnapshot(session).key == false) + try await session.command("feedback", "show-current") + try await waitUntil("the explicitly opened card becomes key") { + try await feedbackSnapshot(session).key + } + try await session.command("feedback", "dismiss") + try await waitUntil("the fixture regains keyboard focus") { + let feedback = try await feedbackSnapshot(session) + let snapshot = try await fixture.snapshot() + return !feedback.key && !feedback.visible && snapshot.focusedWindow == focused + && NSWorkspace.shared.frontmostApplication?.processIdentifier == fixture.process.processIdentifier + } + } + } + @Test func retileOfSettledFixtureReportsUnchangedVisibly() async throws { try await withSession { session in let (fixture, _) = try await session.addFixture(arguments: ["--title", "Retile Feedback Fixture"]) @@ -95,6 +120,7 @@ private struct FeedbackSnapshot: Decodable { let current: FeedbackNotice? let options: RoomOptions? let visible: Bool + let key: Bool } @MainActor -- knotmirror 0.0.1