import CoreGraphics import Foundation import ParcelCore import ParcelIPC import ParcelPlatform import Testing @testable import ParcelApp @testable import ParcelTestSupport @MainActor @Suite("Fixture mouse input") struct AppFixtureMouseTests { private let environment = ["PARCEL_E2E": "1"] @Test(arguments: [[:], ["PARCEL_E2E": "0"], ["PARCEL_E2E": "true"], ["PARCEL_E2E": "1 "]]) func requestsRequireHarnessMode(_ environment: [String: String]) { #expect(throws: IPCError.self) { try AppFixtureMouseRequest(arguments: ["restore"], environment: environment) } } @Test func requestsParseEveryActionAndSupportedModifiers() throws { let flags: CGEventFlags = [.maskCommand, .maskAlternate, .maskControl, .maskShift] let down = try request(["down", "1", "100.5", "80", String(flags.rawValue), "2"]) #expect(down.action == .down && down.window == 1 && down.point == CGPoint(x: 100.5, y: 80)) #expect(down.flags == flags && down.clickCount == 2 && down.button == .left) #expect(try request(["down", "1", "100", "80", "0", "1", "right"]).button == .right) let drag = try request(["drag", "-100", "0", "0"]) #expect(drag.action == .drag && drag.window == nil && drag.point == CGPoint(x: -100, y: 0)) #expect(drag.flags.isEmpty && drag.clickCount == 1) let up = try request(["up", String(CGEventFlags.maskCommand.rawValue), "1"]) #expect(up.action == .up && up.flags == .maskCommand && up.point == nil) for action in ["escape", "restore"] { let parsed = try request([action]) #expect(parsed.action.rawValue == action && parsed.window == nil && parsed.point == nil) } } @Test(arguments: [ [], ["unknown"], ["restore", "extra"], ["escape", "53"], ["down"], ["down", "1", "100", "80", "0", "1", "middle"], ["down", "1", "100", "80", "0", "1", "right", "extra"], ["down", "0", "100", "100", "0", "1"], ["down", "4294967296", "100", "100", "0", "1"], ["down", "1", "nan", "100", "0", "1"], ["down", "1", "100", "inf", "0", "1"], ["down", "1", "100001", "100", "0", "1"], ["down", "1", "100", "100", "0", "0"], ["down", "1", "100", "100", "0", "3"], ["down", "1", "100", "100", "-1", "1"], ["down", "1", "100", "100", "65536", "1"], ["drag", "100", "100"], ["drag", "100", "100", "0", "extra"], ["drag", "-100001", "100", "0"], ["up", "0"], ["up", "0", "1", "extra"], ["up", "18446744073709551616", "1"], ["down", String(repeating: "0", count: 33), "100", "100", "0", "1"], ]) func requestsRejectMalformedOrUnboundedInput(_ arguments: [String]) { #expect(throws: IPCError.self) { try request(arguments) } } @Test func geometryAllowsFixtureTilesAndSharedGapsButNotOutsideClicks() throws { let state = scene() let frame = try #require(state.frames[WindowID(rawValue: 1)]) let gap = CGPoint(x: frame.maxX + 6, y: frame.center.yCoordinate) let geometry = try AppFixtureMouseGeometry(window: 1, point: gap, state: state) #expect(geometry.window == 1 && geometry.pid == 123 && geometry.point == gap) let last = try #require(state.frames[WindowID(rawValue: 3)]) try geometry.validate(CGPoint(x: last.center.xCoordinate, y: last.center.yCoordinate)) #expect(throws: IPCError.self) { try AppFixtureMouseGeometry(window: 1, point: CGPoint(x: -1, y: 100), state: state) } #expect(throws: IPCError.self) { try AppFixtureMouseGeometry(window: 1, point: CGPoint(x: last.center.xCoordinate, y: 100), state: state) } #expect(throws: IPCError.self) { try geometry.validate(CGPoint(x: Double.nan, y: 100)) } #expect(throws: IPCError.self) { try geometry.validate(CGPoint(x: 1201, y: 100)) } } @Test(arguments: ["missing", "floating", "mixedOwner", "inactive", "missingFrame", "invalidFrame", "zeroPID"]) func geometryRejectsUnsafeScenes(_ mutation: String) { var state = scene() switch mutation { case "missing": state.windows.removeValue(forKey: WindowID(rawValue: 1)) case "floating": state.windows[WindowID(rawValue: 2)]?.isFloating = true case "mixedOwner": state.windows[WindowID(rawValue: 2)]?.app = AppID(pid: 456, bundleID: "unrelated") case "inactive": state.activeSpaces = [:] case "missingFrame": state.frames.removeValue(forKey: WindowID(rawValue: 2)) case "invalidFrame": state.frames[WindowID(rawValue: 2)] = Rect(x: .infinity, y: 0, width: 400, height: 800) case "zeroPID": state.windows[WindowID(rawValue: 1)]?.app = AppID(pid: 0, bundleID: "fixture") default: Issue.record("Unexpected scene mutation") } #expect(throws: IPCError.self) { try AppFixtureMouseGeometry(window: 1, point: CGPoint(x: 100, y: 100), state: state) } } @Test func floatingAndKnownDisplaysAreAllowedButDisplayGapsAreNot() throws { var state = scene() let window = WindowID(rawValue: 1) let key = try #require(state.workspace(containing: window)) state = reduce( state, .gestureCommitted( .floatingFrame(window: window, workspace: key, frame: Rect(x: 100, y: 100, width: 300, height: 200)) ) ).0 let extra = DisplayID(rawValue: "mouse-second") state.displays[extra] = Display(id: extra, frame: Rect(x: -1400, width: 1200, height: 800)) state.activeSpaces[extra] = SpaceID(rawValue: 2) state.displays[key.display]?.physicalFrame = Rect(x: 0, y: -30, width: 1200, height: 900) let geometry = try AppFixtureMouseGeometry(window: 1, point: CGPoint(x: 150, y: 150), state: state) try geometry.validate(CGPoint(x: -1300, y: 100)) try geometry.validate(CGPoint(x: 150, y: -20)) try geometry.validate(CGPoint(x: 150, y: 850)) #expect(throws: IPCError.self) { try geometry.validate(CGPoint(x: 150, y: -40)) } #expect(throws: IPCError.self) { try geometry.validate(CGPoint(x: -100, y: 100)) } #expect(throws: IPCError.self) { try geometry.validate(CGPoint(x: -1500, y: 100)) } } @Test func rightDragAndTeardownKeepTheOriginalButton() async throws { let recorder = MouseRecorder() let input = try recorder.input() try await input.post(request(["down", "1", "100", "100", "0", "1", "right"]), state: scene()) try await input.post(request(["drag", "900", "300", "0"]), state: scene()) try input.restore() #expect(recorder.events.first?.type == .rightMouseDown) #expect(recorder.events.dropFirst().dropLast().allSatisfy { $0.type == .rightMouseDragged }) #expect(recorder.events.last?.type == .rightMouseUp) #expect(recorder.restored.count == 1) } @Test func postingUsesChosenOwnerLiveModifiersDeltasAndClickCounts() async throws { let recorder = MouseRecorder() let input = try recorder.input() try await input.post(request(["down", "1", "100", "100", "0", "2"]), state: scene()) try await input.post( request(["drag", "900", "300", String(CGEventFlags.maskCommand.rawValue)]), state: scene()) try await input.post(request(["up", "0", "2"]), state: scene()) try input.restore() let events = recorder.events #expect(events.count == 10) let first = try #require(events.first) let last = try #require(events.last) #expect(first.type == .leftMouseDown && first.flags.isEmpty && first.clicks == 2) #expect(last.type == .leftMouseUp && last.flags.isEmpty && last.clicks == 2 && last.pressure == 0) #expect(last.point == CGPoint(x: 900, y: 300)) #expect(events.allSatisfy { $0.pid == 123 && $0.window == 0 && $0.handlingWindow == 0 }) #expect( events.dropFirst().dropLast().allSatisfy { $0.type == .leftMouseDragged && $0.flags == .maskCommand && $0.dx == 100 && $0.dy == 25 && $0.pressure == 1 }) #expect(recorder.restored == [CGPoint(x: 10, y: 20)]) } @Test func escapeAndHeldMouseAreReleasedBeforeRestoringOnce() async throws { let recorder = MouseRecorder() let input = try recorder.input() try await input.post(request(["down", "1", "100", "100", "0", "1"]), state: scene()) try await input.post(request(["escape"]), state: scene()) try input.restore() try input.restore() #expect(recorder.events.map(\.type) == [.leftMouseDown, .keyDown, .keyUp, .leftMouseUp]) #expect(recorder.events.allSatisfy { $0.pid == 123 }) #expect(recorder.restored.count == 1) await #expect(throws: IPCError.self) { try await input.post(request(["down", "1", "100", "100", "0", "1"]), state: scene()) } #expect(recorder.events.count == 4) } @Test(arguments: ["drag", "up", "escape"]) func gesturesRequireMouseDown(_ action: String) async throws { let recorder = MouseRecorder() let input = try recorder.input() let arguments = action == "drag" ? ["drag", "300", "100", "0"] : (action == "up" ? ["up", "0", "1"] : ["escape"]) await #expect(throws: IPCError.self) { try await input.post(request(arguments), state: scene()) } #expect(recorder.events.isEmpty) } @Test(arguments: ["unrelatedHit", "lostFocus", "outsideDrag", "secondDown"]) func unsafePostingReleasesInputWithoutSendingTheRejectedEvent(_ failure: String) async throws { let recorder = MouseRecorder() if failure == "unrelatedHit" { recorder.hit = DragWindow(pid: 456, windowNumber: 99) } let input = try recorder.input() if failure == "unrelatedHit" { await #expect(throws: IPCError.self) { try await input.post(request(["down", "1", "100", "100", "0", "1"]), state: scene()) } #expect(recorder.events.isEmpty) } else { try await input.post(request(["down", "1", "100", "100", "0", "1"]), state: scene()) if failure == "lostFocus" { recorder.frontmost = false } let arguments = failure == "secondDown" ? ["down", "1", "100", "100", "0", "1"] : ["drag", failure == "outsideDrag" ? "2000" : "900", "300", "0"] await #expect(throws: IPCError.self) { try await input.post(request(arguments), state: scene()) } #expect(recorder.events.map(\.type) == [.leftMouseDown, .leftMouseUp]) } #expect(recorder.restored.count == 1) } @Test(arguments: [false, true]) func cancellationDuringEscapeReleasesBothKeysAndButton(afterKeyUp: Bool) async throws { let recorder = MouseRecorder() let suspended = AsyncStream.makeStream() defer { suspended.continuation.finish() } let input = try recorder.input( sampleDelay: .milliseconds(40), sampleSleep: { duration in #expect(duration == .milliseconds(40)) if afterKeyUp && recorder.events.last?.type == .keyDown { return } suspended.continuation.yield(()) try await suspendFixtureInputUntilCancellation() }, idleSleep: { _ in try await suspendFixtureInputUntilCancellation() }) try await input.post(request(["down", "1", "100", "100", "0", "1"]), state: scene()) let task = Task { try await input.post(request(["escape"]), state: scene()) } defer { task.cancel() } try await waitForTestEvent(suspended.stream, label: "Escape sample suspension") #expect( recorder.events.map(\.type) == (afterKeyUp ? [.leftMouseDown, .keyDown, .keyUp] : [.leftMouseDown, .keyDown])) #expect(recorder.restored.isEmpty) task.cancel() await #expect(throws: CancellationError.self) { try await task.value } #expect(recorder.events.map(\.type) == [.leftMouseDown, .keyDown, .keyUp, .leftMouseUp]) #expect(recorder.restored.count == 1) } @Test func cancellationDuringDragReleasesButtonWithoutSendingRemainingSamples() async throws { let recorder = MouseRecorder() let suspended = AsyncStream.makeStream() defer { suspended.continuation.finish() } let input = try recorder.input( sampleDelay: .milliseconds(40), sampleSleep: { duration in #expect(duration == .milliseconds(40)) suspended.continuation.yield(()) try await suspendFixtureInputUntilCancellation() }, idleSleep: { _ in try await suspendFixtureInputUntilCancellation() }) try await input.post(request(["down", "1", "100", "100", "0", "1"]), state: scene()) let task = Task { try await input.post(request(["drag", "900", "300", "0"]), state: scene()) } defer { task.cancel() } try await waitForTestEvent(suspended.stream, label: "drag sample suspension") #expect(recorder.events.map(\.type) == [.leftMouseDown, .leftMouseDragged]) #expect(recorder.restored.isEmpty) task.cancel() await #expect(throws: CancellationError.self) { try await task.value } #expect(recorder.events.map(\.type) == [.leftMouseDown, .leftMouseDragged, .leftMouseUp]) #expect(recorder.events.last?.point == CGPoint(x: 200, y: 125)) #expect(recorder.restored.count == 1) } @Test func abandonedGestureExpiresAndCannotResume() async throws { let recorder = MouseRecorder() let scheduled = AsyncStream.makeStream() let elapsed = AsyncStream.makeStream() let restored = AsyncStream.makeStream() recorder.onRestore = { restored.continuation.yield(()) } let input = try recorder.input( idleTimeout: .milliseconds(20), idleSleep: { duration in #expect(duration == .milliseconds(20)) scheduled.continuation.yield(()) var iterator = elapsed.stream.makeAsyncIterator() _ = await iterator.next() try Task.checkCancellation() }) try await input.post(request(["down", "1", "100", "100", "0", "1"]), state: scene()) try await waitForTestEvent(scheduled.stream, label: "fixture expiry timer registration") #expect(recorder.restored.isEmpty) elapsed.continuation.yield(()) try await waitForTestEvent(restored.stream, label: "abandoned fixture gesture release") #expect(recorder.events.map(\.type) == [.leftMouseDown, .leftMouseUp]) await #expect(throws: IPCError.self) { try await input.post(request(["drag", "900", "300", "0"]), state: scene()) } #expect(recorder.events.count == 2) } @Test func teardownReleasesAnActiveButton() async throws { let recorder = MouseRecorder() var input: AppFixtureMouseInput? = try recorder.input() try await input?.post(request(["down", "1", "100", "100", "0", "1"]), state: scene()) input = nil #expect(recorder.events.map(\.type) == [.leftMouseDown, .leftMouseUp]) #expect(recorder.restored.count == 1) } @Test func cursorRestorationFailureIsSurfacedAndCanBeRetried() async throws { let recorder = MouseRecorder() let input = try recorder.input() try await input.post(request(["down", "1", "100", "100", "0", "1"]), state: scene()) recorder.restoreResult = .failure #expect(throws: IPCError.self) { try input.restore() } #expect(recorder.events.map(\.type) == [.leftMouseDown, .leftMouseUp]) recorder.restoreResult = .success try input.restore() #expect(recorder.events.count == 2 && recorder.restored.count == 2) } @Test func normalHandlerNeverAcceptsSyntheticMouseWithoutTheHarness() async { guard ProcessInfo.processInfo.environment["PARCEL_E2E"] != "1" else { return } let handler = AppIPCHandler( services: EngineShellServices(), configPath: "/tmp/config.toml", permission: { true }) await #expect(throws: IPCError.self) { try await handler.run(command: "e2e-mouse", args: ["restore"]) } } private func request(_ arguments: [String]) throws -> AppFixtureMouseRequest { try AppFixtureMouseRequest(arguments: arguments, environment: environment) } private func scene() -> State { let display = DisplayID(rawValue: "mouse-display") let space = SpaceID(rawValue: 1) let key = WorkspaceKey(display: display, space: space) var state = State( displays: [Display(id: display, frame: Rect(width: 1200, height: 800))], activeSpaces: [display: space]) for raw in 1...3 { state = reduce( state, .windowAppeared( ManagedWindow(id: WindowID(rawValue: UInt32(raw)), app: AppID(pid: 123, bundleID: "fixture")), workspace: key, frame: Rect(width: 400, height: 300)) ).0 } return reduce(state, .commandIssued(.setLayout(.columns))).0 } } @MainActor private final class MouseRecorder { struct Event { let type: CGEventType let point: CGPoint let flags: CGEventFlags let pid: Int64 let window: Int64 let handlingWindow: Int64 let clicks: Int64 let dx: Int64 let dy: Int64 let pressure: Double } var events: [Event] = [] var restored: [CGPoint] = [] var onRestore: (@MainActor () -> Void)? var frontmost = true var hit: DragWindow? = DragWindow(pid: 123, windowNumber: 1) var restoreResult: CGError = .success func input( sampleDelay: Duration = .zero, sampleSleep: @escaping @MainActor (Duration) async throws -> Void = { try await Task.sleep(for: $0) }, idleTimeout: Duration = .seconds(30), idleSleep: @escaping @MainActor (Duration) async throws -> Void = { try await Task.sleep(for: $0) } ) throws -> AppFixtureMouseInput { try AppFixtureMouseInput( operations: .init( requireFixture: { pid in guard self.frontmost && pid == 123 else { throw AppFixtureDrag.rejected("Fixture lost focus") } }, windowAt: { _ in self.hit }, post: { event in self.events.append( Event( type: event.type, point: event.location, flags: event.flags, pid: event.getIntegerValueField(.eventTargetUnixProcessID), window: event.getIntegerValueField(.mouseEventWindowUnderMousePointer), handlingWindow: event.getIntegerValueField( .mouseEventWindowUnderMousePointerThatCanHandleThisEvent), clicks: event.getIntegerValueField(.mouseEventClickState), dx: event.getIntegerValueField(.mouseEventDeltaX), dy: event.getIntegerValueField(.mouseEventDeltaY), pressure: event.getDoubleValueField(.mouseEventPressure))) }, restoreCursor: { cursor in self.restored.append(cursor) self.onRestore?() return self.restoreResult }), cursor: CGPoint(x: 10, y: 20), sampleDelay: sampleDelay, sampleSleep: sampleSleep, idleTimeout: idleTimeout, idleSleep: idleSleep) } } @MainActor private func suspendFixtureInputUntilCancellation() async throws { let (stream, continuation) = AsyncStream.makeStream() defer { continuation.finish() } for await _ in stream {} try Task.checkCancellation() throw E2EError(description: "Fixture input suspension ended without cancellation") }