Files
lucioandClaude Opus 5 84aa59a512 input-capture: coalescing looks back two entries
In remote mode one physical move queues a .mouse and an .edgeCandidate,
so matching only the last entry meant the kinds alternated and motion was
never coalesced -- the ring would fill at two entries per move whenever
the Engine stalled, which is the case C3's coalescing exists to survive.
The scan stops at the first non-motion entry so transitions keep order.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-16 02:19:38 -07:00

190 lines
7.4 KiB
Swift

// 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 a recent 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 target = coalesceTarget(state, input),
let merged = coalesce(state.slots[target], input)
{
state.slots[target] = 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 } }
/// Which queued entry `input` should merge into, if any.
///
/// The search looks back two entries, not one, because one physical mouse
/// move produces a `.mouse` *and* an `.edgeCandidate` while a peer is being
/// controlled: matching only the last entry would find the wrong kind every
/// time and coalescing would never happen. It stops at the first entry that
/// is not itself motion, so a button or key transition is never reordered
/// past.
private func coalesceTarget(_ state: Ring, _ input: CapturedInput) -> Int? {
var offset = state.count - 1
let limit = max(0, state.count - 2)
while offset >= limit {
let index = (state.head + offset) % capacity
let slot = state.slots[index]
if coalesce(slot, input) != nil { return index }
guard let slot, isMotion(slot) else { return nil }
offset -= 1
}
return nil
}
private func isMotion(_ input: CapturedInput) -> Bool {
switch input {
case .edgeCandidate:
return true
case .mouse(let data):
return data.flags == WindowsMessage.mouseMove
|| data.flags == WindowsMessage.wheel
|| data.flags == WindowsMessage.horizontalWheel
default:
return false
}
}
/// 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 .mouse(mergedMove(old, new))
}
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
}
}
/// Two consecutive moves become one.
///
/// An absolute move carries a position, so the newest one wins. A *relative*
/// move carries a delta (`MoveMouseRelatively`, docs/protocol.md §4.4), and
/// dropping the older one would throw away real motion — those are summed,
/// untagged and re-tagged so the `MOVE_MOUSE_RELATIVE` bias is applied once.
private func mergedMove(_ old: MouseData, _ new: MouseData) -> MouseData {
let oldPoint = UniversalPoint(x: old.x, y: old.y)
let newPoint = UniversalPoint(x: new.x, y: new.y)
guard Coordinates.isRelative(oldPoint), Coordinates.isRelative(newPoint) else {
return new
}
let a = Coordinates.untagRelative(oldPoint)
let b = Coordinates.untagRelative(newPoint)
let summed = Coordinates.tagRelative(dx: a.x &+ b.x, dy: a.y &+ b.y)
var merged = new
merged.x = summed.x
merged.y = summed.y
return merged
}
}