input-capture: the routing snapshot lock and the bounded capture ring

RoutingState holds the snapshot and the virtual cursor behind one
OSAllocatedUnfairLock so the tap callback can decide synchronously
(contracts C3); CaptureQueue is the 4096-entry ring with the C3
coalescing and overflow policy, plus notices that survive a full ring.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
lucioandClaude Opus 5 committed 2026-09-16 02:07:56 -07:00
1 parent c4c04914b3
commit d2d221fe29
2 files changed
+235

No files matched your search

+137
View File
@@ -0,0 +1,137 @@
// The bounded ring the event-tap callback pushes into and the Engine drains
// (contracts C3).
//
// The callback may not allocate, may not block and may not await, so it cannot
// hand a value to an actor directly. It appends to a fixed-size ring under an
// uncontended `OSAllocatedUnfairLock` and returns; the Engine drains on its own
// task. The ring lives in `MWBMac` rather than `MWBCore` because it needs that
// lock, and `MWBCore` may import Foundation only (README D2).
//
// Overflow policy, from contracts C3: pointer motion is coalesced, so a busy
// mouse cannot fill the ring; key and button transitions are never dropped, and
// if one cannot be enqueued the tap routes control local instead, because losing
// a key-up on a remote machine is worse than losing control.
import Foundation
import MWBCore
import os
/// Something the tap must tell the Engine that is not itself an input event and
/// must never be lost to a full ring.
public enum CaptureNotice: Sendable {
/// The tap was disabled and re-enabled; held-key state is unknown.
case tapLost
/// The ring filled and input was dropped.
case overflow
}
/// A fixed-capacity queue of captured input, safe to push to from the tap
/// callback and to drain from the Engine.
public final class CaptureQueue: Sendable {
/// The default depth: ~4 seconds of a fast mouse, before coalescing
/// (contracts C3).
public static let defaultCapacity = 4096
private struct Ring: Sendable {
var slots: [CapturedInput?]
var head = 0
var count = 0
var tapLost = false
var overflowed = false
}
private let capacity: Int
private let ring: OSAllocatedUnfairLock<Ring>
/// A queue holding at most `capacity` events.
public init(capacity: Int = CaptureQueue.defaultCapacity) {
let size = max(1, capacity)
self.capacity = size
ring = OSAllocatedUnfairLock(initialState: Ring(slots: Array(repeating: nil, count: size)))
}
/// Appends one event, coalescing it into the previous one where contracts C3
/// allows. Returns `false` if the ring was full and the event was dropped —
/// the caller must then route control local and `signal(.overflow)`.
@discardableResult
public func push(_ input: CapturedInput) -> Bool {
ring.withLock { state in
if let last = lastIndex(of: state), let merged = coalesce(state.slots[last], input) {
state.slots[last] = merged
return true
}
guard state.count < capacity else { return false }
state.slots[(state.head + state.count) % capacity] = input
state.count += 1
return true
}
}
/// Raises a notice that `drain()` will report even if the ring is full.
public func signal(_ notice: CaptureNotice) {
ring.withLock { state in
switch notice {
case .tapLost: state.tapLost = true
case .overflow: state.overflowed = true
}
}
}
/// Everything queued since the last drain, oldest first, with any raised
/// notices appended — they describe the state the tap is in *now*, so they
/// belong after the events they interrupted.
public func drain() -> [CapturedInput] {
ring.withLock { state in
var result: [CapturedInput] = []
result.reserveCapacity(state.count + 2)
for offset in 0..<state.count {
let index = (state.head + offset) % capacity
if let value = state.slots[index] { result.append(value) }
state.slots[index] = nil
}
state.head = 0
state.count = 0
if state.tapLost {
result.append(.tapLost)
state.tapLost = false
}
if state.overflowed {
result.append(.overflow)
state.overflowed = false
}
return result
}
}
/// How many events are waiting. For the menu bar and the perf notes only.
public var depth: Int { ring.withLock { $0.count } }
private func lastIndex(of state: Ring) -> Int? {
guard state.count > 0 else { return nil }
return (state.head + state.count - 1) % capacity
}
/// The two coalescing rules of contracts C3, or `nil` when the new event must
/// be queued on its own. Only ever merges like with like: a transition never
/// disappears into a move.
private func coalesce(_ previous: CapturedInput?, _ next: CapturedInput) -> CapturedInput? {
switch (previous, next) {
case (.edgeCandidate, .edgeCandidate):
return next // the latest pointer position is the only one that matters
case (.mouse(let old), .mouse(let new)):
if old.flags == WindowsMessage.mouseMove && new.flags == WindowsMessage.mouseMove {
return next
}
if old.flags == new.flags,
new.flags == WindowsMessage.wheel || new.flags == WindowsMessage.horizontalWheel
{
var summed = new
summed.wheelDelta = old.wheelDelta &+ new.wheelDelta
return .mouse(summed)
}
return nil
default:
return nil
}
}
}
+98
View File
@@ -0,0 +1,98 @@
// The one piece of shared state the event-tap callback is allowed to read:
// where input is going right now. See contracts C3.
//
// The Engine (an actor) owns everything else, but the tap must decide whether to
// swallow an event *synchronously*, inside a callback that may not await and may
// not block (CLAUDE.md invariant 4). So the decision inputs live here, behind an
// `OSAllocatedUnfairLock` that is only ever held for a struct copy.
//
// The virtual cursor lives here for the same reason: while a remote machine is
// being controlled the real pointer is parked (`Cursor.decouple`), so the tap
// keeps its own idea of where the pointer "is", seeded by the Engine when a
// switch lands and advanced by the callback from the raw deltas. It is the
// macOS stand-in for Windows' `Common.LastPos` plus `hookCallbackMouseData.X/Y`
// (`InputHook.cs:287-309`).
import Foundation
import MWBCore
import os
/// The routing snapshot and the virtual cursor, shared between the Engine and
/// the event-tap callback.
public final class RoutingState: Sendable {
private struct Box: Sendable {
var snapshot: RoutingSnapshot
var virtualCursor: CGPoint
}
private let box: OSAllocatedUnfairLock<Box>
/// Starts routed local, with the pointer believed to be at `virtualCursor`.
public init(
_ snapshot: RoutingSnapshot = RoutingSnapshot(),
virtualCursor: CGPoint = Coordinates.point(0, 0)
) {
box = OSAllocatedUnfairLock(initialState: Box(snapshot: snapshot, virtualCursor: virtualCursor))
}
/// A copy of the current snapshot. Called once per captured event.
public func read() -> RoutingSnapshot {
box.withLock { $0.snapshot }
}
/// Replaces the snapshot. Called by the Engine on every switch and whenever
/// settings change.
public func write(_ snapshot: RoutingSnapshot) {
box.withLock { $0.snapshot = snapshot }
}
/// Edits the snapshot in place. The closure runs with the lock held, so it
/// must not block or call back into the Engine.
public func update(_ body: @Sendable (inout RoutingSnapshot) -> Void) {
box.withLock { body(&$0.snapshot) }
}
/// Routes control back to this Mac and stops swallowing — the first half of
/// every recovery path in contracts C2, safe to call from the tap callback.
///
/// Returns `true` if this actually changed anything, so a caller can skip
/// telling the Engine about a no-op.
@discardableResult
public func routeLocal() -> Bool {
box.withLock { state in
let local = state.snapshot.routedLocal()
guard local != state.snapshot else { return false }
state.snapshot = local
return true
}
}
/// Where the tap believes the pointer is, in this Mac's screen coordinates.
public var virtualCursor: CGPoint {
get { box.withLock { $0.virtualCursor } }
set { box.withLock { $0.virtualCursor = newValue } }
}
/// Moves the virtual cursor by a raw device delta and clamps it to one pixel
/// outside `primary`, returning the new position.
///
/// The clamp is Windows' (`InputHook.cs:293-309`): while a remote machine is
/// controlled the virtual pointer may sit one pixel beyond each edge of the
/// controller's primary monitor, which is exactly what edge detection needs
/// to see to trigger the next switch, and no further.
public func advanceVirtualCursor(dx: Double, dy: Double, clampedTo primary: CGRect) -> CGPoint {
let bounds = Coordinates.bounds(primary)
return box.withLock { state in
let x = clamp(state.virtualCursor.x + dx, low: bounds.left, high: bounds.right)
let y = clamp(state.virtualCursor.y + dy, low: bounds.top, high: bounds.bottom)
state.virtualCursor = CGPoint(x: x, y: y)
return state.virtualCursor
}
}
private func clamp(_ value: CGFloat, low: Int, high: Int) -> CGFloat {
if value < CGFloat(low) { return CGFloat(low - 1) }
if value > CGFloat(high) { return CGFloat(high + 1) }
return value
}
}