import AppKit import Foundation import ParcelConfig import ParcelCore import ParcelEngine import ParcelPlatform import Testing @testable import ParcelApp @testable import ParcelTestSupport extension AppKitTestSuite { @MainActor struct AppMouseControlTests { @Test func disabledHoverInstallsNothingAndNeverChecksSecureInput() throws { let engine = try ParcelEngine( world: RecordingWorld(), clock: SystemEngineClock(), scheduler: RunLoopEngineScheduler(), displayLink: { _ in throw AppFailure(message: "This test never starts a display link") }, announcer: MouseTestAnnouncer(), log: MouseTestLog(), trace: nil, reduceMotionSource: nil) var checks = 0 let hover = AppHoverFocus( engine: { engine }, allowed: { checks += 1 return true }, failure: { Issue.record($0) }) try hover.start() try hover.synchronize() for _ in 0..<100 { hover.receive(.mouseMoved) } #expect(!hover.isRunning) #expect(checks == 0) hover.stop() } @Test func runtimeStopPreventsHoverResynchronizationUntilInputRestarts() throws { _ = NSApplication.shared let suite = "dev.vinnymac.parcel.mouse-lifecycle.\(UUID())" let defaults = try #require(UserDefaults(suiteName: suite)) defer { defaults.removePersistentDomain(forName: suite) } let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) let runtime = NativeAppRuntime( store: ConfigStore(fileURL: directory.appendingPathComponent("parcel.toml")), socketPath: directory.appendingPathComponent("ipc.sock").path, defaults: defaults, fixtureOnly: true) var configuration = ParcelConfiguration.defaults configuration.mouse.focusFollowsMouse = true let engine = try ParcelEngine( world: RecordingWorld(), clock: SystemEngineClock(), scheduler: RunLoopEngineScheduler(), displayLink: { _ in throw AppFailure(message: "This test never starts a display link") }, announcer: MouseTestAnnouncer(), log: MouseTestLog(), configuration: configuration, trace: nil, reduceMotionSource: nil) runtime.services.engine = engine defer { do { try runtime.stopInput() } catch { Issue.record(error) } } #expect(engine.snapshot.state.hoverFocusEnabled) try runtime.synchronizeHoverFocus() #expect(!runtime.isHoverFocusRunning) var starts = 0 try runtime.startDragMonitor(start: { _ in starts += 1 }) #expect(runtime.isHoverFocusRunning) try runtime.stopInput() #expect(!runtime.isHoverFocusRunning) #expect(engine.snapshot.state.hoverFocusEnabled) try runtime.synchronizeHoverFocus() #expect(!runtime.isHoverFocusRunning) try runtime.applyConfiguration(configuration) #expect(!runtime.isHoverFocusRunning) try runtime.startDragMonitor(start: { _ in starts += 1 }) #expect(runtime.isHoverFocusRunning) #expect(starts == 2) configuration.mouse.focusFollowsMouse = false try runtime.applyConfiguration(configuration) #expect(!runtime.isHoverFocusRunning) configuration.mouse.focusFollowsMouse = true try runtime.applyConfiguration(configuration) #expect(runtime.isHoverFocusRunning) } @Test func inputTimeoutExplainsWhyControlsStopped() { let notices = AppNotices() let report = notices.report(InputError.tapTimedOut, kind: .input) #expect( report.message == "Mouse controls stopped after an input timeout. Restart Parcel when it is responsive." ) #expect(notices.counts[.input] == 1) } @Test func localizedFailuresRemainIndependentOfInputTimeoutGuidance() { let notices = AppNotices() let timeout = notices.report(InputError.tapTimedOut, kind: .input) let first = notices.report(AppFailure(message: "First rule failure"), kind: .internalFailure) let second = notices.report(AppFailure(message: "Second rule failure"), kind: .internalFailure) let input = notices.report(InputError.tapEnableFailed, kind: .input) #expect( timeout.message == "Mouse controls stopped after an input timeout. Restart Parcel when it is responsive.") #expect(first.message == "First rule failure") #expect(second.message == "Second rule failure") #expect(input.message == AppNotices.Kind.input.message) #expect(notices.shortcutRepairActions.isEmpty) #expect(notices.counts[.input] == 2) #expect(notices.counts[.internalFailure] == 2) } @Test func hoverSwitchHasNoDisconnectedSilentFallback() async throws { let services = EngineShellServices() await #expect(throws: AppFailure.self) { try await services.send(.toggleHoverFocus) } var toggles = 0 services.toggleHoverFocus = { toggles += 1 } try await services.send(.toggleHoverFocus) #expect(toggles == 1) services.toggleHoverFocus = { throw AppFailure(message: "Can't save") } await #expect(throws: AppFailure.self) { try await services.send(.toggleHoverFocus) } } @Test func ipcRoutesHoverFocusToPersistentAppSwitch() async throws { let services = EngineShellServices() var toggles = 0 services.toggleHoverFocus = { toggles += 1 } let handler = AppIPCHandler(services: services, configPath: "/tmp/config.toml", permission: { false }) _ = try await handler.run(command: "hover-focus-toggle", args: []) #expect(toggles == 1) let config = try await handler.query(.config) guard case .object(let values) = config, case .object(let mouse) = values["mouse"] else { Issue.record("Expected mouse configuration") return } #expect(mouse["focus-follows-mouse"] == .bool(false)) #expect(mouse["focus-delay"] == .number(0.35)) #expect(!mouse.keys.contains { $0.contains("_") }) } @Test func cursorWarpsCannotActivateAStaleHoverCandidate() { #expect(AppHoverFocus.remainsSettled(at: Point(x: 1, y: 1), since: Point())) #expect(!AppHoverFocus.remainsSettled(at: Point(x: 100), since: Point())) #expect(!AppHoverFocus.remainsSettled(at: Point(x: .nan), since: Point())) } @Test func transparentChromeDoesNotBlockHoverButInteractiveWindowsDo() { let chrome = WindowID(rawValue: 99) let window = WindowID(rawValue: 1) let frames = [ WindowFrame(window: chrome, frame: Rect(width: 800, height: 600)), WindowFrame(window: window, frame: Rect(x: 100, y: 100, width: 300, height: 200)), ] let point = Point(x: 200, y: 200) #expect(AppHoverFocus.frontmostWindow(at: point, frames: frames, ignoring: [chrome]) == window) #expect(AppHoverFocus.frontmostWindow(at: point, frames: frames, ignoring: []) == chrome) #expect(AppHoverFocus.frontmostWindow(at: Point(x: 900), frames: frames, ignoring: [chrome]) == nil) } @Test func overlappingFloatingWindowsCanTargetTheNonfocusedWindow() { let display = DisplayID(rawValue: "floating") let key = WorkspaceKey(display: display, space: SpaceID(rawValue: 1)) let first = WindowID(rawValue: 1) let second = WindowID(rawValue: 2) let frame = Rect(x: 100, y: 100, width: 300, height: 200) let app = AppID(pid: 42, bundleID: "fixture") let state = State( displays: [Display(id: display, frame: Rect(width: 800, height: 600))], activeSpaces: [display: key.space], workspaces: [key: Workspace(key: key, order: [first, second])], windows: [ first: ManagedWindow(id: first, app: app, isFloating: true), second: ManagedWindow(id: second, app: app, isFloating: true), ], focusedWindow: first, observedFrames: [first: frame, second: frame]) #expect(AppHoverFocus.target(at: frame.center, state: state)?.window == second) #expect(AppHoverFocus.target(for: second, state: state)?.workspace == key) #expect(AppHoverFocus.target(for: first, state: state) == nil) } @Test func pointerTargetsOnlyVisibleKnownDisplaySpaces() { let display = DisplayID(rawValue: "known") let key = WorkspaceKey(display: display, space: SpaceID(rawValue: 1)) let window = WindowID(rawValue: 1) let frame = Rect(x: 100, y: 100, width: 300, height: 200) var state = State( displays: [Display(id: display, frame: Rect(width: 1000, height: 800))], activeSpaces: [display: key.space], workspaces: [key: Workspace(key: key, order: [window])], windows: [window: ManagedWindow(id: window, app: AppID(pid: 42, bundleID: "fixture"))], observedFrames: [window: frame]) #expect(AppHoverFocus.target(at: frame.center, state: state)?.window == window) state.focusedWindow = window #expect(AppHoverFocus.target(at: frame.center, state: state) == nil) state.focusedWindow = nil state.activeSpaces[display] = SpaceID(rawValue: 2) #expect(AppHoverFocus.target(at: frame.center, state: state) == nil) state.activeSpaces[display] = key.space state.displays.removeAll() #expect(AppHoverFocus.target(at: frame.center, state: state) == nil) } } } @MainActor private final class MouseTestAnnouncer: EngineAnnouncer { func announce(_ announcement: Announcement) {} } @MainActor private final class MouseTestLog: EngineLogSink { func record(_ diagnostic: EngineDiagnostic) {} }