import CoreGraphics import Foundation import Testing @testable import ParcelPlatform struct MouseInputSafetyTests { @Test func frontmostFloatingCandidateUsesVerifiedWindowServerOrder() { let first = WindowHitTest.HoverStackRecord( number: 10, layer: CGWindowLevelForKey(.normalWindow), bounds: CGRect(x: 100, y: 100, width: 400, height: 300)) let second = WindowHitTest.HoverStackRecord( number: 20, layer: CGWindowLevelForKey(.normalWindow), bounds: first.bounds) #expect(WindowHitTest.frontmostHoverWindow(in: [10, 20], records: [second, first]) == 20) #expect(WindowHitTest.frontmostHoverWindow(in: [10, 20], records: [first, second]) == 10) #expect(WindowHitTest.frontmostHoverWindow(in: [20], records: [first, second]) == 20) #expect(WindowHitTest.frontmostHoverWindow(in: [10, 20], records: [first]) == nil) #expect(WindowHitTest.frontmostHoverWindow(in: [10, 20], records: [first, second, first]) == nil) #expect(WindowHitTest.frontmostHoverWindow(in: [], records: [first, second]) == nil) #expect(WindowHitTest.frontmostHoverWindow(in: [0, 10], records: [first, second]) == nil) let system = WindowHitTest.HoverStackRecord( number: 20, layer: CGWindowLevelForKey(.popUpMenuWindow), bounds: first.bounds) #expect(WindowHitTest.frontmostHoverWindow(in: [10, 20], records: [system, first]) == nil) let invalid = WindowHitTest.HoverStackRecord(number: 20, layer: 0, bounds: .zero) #expect(WindowHitTest.frontmostHoverWindow(in: [10, 20], records: [invalid, first]) == nil) } @Test func passiveHoverAllowsOnlyEmptyResizePaddingAndStillBlocksContentAndSystemSurfaces() { let bounds = CGRect(x: 100, y: 50, width: 400, height: 400) let outside = CGPoint(x: 300, y: 44) let inside = CGPoint(x: 300, y: 54) let normal = CGWindowLevelForKey(.normalWindow) #expect(WindowHitTest.hoverHit(number: 12, layer: normal, bounds: bounds, at: outside) == 0) #expect(WindowHitTest.hoverHit(number: 12, layer: normal, bounds: bounds, at: inside) == 12) #expect( WindowHitTest.hoverHit( number: 12, layer: CGWindowLevelForKey(.popUpMenuWindow), bounds: bounds, at: outside) == 12) #expect(WindowHitTest.hoverHit(number: 12, layer: normal, bounds: .zero, at: outside) == nil) } @Test func snapshotHoverPreservesNativeIdentityAndRejectsNewOrAmbiguousWindows() { let record = WindowHitTest.HoverStackRecord( number: 10, layer: CGWindowLevelForKey(.normalWindow), bounds: CGRect(x: 100, y: 100, width: 400, height: 300)) let gap = CGPoint(x: 250, y: 95) #expect(WindowHitTest.hoverSnapshotHit(number: 10, records: [record], at: gap) == 0) #expect(WindowHitTest.hoverSnapshotHit(number: 10, records: [record], at: CGPoint(x: 250, y: 105)) == 10) #expect(WindowHitTest.hoverSnapshotHit(number: 11, records: [], at: gap) == nil) #expect(WindowHitTest.hoverSnapshotHit(number: 11, records: [record], at: gap) == nil) #expect(WindowHitTest.hoverSnapshotHit(number: 10, records: [record, record], at: gap) == nil) #expect(WindowHitTest.hoverSnapshotHit(number: nil, records: [record], at: gap) == nil) #expect(WindowHitTest.hoverSnapshotHit(number: 0, records: [], at: gap) == 0) let desktop = WindowHitTest.HoverStackRecord( number: 12, layer: CGWindowLevelForKey(.desktopWindow), bounds: CGRect(x: 0, y: 0, width: 800, height: 600)) #expect(WindowHitTest.hoverSnapshotHit(number: 12, records: [desktop], at: gap) == 0) let popup = WindowHitTest.HoverStackRecord( number: 13, layer: CGWindowLevelForKey(.popUpMenuWindow), bounds: desktop.bounds) #expect(WindowHitTest.hoverSnapshotHit(number: 13, records: [popup], at: gap) == 13) } @Test func hoverBackdropAllowsOnlyVerifiedNormalWindowsBehindGapOwner() { let owner = WindowHitTest.HoverStackRecord( number: 10, layer: CGWindowLevelForKey(.normalWindow), bounds: CGRect(x: 100, y: 100, width: 400, height: 300)) let behind = WindowHitTest.HoverStackRecord( number: 20, layer: CGWindowLevelForKey(.normalWindow), bounds: CGRect(x: 0, y: 0, width: 800, height: 600)) let panel = WindowHitTest.HoverStackRecord( number: 30, layer: CGWindowLevelForKey(.floatingWindow), bounds: CGRect(x: 200, y: 90, width: 100, height: 10)) let gap = CGPoint(x: 250, y: 95) #expect(WindowHitTest.hoverBackdropHit(number: 20, owner: 10, records: [owner, behind], at: gap) == 0) #expect(WindowHitTest.hoverBackdropHit(number: 20, owner: 10, records: [behind, owner], at: gap) == 20) #expect( WindowHitTest.hoverBackdropHit( number: 20, owner: 10, records: [owner, behind], at: CGPoint(x: 250, y: 105)) == nil) #expect( WindowHitTest.hoverBackdropHit( number: 20, owner: 10, records: [panel, owner, behind], ignoring: [30], at: gap) == 0) #expect(WindowHitTest.hoverBackdropHit(number: 30, owner: 10, records: [panel, owner, behind], at: gap) == 30) #expect(WindowHitTest.hoverBackdropHit(number: 20, owner: 10, records: [behind], at: gap) == nil) #expect(WindowHitTest.hoverBackdropHit(number: 20, owner: 10, records: [owner], at: gap) == nil) #expect(WindowHitTest.hoverBackdropHit(number: 20, owner: 10, records: [owner, owner, behind], at: gap) == nil) #expect( WindowHitTest.hoverBackdropHit( number: 30, owner: 10, records: [panel, owner, behind], ignoring: [30], at: gap) == nil) let invalid = WindowHitTest.HoverStackRecord( number: 10, layer: CGWindowLevelForKey(.normalWindow), bounds: .zero) #expect(WindowHitTest.hoverBackdropHit(number: 20, owner: 10, records: [invalid, behind], at: gap) == nil) #expect(WindowHitTest.hoverBackdropHit(number: nil, owner: 10, records: [owner, behind], at: gap) == nil) #expect(WindowHitTest.hoverBackdropHit(number: 0, owner: 10, records: [owner], at: gap) == 0) #expect(WindowHitTest.hoverBackdropHit(number: 0, owner: 10, records: [], at: gap) == nil) #expect(WindowHitTest.hoverBackdropHit(number: 10, owner: 10, records: [owner], at: gap) == 0) #expect( WindowHitTest.hoverBackdropHit( number: 10, owner: 10, records: [owner], at: CGPoint(x: 250, y: 105)) == nil) #expect( WindowHitTest.hoverBackdropHit( number: 0, owner: 10, records: [owner], at: CGPoint(x: 250, y: 105)) == nil) } private let point = CGPoint(x: 500, y: 200) private var left: DragWindow { DragWindow(pid: 42, windowNumber: 1, bounds: CGRect(x: 0, y: 0, width: 495, height: 600)) } private var right: DragWindow { DragWindow(pid: 42, windowNumber: 2, bounds: CGRect(x: 505, y: 0, width: 495, height: 600)) } private var edge: MouseEdgeRegion { MouseEdgeRegion( hitArea: CGRect(x: 490, y: 0, width: 20, height: 600), gapArea: CGRect(x: 495, y: 0, width: 10, height: 600), windows: [left, right]) } @Test func nativePointIdentityWinsOverAClickThroughCanvasAndUnknownHitsStayBlocked() { let canvas = DragWindow( pid: 9, windowNumber: 16, layer: 20, bounds: CGRect(x: 0, y: 0, width: 1000, height: 600)) let windows = [canvas, left] #expect(WindowHitTest.resolveNativeHit(number: left.windowNumber, windows: windows) == .window(left)) #expect(WindowHitTest.resolveNativeHit(number: canvas.windowNumber, windows: windows) == .window(canvas)) #expect(WindowHitTest.resolveNativeHit(number: 0, windows: windows) == .empty) #expect(WindowHitTest.resolveNativeHit(number: 999, windows: windows) == .unavailable) #expect(WindowHitTest.resolveNativeHit(number: nil, windows: windows) == .unavailable) } @Test(arguments: [true, false]) func nativeDesktopIdentityAllowsGapClicksAfterHoverWhileCanvasesStillBlock(fresh: Bool) { let canvas = DragWindow( pid: 9, windowNumber: 16, layer: 20, bounds: CGRect(x: 0, y: 0, width: 1000, height: 600)) let desktop = DragWindow( pid: 8, windowNumber: 26, layer: CGWindowLevelForKey(.desktopIconWindow), bounds: canvas.bounds) let mailbox = MouseTapMailbox() mailbox.publish(MouseInputSnapshot(enabled: true, managedWindows: [left, right], edges: [edge]), ignoring: []) mailbox.publishWindows( [canvas, left, right, desktop], at: ProcessInfo.processInfo.systemUptime - (fresh ? 0 : 1)) let claimed = mailbox.receive(DragSample(kind: .down, location: point), windowHint: desktop.windowNumber) #expect(claimed) mailbox.stop() let blocked = MouseTapMailbox() blocked.publish(MouseInputSnapshot(enabled: true, managedWindows: [left, right], edges: [edge]), ignoring: []) blocked.publishWindows([canvas, left, right, desktop], at: ProcessInfo.processInfo.systemUptime) #expect(!blocked.receive(DragSample(kind: .down, location: point), windowHint: canvas.windowNumber)) blocked.stop() } @Test(arguments: [false, true]) func escapeTapAppliesInitialSnapshotWithoutAnEnableDisableCycle(enabled: Bool) throws { var activation = MouseTapActivation() var actual = !enabled var writes: [Bool] = [] try activation.synchronize( enabled: enabled, write: { writes.append($0); actual = $0 }, read: { actual }) #expect(writes == [enabled]) #expect(activation.enabled == enabled) try activation.synchronize( enabled: enabled, write: { _ in Issue.record("Unchanged activation must not write") }, read: { Issue.record("Unchanged activation must not read"); return actual }) #expect(writes == [enabled]) } @Test(arguments: [false, true]) func failedEscapeTapReadbackDoesNotRecordTheRequestedState(enabled: Bool) throws { var activation = MouseTapActivation() var writes: [Bool] = [] #expect(throws: InputError.tapEnableFailed) { try activation.synchronize(enabled: enabled, write: { writes.append($0) }, read: { !enabled }) } #expect(activation.enabled == nil) try activation.synchronize(enabled: enabled, write: { writes.append($0) }, read: { enabled }) #expect(activation.enabled == enabled) #expect(writes == [enabled, enabled]) } @Test(arguments: [false, true]) func failedEscapeTapTransitionRetainsOnlyTheLastVerifiedState(enabled: Bool) throws { var activation = MouseTapActivation() try activation.synchronize(enabled: !enabled, write: { _ in }, read: { !enabled }) #expect(throws: InputError.tapEnableFailed) { try activation.synchronize(enabled: enabled, write: { _ in }, read: { !enabled }) } #expect(activation.enabled == !enabled) } @Test(arguments: [MouseTapRole.mouse, .observation, .escape], [false, true]) func onlyIntentionallyInactiveEscapeTapIgnoresUserInputDisable(role: MouseTapRole, escapeEnabled: Bool) { let failure = MouseTapActivation.failure( for: .tapDisabledByUserInput, role: role, escapeEnabled: escapeEnabled, escapeRequested: escapeEnabled) #expect(failure == (role == .escape && !escapeEnabled ? nil : .tapEnableFailed)) } @Test func pendingEscapeActivationCannotHideUserInputDisable() { #expect( MouseTapActivation.failure( for: .tapDisabledByUserInput, role: .escape, escapeEnabled: false, escapeRequested: true) == .tapEnableFailed) } @Test(arguments: [MouseTapRole.mouse, .observation, .escape]) func unknownTapActivationCannotHideUserInputDisable(role: MouseTapRole) { #expect( MouseTapActivation.failure( for: .tapDisabledByUserInput, role: role, escapeEnabled: nil, escapeRequested: false) == .tapEnableFailed) } @Test(arguments: [MouseTapRole.mouse, .observation, .escape], [false, true]) func timeoutFailsEvenWhenEscapeIsIntentionallyInactive(role: MouseTapRole, escapeEnabled: Bool) { #expect( MouseTapActivation.failure( for: .tapDisabledByTimeout, role: role, escapeEnabled: escapeEnabled, escapeRequested: escapeEnabled) == .tapTimedOut) #expect( MouseTapActivation.failure( for: .keyDown, role: role, escapeEnabled: escapeEnabled, escapeRequested: escapeEnabled) == nil) } @Test(arguments: [Int32(0), 20, 24, 101]) func unrelatedWindowsAtEveryLayerKeepTheirClicks(layer: Int32) { let unrelated = DragWindow( pid: 99, windowNumber: 7, layer: layer, bounds: CGRect(x: 480, y: 100, width: 40, height: 300)) #expect(!edge.claim(at: point, topmost: unrelated, doubleClick: false)) #expect(!edge.claim(at: point, topmost: unrelated, doubleClick: true)) } @Test func onlyRealGapsResetAndContentKeepsScrollbarClicks() { #expect(edge.claim(at: point, topmost: nil, doubleClick: true)) #expect(edge.claim(at: CGPoint(x: 494, y: 200), topmost: left, doubleClick: false)) #expect(!edge.claim(at: CGPoint(x: 494, y: 200), topmost: left, doubleClick: true)) #expect(!edge.claim(at: CGPoint(x: 492, y: 200), topmost: left, doubleClick: false)) #expect(!edge.claim(at: CGPoint(x: 492, y: 599), topmost: left, doubleClick: false)) let zero = MouseEdgeRegion( hitArea: edge.hitArea, gapArea: CGRect(x: 500, y: 0, width: 0, height: 600), windows: [left, right]) #expect(!zero.claim(at: point, topmost: left, doubleClick: false)) #expect(!zero.claim(at: point, topmost: nil, doubleClick: true)) } @Test func topmostHitIncludesMenusAndIgnoresOnlyNamedChrome() { let chrome = DragWindow( pid: 2, windowNumber: 8, layer: 120, bounds: CGRect(x: 0, y: 0, width: 1000, height: 600)) let popover = DragWindow( pid: 3, windowNumber: 9, layer: 101, bounds: CGRect(x: 480, y: 100, width: 100, height: 300)) #expect(WindowHitTest.frontmost(at: point, windows: [chrome, popover, left]) == chrome) #expect(WindowHitTest.frontmost(at: point, windows: [chrome, popover, left], ignoring: [8]) == popover) } @Test(arguments: [Int32(24), 101, 102]) func menusAwayFromThePointerBlockHover(layer: Int32) { let menu = DragWindow( pid: 2, windowNumber: 4, layer: layer, bounds: CGRect(x: 20, y: 60, width: 200, height: 300)) #expect(WindowHitTest.frontmost(at: point, windows: [menu]) == nil) #expect(WindowHitTest.blocksHover([menu])) } @Test func menuBarStripAloneDoesNotBlockHover() { let strip = CGRect(x: -1000, y: -800, width: 1000, height: 24) let bar = DragWindow(pid: 2, windowNumber: 4, layer: 24, bounds: strip) #expect(!WindowHitTest.blocksHover([bar], menuBars: [strip])) #expect(WindowHitTest.blocksHover([bar])) let tall = DragWindow( pid: 2, windowNumber: 5, layer: 24, bounds: CGRect(x: -1000, y: -800, width: 1000, height: 80)) #expect(WindowHitTest.blocksHover([tall], menuBars: [strip])) } @Test func dragSamplesAreLatestWinsAndIndependentOfWindowCount() async throws { let mailbox = MouseTapMailbox() let windows = (1...50).map { DragWindow(pid: 42, windowNumber: UInt32($0), bounds: CGRect(x: 0, y: 0, width: 1000, height: 600)) } mailbox.publish(MouseInputSnapshot(enabled: true, moveModifiers: .hyper, managedWindows: windows), ignoring: []) mailbox.publishWindows(windows, at: ProcessInfo.processInfo.systemUptime) #expect(mailbox.receive(DragSample(kind: .down, location: point, modifiers: .hyper), windowHint: 1)) let clock = ContinuousClock() let start = clock.now for index in 1...10_000 { #expect( mailbox.receive( DragSample(kind: .dragged, location: CGPoint(x: index, y: 200), timestamp: Double(index)))) } let elapsed = start.duration(to: clock.now) #expect(elapsed < .seconds(2)) #expect(mailbox.takeDragged()?.sample.location == CGPoint(x: 10_000, y: 200)) #expect(mailbox.takeDragged() == nil) #expect(mailbox.receive(DragSample(kind: .up, location: point))) mailbox.stop() var deliveries = 0 for await event in mailbox.events { if case .sample = event { deliveries += 1 } } #expect(deliveries == 3) } @Test func nativeCommandDragWithoutEventWindowHintRetainsWindowIdentityAndFinalSample() async { let mailbox = MouseTapMailbox() mailbox.publish(MouseInputSnapshot(enabled: true, moveModifiers: .hyper, managedWindows: [left]), ignoring: []) mailbox.publishWindows([left], at: ProcessInfo.processInfo.systemUptime) let down = DragSample(kind: .down, location: CGPoint(x: 200, y: 12), modifiers: .command, timestamp: 1) let drag = DragSample(kind: .dragged, location: CGPoint(x: 750, y: 300), modifiers: .command, timestamp: 2) let up = DragSample(kind: .up, location: drag.location, modifiers: .command, timestamp: 3) #expect(!mailbox.receive(down)) #expect(!mailbox.receive(drag)) #expect(!mailbox.receive(up)) mailbox.stop() var deliveries: [MouseTapDelivery] = [] for await event in mailbox.events { if case .sample(let delivery) = event { deliveries.append(delivery) } if case .failed(let error) = event { Issue.record(error) } } #expect(deliveries.map(\.sample.kind) == [.down, .dragged, .up, .interrupted]) #expect(deliveries.first?.sample.wasClaimed == false) #expect(deliveries.first?.window == left) #expect(deliveries.dropFirst().allSatisfy { $0.window == nil }) #expect(deliveries.dropFirst().first?.sample == drag) #expect(!mailbox.consumesEscape) } @Test(arguments: [DragSample.Kind.cancel, .interrupted]) func cancellationsReleaseTheClaimedButton(kind: DragSample.Kind) { let mailbox = MouseTapMailbox() mailbox.publish(MouseInputSnapshot(enabled: true, moveModifiers: .hyper, managedWindows: [left]), ignoring: []) mailbox.publishWindows([left], at: ProcessInfo.processInfo.systemUptime) #expect( mailbox.receive( DragSample(kind: .down, location: CGPoint(x: 100, y: 100), modifiers: .hyper), windowHint: 1)) mailbox.receive(DragSample(kind: kind, location: point)) #expect(!mailbox.consumesEscape) #expect(!mailbox.receive(DragSample(kind: .dragged, location: point))) #expect(!mailbox.receive(DragSample(kind: .up, location: point))) mailbox.stop() } @Test func timeoutDisablesInsteadOfRearmingAndSurfacesFailure() async { let mailbox = MouseTapMailbox() mailbox.publish(MouseInputSnapshot(enabled: true, consumesEscape: true), ignoring: []) mailbox.disable(.tapTimedOut) #expect(!mailbox.consumesEscape) #expect(!mailbox.receive(DragSample(kind: .down, location: point))) mailbox.stop() var failures: [InputError] = [] for await event in mailbox.events { if case .failed(let error) = event { failures.append(error) } } #expect(failures == [.tapTimedOut]) } @Test func disabledGesturesStillObserveNativeManagedClicksWithoutWindowListReads() async { let mailbox = MouseTapMailbox() mailbox.publish(MouseInputSnapshot(enabled: false, managedWindows: [left]), ignoring: []) #expect(!mailbox.receive(DragSample(kind: .down, location: CGPoint(x: 100, y: 100)), windowHint: 1)) #expect(!mailbox.needsWindowRefresh(at: point, modifiers: .hyper)) mailbox.stop() var windows: [DragWindow?] = [] for await event in mailbox.events { if case .sample(let delivery) = event, delivery.sample.kind == .down { windows.append(delivery.window) } } #expect(windows == [left]) } @Test func ordinaryPointerMotionDoesNotRefreshWindowLists() { let snapshot = MouseInputSnapshot( enabled: true, moveModifiers: .hyper, resizeModifiers: [.hyper, .function], edges: [edge]) #expect(!snapshot.needsWindowRefresh(at: CGPoint(x: 100, y: 100), modifiers: [])) #expect(snapshot.needsWindowRefresh(at: point, modifiers: [])) #expect(snapshot.needsWindowRefresh(at: CGPoint(x: 100, y: 100), modifiers: .hyper)) #expect(!MouseInputSnapshot().needsWindowRefresh(at: point, modifiers: .hyper)) } @Test func staleOrDisagreeingWindowIdentityCannotClaim() { let mailbox = MouseTapMailbox() mailbox.publish(MouseInputSnapshot(enabled: true, moveModifiers: .hyper, managedWindows: [left]), ignoring: []) mailbox.publishWindows([left], at: 0) let sample = DragSample(kind: .down, location: CGPoint(x: 100, y: 100), modifiers: .hyper) #expect(!mailbox.receive(sample)) #expect(!mailbox.receive(sample, windowHint: 99)) mailbox.stop() } }