input-capture: protocol §10.4, README rewrite, TODO §4 ticked

§10.4 records ten things the lane established from the Windows source
(one-sided hotkey matching, the three meanings of Md.WheelDelta, the
virtual cursor and its primary+-1 clamp, the unconditional relative bias,
SwitchLocation, synthesised LLKHF bits, the eleven ReleaseAllKeys VKs, the
two input counters, monitor enumeration) plus the macOS device masks. The
README's Assumptions and Handshakes now describe what shipped, with the
nine decisions and three deliberate non-ports in the work log.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
lucioandClaude Opus 5 committed 2026-09-16 02:18:12 -07:00
1 parent 59fc7a3162
commit fd1ceeac08
5 files changed
+449 -117

No files matched your search

+3 -3
View File
@@ -119,8 +119,7 @@ public struct ModifierState: Sendable, Equatable {
public var shift: Bool
/// All modifiers up.
public init(command: Bool = false, control: Bool = false, option: Bool = false, shift: Bool = false)
{
public init(command: Bool = false, control: Bool = false, option: Bool = false, shift: Bool = false) {
self.command = command
self.control = control
self.option = option
@@ -145,7 +144,8 @@ public struct Hotkey: Sendable, Equatable {
public var shift: Bool
/// A hotkey. `vk == 0` disables it, as an empty `HotkeySettings` does.
public init(vk: Int32, command: Bool = false, control: Bool = false, option: Bool = false,
public init(
vk: Int32, command: Bool = false, control: Bool = false, option: Bool = false,
shift: Bool = false
) {
self.vk = vk
+1 -2
View File
@@ -76,8 +76,7 @@ public enum Permissions {
public final class PermissionHealthCheck: @unchecked Sendable {
private let timer: any DispatchSourceTimer
fileprivate init(interval: TimeInterval, onChange: @escaping @Sendable (PermissionState) -> Void)
{
fileprivate init(interval: TimeInterval, onChange: @escaping @Sendable (PermissionState) -> Void) {
let queue = DispatchQueue(label: "com.mwb-mac.permission-health", qos: .utility)
let timer = DispatchSource.makeTimerSource(queue: queue)
let last = OSAllocatedUnfairLock(initialState: Permissions.preflight())
+8 -8
View File
@@ -74,29 +74,29 @@ concurrency, shared constants, checkpoints) is fixed in `docs/contracts.md`.
hotkey; `reopenAll()`; delete `Placeholder.swift`.
- [x] Machine-ID collision ⇒ regenerate and reopen (§1.5).
## 4. input-capture (mac) — `Sources/MWBMac/EventTap.swift`, `Permissions.swift`, `Screens.swift`, `Cursor.swift`, `Hotkeys.swift`, `Sources/MWBCore/KeyMap.swift`, `Sources/MWBCore/InputTypes.swift`
## 4. input-capture (mac) — `Sources/MWBMac/EventTap.swift`, `Permissions.swift`, `Screens.swift`, `Cursor.swift`, `Hotkeys.swift`, `RoutingState.swift`, `CaptureQueue.swift`, `Sources/MWBCore/KeyMap.swift`, `Sources/MWBCore/InputTypes.swift` — done 2026-09-16
- [ ] `InputTypes.swift` (core): `CapturedInput`, `RoutingSnapshot`, the
- [x] `InputTypes.swift` (core): `CapturedInput`, `RoutingSnapshot`, the
injected-event tag constant, the escape-hotkey definitions
(contracts C3, C4) — defined here so input-inject can consume them.
- [ ] `Permissions.request…` added to the preflight file; health check
- [x] `Permissions.request…` added to the preflight file; health check
every 5 s reporting revocation (C2).
- [ ] Session-level head-insert swallowing `CGEventTap` on its own
- [x] Session-level head-insert swallowing `CGEventTap` on its own
run-loop thread for keys, flags, mouse, scroll; reads the routing
snapshot under `OSAllocatedUnfairLock` to decide swallowing
synchronously; appends to the bounded capture ring (4096, motion
coalesced, transitions never dropped — on overflow route local);
passes tagged injected events; on `tapDisabledByTimeout/UserInput`
re-enables **and** routes local (C2, C3, invariants 3, 4).
- [ ] Escape: switch-machine hotkey naming the local slot and ⌃⌥⌘Escape
- [x] Escape: switch-machine hotkey naming the local slot and ⌃⌥⌘Escape
flip the snapshot to local inside the callback, then notify (C2).
- [ ] `KeyMap`: macOS keycode ↔ Windows VK, `flagsChanged` → modifier VK
- [x] `KeyMap`: macOS keycode ↔ Windows VK, `flagsChanged` → modifier VK
pairs, `LLKHF` flags §5.1; `WM_*` mouse mapping, wheel ×120,
X-buttons, absolute 0..65535 moves §5.2.
- [ ] Hotkeys §4.5 with D4 (⌘=Win, ⌥=Alt): switch machine ⌃⌥F1–F4,
- [x] Hotkeys §4.5 with D4 (⌘=Win, ⌥=Alt): switch machine ⌃⌥F1–F4,
lock (double-press ⇒ ALL + lock), reconnect, toggle Easy Mouse,
switch-to-all; ignore when Shift/⌘ also held; Easy Mouse modes.
- [ ] `Screens`: displays, primary, desktop union, corners; refresh on
- [x] `Screens`: displays, primary, desktop union, corners; refresh on
change. `Cursor`: park (centre-x, y=4) / hide, decouple while
controlling remote, restore; `HideMouse (50)`; clamp while
controlled §5.3.
+358 -104
View File
@@ -16,149 +16,403 @@ this lane's.
## Assumptions
Written at planning time, revised 2026-09-16 to what shipped. Anything the
code does not enforce is here.
- **One tap, on its own thread.** `CGEvent.tapCreate(tap: .cgSessionEventTap,
place: .headInsertEventTap, options: .defaultTap, …)` for key down/up,
flagsChanged, mouse moved/dragged, all button down/up, scroll wheel,
plus `tapDisabledByTimeout`/`tapDisabledByUserInput`. The run-loop
source is added to a `CFRunLoop` on a dedicated `Thread`, never the
main thread (C3). A `.defaultTap` needs Accessibility; listening to
keys needs Input Monitoring (README §Permissions).
- **The callback does four things and returns**: (1) if the event
carries the injected tag (`CGEventField.eventSourceUserData ==
InputTypes.injectedEventTag`) return it untouched — the Windows
`RealData` flag (`InputHook.cs:213-220, 340-343`); (2) read the
`RoutingSnapshot`; (3) match hotkeys — the escape set (`InputTypes`)
flips the snapshot to local *inside the callback* and is swallowed;
other hotkeys are queued as `.hotkey` and swallowed; (4) if the
destination is remote, convert to `CapturedInput`, push, return `nil`
(swallow: `InputHook.cs:361-368` keyboard, `:322-325` mouse); if local,
push mouse *moves only* (so `Edge` can watch for a crossing) and pass
everything through. No allocation-heavy work, no locks beyond the
snapshot's uncontended `OSAllocatedUnfairLock` (invariant 4).
flagsChanged, mouse moved/dragged, all button down/up and scroll wheel. The
run-loop source is added to the `CFRunLoop` of a dedicated `Thread` at
`.userInteractive`, never the main thread (contracts C3). A `.defaultTap`
needs Accessibility; listening to keys needs Input Monitoring (README
§Permissions). `tapDisabledByTimeout` / `tapDisabledByUserInput` arrive
whatever the mask says, so they are not in it.
- **The callback does five things and returns**: (1) handle a disabled tap;
(2) if the event carries the injected tag (`CGEventField.eventSourceUserData
== InputTypes.injectedEventTag`) return it untouched — the Windows `RealData`
flag (`InputHook.cs:213-220, 340-343`); (3) read the `RoutingSnapshot`;
(4) match hotkeys — the escape set flips the snapshot to local *inside the
callback* and is swallowed, other hotkeys are queued and swallowed; (5) if
the destination is remote, convert to `CapturedInput`, push and swallow
(`InputHook.cs:361-368` keyboard, `:322-325` mouse); if local, push mouse
*moves only* so `Edge` can watch for a crossing, and pass everything through.
Three uncontended `OSAllocatedUnfairLock` acquisitions per event at most
(snapshot, virtual cursor, counters) and no allocation (invariant 4).
- **Swallowing is a separate flag from the destination.** ALL-machines mode
sends input to every peer *and* keeps it locally (`InputHook.cs:361`), so
`swallowKeys`/`swallowMouse` are set by the Engine, not derived here.
- **The queue is a bounded ring of 4096 `CapturedInput`s** in
`MWBMac/CaptureQueue.swift` (it needs a lock, which `MWBCore` may not
import). Motion is coalesced on push when the previous entry is also
motion (latest position wins, wheel deltas summed); a key/button
transition that finds the ring full triggers local recovery: the tap
flips the snapshot to local and reports `.overflow` (C3).
- **Keyboard encoding**: `wVk` from `KeyMap.vk(forKeycode:)`; `dwFlags`
= `LLKHF` bits (`WM.cs:47-54`): `UP 0x80` on key-up, `EXTENDED 0x01`
for the keys Windows marks extended (right Ctrl/Alt, arrows, Ins/Del/
Home/End/PgUp/PgDn, numpad Enter/divide, Win keys), `ALTDOWN 0x20`
while either Option is down. Autorepeat (`CGEventField.keyboardEventAutorepeat`)
is sent as repeated key-downs, which is what the Windows hook sees.
import). Motion is coalesced on push when the previous entry is also motion —
latest position wins for an absolute move, deltas are **summed** for a
relative one, and wheel deltas of the same axis are summed. A push that
cannot be satisfied routes control local and raises `.overflow`, which
`drain()` reports even when the ring is full (contracts C3).
- **Keyboard encoding**: `wVk` from `KeyMap.vk(forKeycode:)`; `dwFlags` =
`LLKHF` bits (`WM.cs:47-54`): `UP 0x80` on key-up, `EXTENDED 0x01` for the
keys Windows marks extended (right Ctrl/Alt, arrows, Ins/Del/Home/End/
PgUp/PgDn, numpad Enter and divide, Num Lock, both Windows keys),
`ALTDOWN 0x20` while either Option is down. Autorepeat
(`CGEventField.keyboardEventAutorepeat`) is sent as repeated key-downs,
which is what the Windows hook sees; hotkeys are **not** matched on repeats.
- **Modifiers come from `flagsChanged`**, diffed against the previous
device-specific flag word (`NX_DEVICELCTLKEYMASK 0x01`, `LSHIFT 0x02`,
`RSHIFT 0x04`, `LCMD 0x08`, `RCMD 0x10`, `LALT 0x20`, `RALT 0x40`) into
down/up pairs of `VK_LCONTROL 0xA2`/`RCONTROL 0xA3`, `LSHIFT 0xA0`/
`RSHIFT 0xA1`, `LWIN 0x5B`/`RWIN 0x5C` (⌘ = Win, README D4),
`LMENU 0xA4`/`RMENU 0xA5` (⌥ = Alt). Caps Lock is `VK_CAPITAL 0x14` as
a down+up pair on each toggle; `fn` is ignored.
- **`KeyMap` is a static table in `MWBCore`** keyed by macOS virtual
keycode (the `kVK_*` numbers written as literals with their names in
comments — `Carbon` may not be imported there) for a US layout:
letters, digits, F1–F19, arrows, editing keys, numpad, punctuation,
Return/Tab/Space/Escape/Delete/ForwardDelete. Keys with no VK are
dropped and counted. The reverse map is what `input-inject` uses.
- **Mouse encoding** (`InputHook.cs:245-260`, `WM.cs:27-40`): `dwFlags` =
the `WM_*` id; buttons 0/1/2 = L/R/M, buttons 3/4 = `WM_XBUTTON*` with
`WheelDelta` = 1/2; moves are absolute 0..65535 against the **primary**
`RSHIFT 0x04`, `LCMD 0x08`, `RCMD 0x10`, `LALT 0x20`, `RALT 0x40`,
`RCTL 0x2000`) into down/up pairs of `VK_LCONTROL 0xA2`/`RCONTROL 0xA3`,
`LSHIFT 0xA0`/`RSHIFT 0xA1`, `LWIN 0x5B`/`RWIN 0x5C` (⌘ = Win, README D4),
`LMENU 0xA4`/`RMENU 0xA5` (⌥ = Alt). Caps Lock is `VK_CAPITAL 0x14` as a
down+up pair on each toggle of `NX_ALPHASHIFTMASK 0x10000`; `fn` is ignored.
- **`KeyMap` is a static table in `MWBCore`** keyed by macOS virtual keycode
(the `kVK_*` numbers written as literals with their names in comments —
`Carbon` may not be imported there) for a US ANSI layout: letters, digits,
F1–F20, arrows, editing keys, keypad, punctuation, volume,
Return/Tab/Space/Escape/Delete/ForwardDelete and the eight modifiers. Keys
with no VK are passed through to this Mac and counted
(`EventTap.unmappedKeyCount`). The reverse map is what `input-inject` uses.
- **Mouse encoding** (`InputHook.cs:245-260`, `WM.cs:27-40`): `dwFlags` = the
`WM_*` id; buttons 0/1/2 = L/R/M, buttons 3/4 = `WM_XBUTTON*` with
`WheelDelta` = 1/2, higher buttons stay local; dragging is a move, as the
Windows hook reports it. Moves are absolute 0..65535 against the **primary**
display (`Event.cs:112-113`) — or, in `MoveMouseRelatively` mode,
`mouseEventDeltaX/Y` biased by `Coordinates` (§4.4). Scroll: the
fixed-point line delta × 120 accumulated into a remainder so trackpad
scrolling emits whole 120-unit steps (`WM_MOUSEWHEEL` axis 1,
`WM_MOUSEHWHEEL` axis 2, sign as Windows: up/away = +120).
`mouseEventDeltaX/Y` tagged by `Coordinates.tagRelative` (§4.4). Scroll: the
fixed-point line delta × 120 accumulated into a per-axis remainder so
trackpad scrolling emits whole 120-unit notches (`WM_MOUSEWHEEL` axis 1,
`WM_MOUSEHWHEEL` axis 2). **The axis-2 sign against Windows' "positive means
scroll right" is unverified** — a CP1 question (docs/protocol.md §10.4
note 10).
- **The virtual cursor.** While a remote machine is controlled the real pointer
is frozen, so the tap keeps its own position: seeded from the real pointer on
every local move, advanced by `mouseEventDeltaX/Y`, clamped to
`primary ± 1 px` exactly as `InputHook.cs:293-309` does. That is what goes on
the wire and what edge detection sees.
- **Hotkeys** (`InputHook.cs:539-658`, `MouseWithoutBordersProperties.cs`):
switch-machine = ⌃⌥ + `HotKeySwitchMachine` VK offset by slot
(F1..F4 → slots 0..3); lock = ⌘⌃⌥L (twice within 500 ms ⇒ ALL + lock);
reconnect = ⌘⌃⌥R; toggle Easy Mouse = ⌘⌃⌥E; switch-to-all = disabled
by default; ignored when Shift or ⌘ is also held with ⌃⌥ alone
(`InputHook.cs:604-610`). Escape set (C2): switch-machine naming the
local slot, and ⌃⌥⌘Escape. Hotkey definitions arrive in
`CaptureConfig` as VK + modifier set; the tap compares against the
live modifier state it tracks.
- **Easy Mouse** (`EasyMouseOption.cs`, `InputHook.cs:467-473`): the tap
pushes `.edgeCandidate(point)` moves only when the mode allows it —
always for `Enable`, only while ⌃ / ⇧ is held for those modes, never
for `Disable`; the fullscreen rule is the extras lane's.
switch-machine = ⌃⌥ + `HotKeySwitchMachine` VK offset by slot (F1..F4 →
slots 0..3); lock = ⌘⌃⌥L (twice within 500 ms ⇒ ALL + lock); reconnect =
⌘⌃⌥R; toggle Easy Mouse = ⌘⌃⌥E; switch-to-all = disabled by default;
switch-machine is ignored when Shift or ⌘ is also held (`InputHook.cs:604-610`).
Escape set (contracts C2): switch-machine naming the local slot while control
is remote, and ⌃⌥⌘Escape, which is checked first so no veto can shadow it.
- **Easy Mouse** (`EasyMouseOption.cs`, `InputHook.cs:467-473`): the tap pushes
`.edgeCandidate(point:now:)` on moves only when the mode allows it — always
for `Enable`, while ⌃ / ⇧ is held for those modes, never for `Disable` — and
never while controlling a remote in relative mode (`Event.cs:73`). The
fullscreen rule is the extras lane's.
- **Screens** (`WinAPI.cs:70-80, 115-184`): `CGGetActiveDisplayList` +
`CGDisplayBounds`; primary = `CGMainDisplayID()`; desktop = union;
`screenWidth/Height` = primary size; corner points = every display's
four corners (`MonitorEnumProc`'s sensitive points). Refreshed on
`NSApplication.didChangeScreenParametersNotification` and reported to
the Engine so it can rebuild `EdgeConfig`.
- **Cursor** (`Common.cs:1482-1496`, `InputHook.cs:293-309`): while a
remote is controlled, `CGAssociateMouseAndMouseCursorPosition(false)`
keeps the real pointer parked (deltas still arrive) and
`CGDisplayHideCursor` hides it; parking = warp to (primary centre-x,
y = 4) when `HideMouse` is on, else primary centre; on return,
re-associate, show, warp to the last local position. `parkCursor`
actions from `Switcher` are applied by the consumer rule in the
session-matrix Handshakes (move only when `destinationIsRemote ||
byHideMouseMessage`).
- **Permissions**: `Permissions.preflight()` stays; `request()` calls
`CGRequestListenEventAccess()` / `CGRequestPostEventAccess()` and is
invoked only from a UI action the user clicks (app-shell); a 5 s
health check re-preflights and reports loss (C2). Agents never call
`request()` themselves.
- **Tap loss** (`InputHook.cs` has no equivalent; C2): on
`tapDisabledByTimeout`/`ByUserInput` the callback re-enables the tap
with `CGEvent.tapEnable` **and** flips the snapshot to local, then
reports `.tapLost`; the Engine releases keys.
`CGDisplayBounds`; primary = `CGMainDisplayID()`; desktop = union; corner
points = every display's four corners, half-open as `SensitivePoints` is.
Refreshed on `NSApplication.didChangeScreenParametersNotification`;
`ScreenLayout.edgeConfig(blockCorners:moveRelatively:)` hands the Engine a
ready `EdgeConfig`.
- **Cursor** (`Common.cs:1482-1496`, `InputHook.cs:293-309`): while a remote is
controlled, `CGAssociateMouseAndMouseCursorPosition(false)` keeps the real
pointer parked (deltas still arrive) and `CGDisplayHideCursor` hides it;
parking = warp to (primary centre-x, y = 4) when `HideMouse` is on, else
primary centre; on return, show, re-associate, warp to the last local
position — in that order, so a queued delta cannot beat the warp.
`Cursor.park` applies the `destinationIsRemote || byHideMouseMessage` gate
itself, so a `SwitchAction.parkCursor` maps onto it one-to-one (session-matrix
Handshakes).
- **Permissions**: `preflight()` stays; `request()` calls
`CGRequestListenEventAccess()` / `CGRequestPostEventAccess()` and is invoked
only from a UI action the user clicks (app-shell); a 5 s health check
re-preflights and reports any change (contracts C2). Agents never call
`request()`.
- **Tap loss** (contracts C2): on `tapDisabledByTimeout`/`ByUserInput` the
callback re-enables the tap with `CGEvent.tapEnable` **and** flips the
snapshot to local, forgets the modifier state, then raises `.tapLost`; the
Engine releases keys.
- **Clocks.** `.edgeCandidate` timestamps come from `EventTap.now()`
(`mach_absolute_time`). The Engine must use the same function for
`Switcher`/`Edge`, or the 100 ms jump debounce compares two clocks.
## Handshakes
### Consumed
- `session-matrix`: `Coordinates` (universal/relative encoding), `EdgeConfig`
shape, `Direction`, `SwitchAction.parkCursor` consumer rule.
- `wire-core`: `Packet`, `MouseData`/`KeyboardData` field layout for the
values `CapturedInput` carries.
- `session-matrix`: `Coordinates` (universal/relative encoding, the CG helpers),
`EdgeConfig`, `Direction`, the `SwitchAction.parkCursor` consumer rule.
- `wire-core`: `MouseData` for the values `CapturedInput` carries.
### Promised (to input-inject, app-shell, extras)
As shipped 2026-09-16. Later lanes code against this, not against the sketch
this section used to hold.
```swift
// MWBCore/InputTypes.swift
public enum InputTypes { public static let injectedEventTag: Int64 } // C4
public struct RoutingSnapshot: Sendable { destination: Destination (.local | .remote(UInt32)); swallowKeys, swallowMouse: Bool; easyMouse: EasyMouseMode; hotkeys: HotkeyConfig }
public enum CapturedInput: Sendable { key(vk: Int32, flags: Int32); mouse(MouseData) /* WM_* + coords */; edgeCandidate(CGPoint, now: TimeInterval); hotkey(Hotkey); tapLost; overflow }
public struct HotkeyConfig: Sendable { switchMachineVK, lock, reconnect, toggleEasyMouse, switchToAll: Hotkey? }
public enum EasyMouseMode: Int, Sendable { disable = 0, enable = 1, ctrl = 2, shift = 3 }
public enum KeyMap { static func vk(forKeycode: Int64) -> Int32?; static func keycode(forVK: Int32) -> Int64?; static func isExtended(vk:) -> Bool; static func modifierTransitions(old: UInt64, new: UInt64) -> [(vk: Int32, down: Bool)] }
public enum WindowsMessage { // WM.cs:27-40
static let mouseMove, leftDown, leftUp, leftDoubleClick, rightDown, rightUp,
rightDoubleClick, middleDown, middleUp, middleDoubleClick, wheel,
extraDown, extraUp, horizontalWheel: Int32
static let wheelDelta: Int32 // 120
}
public enum KeyFlag { static let extended, injected, altDown, up: Int32 } // WM.cs:47-54
public enum Destination: Sendable, Equatable { case local, remote(UInt32); var isRemote: Bool }
public enum EasyMouseMode: Int, Sendable, Equatable { case disable, enable, ctrl, shift }
public struct ModifierState: Sendable, Equatable { var command, control, option, shift: Bool }
public struct Hotkey: Sendable, Equatable {
var vk: Int32; var command, control, option, shift: Bool
var isEmpty: Bool
func matches(vk: Int32, modifiers: ModifierState) -> Bool
}
public struct HotkeyConfig: Sendable, Equatable {
var switchMachineVK: Int32; var lock, reconnect, toggleEasyMouse, switchToAll: Hotkey
static let switchMachineSlots: Int // 4
static let escape: Hotkey // ⌃⌥⌘Escape, mac-only
}
public enum HotkeyAction: Sendable, Equatable {
case switchToSlot(Int), lockMachine, lockAllMachines, reconnect,
toggleEasyMouse, toggleSwitchToAll, escapedToLocal
}
public enum CapturedInput: Sendable {
case key(vk: Int32, flags: Int32)
case mouse(MouseData)
case edgeCandidate(point: CGPoint, now: TimeInterval)
case hotkey(HotkeyAction)
case tapLost
case overflow
}
public struct RoutingSnapshot: Sendable, Equatable {
var destination: Destination
var swallowKeys, swallowMouse: Bool
var easyMouse: EasyMouseMode
var moveMouseRelatively: Bool
var hotkeys: HotkeyConfig
var localSlot: Int?
func routedLocal() -> RoutingSnapshot
}
// MWBCore/KeyMap.swift
public enum KeyMap {
static let back, `return`, capital, escape, leftWin, rightWin, leftShift, rightShift,
leftControl, rightControl, leftMenu, rightMenu: Int32
static let keypadEnterKeycode: Int64
static func vk(forKeycode: Int64) -> Int32?
static func keycode(forVK: Int32) -> Int64?
static func isExtended(vk: Int32, keycode: Int64) -> Bool
static let leftControlMask, leftShiftMask, rightShiftMask, leftCommandMask,
rightCommandMask, leftOptionMask, rightOptionMask, rightControlMask,
capsLockMask: UInt64 // NX_DEVICE* / NX_ALPHASHIFT
static func modifiers(from flags: UInt64) -> ModifierState
static func forEachModifierTransition(old: UInt64, new: UInt64, _ body: (Int32, Bool) -> Void)
static func modifierTransitions(old: UInt64, new: UInt64) -> [(vk: Int32, down: Bool)]
static func capsLockToggled(old: UInt64, new: UInt64) -> Bool
}
// MWBMac
public final class RoutingState { func read() -> RoutingSnapshot; func write(_:) } // OSAllocatedUnfairLock
public final class CaptureQueue { init(capacity: Int = 4096); func push(_:) -> Bool; func drain() -> [CapturedInput] }
public final class EventTap { init(routing: RoutingState, queue: CaptureQueue, screens: Screens, config: CaptureConfig, onWake: @escaping @Sendable () -> Void); func start() throws; func stop(); func reconfigure(_:) }
public struct ScreenLayout: Sendable { displays: [CGRect]; primary: CGRect; desktop: CGRect; corners: [CGPoint] }
public final class Screens { var layout: ScreenLayout; func refresh(); var onChange: (() -> Void)? }
public final class Cursor { func decouple(parkHidden: Bool, layout: ScreenLayout); func recouple(to: CGPoint?); func park(hideMouse: Bool, layout: ScreenLayout) }
public enum Permissions { static func preflight() -> PermissionState; static func request(); static func startHealthCheck(onLoss:) }
public final class RoutingState: Sendable {
init(_ snapshot: RoutingSnapshot = .init(), virtualCursor: CGPoint = …)
func read() -> RoutingSnapshot
func write(_ snapshot: RoutingSnapshot)
func update(_ body: @Sendable (inout RoutingSnapshot) -> Void)
@discardableResult func routeLocal() -> Bool
var virtualCursor: CGPoint { get set }
func advanceVirtualCursor(dx: Double, dy: Double, clampedTo primary: CGRect) -> CGPoint
}
public enum CaptureNotice: Sendable { case tapLost, overflow }
public final class CaptureQueue: Sendable {
static let defaultCapacity: Int // 4096
init(capacity: Int = defaultCapacity)
@discardableResult func push(_ input: CapturedInput) -> Bool
func signal(_ notice: CaptureNotice)
func drain() -> [CapturedInput]
var depth: Int { get }
}
public struct CaptureConfig: Sendable, Equatable {
var hotkeys: HotkeyConfig; var easyMouse: EasyMouseMode
var moveMouseRelatively: Bool; var localSlot: Int?
}
public enum EventTapError: Error, Equatable { case creationFailed, runLoopSourceFailed }
public final class EventTap: @unchecked Sendable {
init(routing: RoutingState, queue: CaptureQueue, screens: Screens,
config: CaptureConfig = .init(), onWake: @escaping @Sendable () -> Void)
func start() throws
func stop()
var isRunning: Bool { get }
func reconfigure(_ config: CaptureConfig)
var realInputEventCount: UInt64 { get } // Session.tick takes this
var unmappedKeyCount: UInt64 { get }
static func now() -> TimeInterval // the lane's clock
}
public struct HotkeyMatch: Sendable, Equatable { var action: HotkeyAction; var routesLocal: Bool }
public struct HotkeyMatcher: Sendable {
static let lockDoublePressWindow: TimeInterval // 0.5
var config: HotkeyConfig
mutating func match(vk: Int32, modifiers: ModifierState, localSlot: Int?,
destinationIsRemote: Bool, now: TimeInterval) -> HotkeyMatch?
mutating func resetLockTimer()
}
public struct ScreenLayout: Sendable {
var displays: [CGRect]; var primary, desktop: CGRect; var corners: [CGPoint]
static func current() -> ScreenLayout
func edgeConfig(blockCorners: Bool, moveRelatively: Bool) -> EdgeConfig
}
public final class Screens: @unchecked Sendable {
init(onChange: (@Sendable () -> Void)? = nil)
var layout: ScreenLayout { get }
func refresh()
func startObserving() // main thread
func stopObserving() // main thread
}
public final class Cursor: Sendable {
static func parkPosition(hideMouse: Bool, in layout: ScreenLayout) -> CGPoint
@discardableResult func park(hideMouse: Bool, layout: ScreenLayout,
destinationIsRemote: Bool, byHideMouseMessage: Bool) -> CGPoint
@discardableResult func decouple(parkHidden: Bool, layout: ScreenLayout) -> CGPoint
func recouple(to point: CGPoint?)
func warp(to point: CGPoint)
func hide(); func show() // balanced
var isDecoupled: Bool { get }
func restoreEverything() // atexit / signal handler
}
public struct PermissionState: Equatable, Sendable { let listen, post: Bool; var isComplete: Bool }
public enum Permissions {
static let healthCheckInterval: TimeInterval // 5
static func preflight() -> PermissionState
@discardableResult static func request() -> PermissionState // user-initiated only
static func startHealthCheck(interval: TimeInterval = healthCheckInterval,
onChange: @escaping @Sendable (PermissionState) -> Void) -> PermissionHealthCheck
}
public final class PermissionHealthCheck: @unchecked Sendable { func cancel() }
```
Five deviations from the shape sketched at planning time, all deliberate:
- **`isExtended` takes the keycode as well as the VK.** The keypad's Enter and
Return share `VK_RETURN`, and the extended bit is the only thing that tells
them apart (docs/protocol.md §10.4 note 6); a `vk`-only predicate cannot.
- **`RoutingSnapshot` carries `easyMouse`, `moveMouseRelatively`, `hotkeys` and
`localSlot`** as well as the routing. The callback needs all of them and there
is no second lock; `reconfigure(_:)` writes that half and leaves the routing
half alone.
- **`Screens.onChange` is an init parameter, not a settable property**, so the
class needs no lock around a closure.
- **`CapturedInput` is not `Equatable`.** `CGPoint` is not, in a
Foundation-only target.
- **The tap owns the two counters `Event.InputEventCount`/`RealInputEventCount`
stand for** — `realInputEventCount` is the value `Session.tick` wants
(docs/protocol.md §10.4 note 8).
### Requested of input-inject (open)
1. `Injector` must stamp `CGEventField.eventSourceUserData` with
`InputTypes.injectedEventTag` on **every** event it posts, including the
synthetic key-ups of `releaseAll()`. An untagged event is captured and echoed
straight back to the peer.
2. `Injector` performs `HotkeyAction.lockMachine` / `.lockAllMachines` by
sending the chord — the tap swallowed the keys, so nothing reaches the peer
otherwise (`InputHook.cs:548-562`).
### Requested of app-shell (open)
1. The Engine must timestamp `Switcher`/`Edge` with `EventTap.now()`.
2. The Engine owns `swallowKeys`/`swallowMouse`: set them false in ALL-machines
mode, true for a single remote destination.
3. On `.tapLost`, `.overflow` and `.hotkey(.escapedToLocal)` the tap has already
routed local; the Engine still owes `releaseAllKeys`, `Cursor.recouple` and
the `HideMouse`/`MachineSwitched` housekeeping (contracts C2).
4. `Screens.startObserving()` and `stopObserving()` must be called on the main
thread, after `NSApplication.shared` exists.
## Status / TODO
- [ ] `Sources/MWBCore/InputTypes.swift`: tag, `RoutingSnapshot`,
- [x] `Sources/MWBCore/InputTypes.swift`: tag, `RoutingSnapshot`,
`CapturedInput`, `HotkeyConfig`, `Hotkey`, `EasyMouseMode` (C3, C4).
- [ ] `Sources/MWBCore/KeyMap.swift`: keycode ↔ VK table, extended set,
- [x] `Sources/MWBCore/KeyMap.swift`: keycode ↔ VK table, extended set,
modifier transitions (`VK.cs`, `WM.cs:47-54`, `InputHook.cs:371-473`).
- [ ] `Sources/MWBMac/CaptureQueue.swift`: bounded ring, coalescing,
- [x] `Sources/MWBMac/CaptureQueue.swift`: bounded ring, coalescing,
overflow policy (C3). `Sources/MWBMac/RoutingState.swift`: the
snapshot lock.
- [ ] `Sources/MWBMac/EventTap.swift`: the tap on its own run loop,
- [x] `Sources/MWBMac/EventTap.swift`: the tap on its own run loop,
callback per Assumptions, mouse/keyboard/scroll encoding
(`InputHook.cs:110-133, 213-368`), tap-loss handling (C2).
- [ ] `Sources/MWBMac/Hotkeys.swift`: matching, double-press lock rule,
- [x] `Sources/MWBMac/Hotkeys.swift`: matching, double-press lock rule,
the ignore-with-Shift/⌘ rule, escape set (`InputHook.cs:539-658`).
- [ ] `Sources/MWBMac/Screens.swift`, `Cursor.swift`: layout, corners,
- [x] `Sources/MWBMac/Screens.swift`, `Cursor.swift`: layout, corners,
change notification; decouple/park/recouple (`WinAPI.cs:70-184`,
`Common.cs:1482-1496`, `InputHook.cs:293-309`).
- [ ] `Sources/MWBMac/Permissions.swift`: add `request()` and the
- [x] `Sources/MWBMac/Permissions.swift`: add `request()` and the
health check.
- [ ] `docs/protocol.md`: append §10.4 with anything learned, cited.
- [x] `docs/protocol.md`: append §10.4 with anything learned, cited.
- Not done, deliberately: the `SwitchLocation.Count` mechanic
(`InputHook.cs:268-284`). See the work log.
- Not done, deliberately: Ctrl+Alt+Delete as a switch-to-local trigger
(`InputHook.cs:427-448`). See the work log.
- Not done, deliberately: `HotKeyExitMM` (`InputHook.cs:588-603`), disabled by
default on Windows and not in TODO §4.
## Work log
### 2026-09-16 — dev (Opus), the whole lane
Nine files: two in `MWBCore` (`InputTypes.swift`, `KeyMap.swift`), seven in
`MWBMac` (`RoutingState.swift`, `CaptureQueue.swift`, `Screens.swift`,
`Cursor.swift`, `Hotkeys.swift`, `EventTap.swift`, `Permissions.swift`).
`tools/gates.sh` green; nothing in this lane was *run*, by instruction — no
event tap was created, no `CGEvent` posted, no cursor warped, no permission
requested. The user tests.
Decisions, in the order they were made:
1. **Config lives in the routing snapshot.** The callback needs `easyMouse`,
`moveMouseRelatively`, `hotkeys` and `localSlot` on every event, and a second
lock for them would double the per-event cost for no gain. `reconfigure(_:)`
writes only those fields, so a settings change cannot race a switch.
2. **The virtual cursor is explicit.** Windows gets it for free: its hook sees
the real pointer, which the OS keeps moving, and it clamps a copy
(`InputHook.cs:287-309`). On macOS the pointer is frozen by
`CGAssociateMouseAndMouseCursorPosition(false)`, so the same clamped position
is kept in `RoutingState` and advanced from `mouseEventDeltaX/Y`. It is
seeded on every *local* mouse move from the real pointer, which means the
Engine does not have to seed it at a switch.
3. **`SwitchLocation.Count` is not ported.** On Windows the first couple of
mouse events after a switch have their coordinates replaced by the landing
point (`InputHook.cs:268-284`). Because the virtual cursor is ours, the same
effect is reached by the Engine writing `RoutingState.virtualCursor` to the
landing point when it applies `SwitchAction.moveCursor`, and the next move
packet then carries landing + delta rather than landing exactly. One packet
differs by one mouse delta; nothing else does. The counter, its reset and the
`Event.cs:97` suppression all disappear with it.
4. **Easy Mouse is read from the live modifier state**, not from the
"last key event was a Ctrl/Shift down" latch of `InputHook.cs:375, 467-473`.
Windows clears the latch on *any* key-up, so on Windows typing while holding
Ctrl in Ctrl mode silently disables edge switching until Ctrl is released and
pressed again. Reading `modifiers.control` is simpler and strictly better;
the wire is unaffected.
5. **Hotkeys are not matched on auto-repeat.** Windows matches every repeated
`WM_KEYDOWN`, so holding ⌘⌃⌥L there reads as the 500 ms double press
(`InputHook.cs:544`) and locks every machine. Skipping repeats costs nothing
and removes an accident.
6. **Overflow always routes local, transition or not.** contracts C3 only
demands it for transitions, but a ring that cannot take a *coalesced* motion
event means the Engine has stopped draining entirely, and the safe state for a
Mac whose Engine is stuck is to have its own keyboard back (invariant 3).
7. **Ctrl+Alt+Delete is not special.** On Windows it is a switch-to-local
trigger (`InputHook.cs:427-448`) because the secure attention sequence is
about to take the desktop away. macOS has no equivalent; ⌃⌥⌘Escape is the
mac escape, and it is checked before every veto so nothing can shadow it.
8. **`Cursor.park` applies the gate itself.** The session-matrix Handshakes
require the `destinationIsRemote || byHideMouseMessage` test
(`Common.cs:1488`) before the pointer moves, and pushing it into the one
function that moves the pointer means no consumer can forget it. `park`
returns the position either way, because Windows records `LastPos`
unconditionally.
9. **A relative move is coalesced by summing.** The first version replaced the
older entry, which is right for an absolute position and loses motion for a
`MOVE_MOUSE_RELATIVE` delta. Fixed in the same lane.
Deviations from the brief: the brief listed the device masks 0x01..0x40 and
omitted `NX_DEVICERCTLKEYMASK 0x2000`, without which the right Control key
never produces a transition; it is in `KeyMap` and in §10.4 note 10. The brief
also asked for `isExtended(vk:)`; it takes the keycode too, for the reason in
Handshakes.
Unverified, for CP1: the sign of `scrollWheelEventFixedPtDeltaAxis2` against
Windows' `WM_MOUSEHWHEEL` (§10.4 note 10), and the `kVK_Help` → `VK_INSERT`
and `kVK_ANSI_KeypadClear` → `VK_NUMLOCK` choices, which map by physical
position rather than by label.
## QA log
## Review
+79
View File
@@ -697,3 +697,82 @@ sees them. One subsection per lane, appended, never rewritten.
makes a macOS stream read mean exactly what `ReadEx(buf, 0, PACKAGE_SIZE)`
means on Windows (`:574`), including "a short count is an `Invalid` package
and a zero count is an `Error` package" (`:574-578, 588-593`).
### 10.4 input-capture (2026-09-16)
1. **Hotkey matching is one-sided, which is why the Ctrl+Alt block needs its
own veto.** `Common.HotkeyMatched` (`Common.cs:127-129`) tests only that
the code is equal and that every modifier the hotkey *asks for* is down;
extra modifiers are ignored. So Win+Ctrl+Alt+L still fires with Shift also
held, while the switch-machine keys, which are matched by arithmetic rather
than by a `HotkeySettings` (`InputHook.cs:611-614`), are guarded by an
explicit `shiftDown || winDown → return true` (`:604-610`, issue #26597).
Only the second family is protected.
2. **`Md.WheelDelta` carries three unrelated things.** For `WM_MOUSEWHEEL` /
`WM_MOUSEHWHEEL` it is a signed multiple of 120; for `WM_XBUTTON*` it is the
button index 1 or 2; for `NextMachine (121)` it is a machine id (§4.4). The
sender extracts it as `(short)((mouseData >> 16) & 0xffff)`
(`InputHook.cs:254`) — a *signed* 16-bit read, so a wheel notch towards the
user arrives as −120 and not as 65416.
3. **While a remote machine is controlled, the coordinates on the wire come
from a virtual cursor, not from the pointer.** The hook keeps
`hookCallbackMouseData.X/Y`, adds the raw delta from the real pointer to it,
and clamps the result to `PrimaryScreenBounds ± 1` (`InputHook.cs:287-309`).
That clamped value is what `Event.cs:112-113` scales to 0..65535 and what
edge detection is fed, which is how the *controller's* primary monitor
becomes the rectangle a controlled machine's pointer roams (§4.4). On macOS
the real pointer is frozen by `CGAssociateMouseAndMouseCursorPosition(false)`
while deltas keep arriving, so the same virtual cursor is kept explicitly.
4. **The relative bias is applied unconditionally; the setting only chooses
which pair of numbers is sent.** `InputHook.cs:311-312` adds
`MOVE_MOUSE_RELATIVE` to every `dx`/`dy` it computes, zero included, whether
or not `MoveMouseRelatively` is on. `Event.cs:105` then picks the tagged
deltas when the setting is on and the absolute pair when it is off, so its
`Math.Abs(dx) >= MOVE_MOUSE_RELATIVE` test is always true on that path and
is not a second condition.
5. **A pending switch overrides the next few mouse packets.** After
`PrepareToSwitchToMachine` sets `SwitchLocation`, the hook replaces the
coordinates of the next `SwitchLocation.Count` mouse events with the landing
point — in pixels when it is `XY_BY_PIXEL`-tagged, otherwise scaled from the
controller's primary monitor — and calls `Common.HideMouseCursor(false)`
once (`InputHook.cs:268-284`). `Event.cs:97` suppresses the outgoing packet
entirely while that counter is positive.
6. **`LLKHF_EXTENDED` and `LLKHF_ALTDOWN` are read from the Windows hook
struct, never computed** (`InputHook.cs:348`), so a non-Windows sender has to
synthesise them: `ALTDOWN` from its own Alt state, `EXTENDED` from the fixed
Windows set — the navigation block, right Control and right Alt, both Windows
keys, keypad divide, Num Lock and the keypad's Enter. The keypad Enter is the
only key where the bit is load-bearing rather than cosmetic: it and Return
share `VK_RETURN 0x0D` and the receiver tells them apart by the bit
(`InputSimulation.cs:108-157`).
7. **`ReleaseAllKeys` releases eleven virtual keys, not eight.** The list is
`LSHIFT, LCONTROL, LMENU, LWIN, RSHIFT, RCONTROL, RMENU, RWIN, SHIFT, MENU,
CONTROL` (`InitAndCleanup.cs:225-229`), each sent only if
`GetAsyncKeyState` says it is down, and the whole routine is rate-limited to
once per 2 s (`:215-220`).
8. **Two input counters, and only one of them means "a human is here".**
`Event.InputEventCount` is bumped for every hook callback including our own
injected events (`InputHook.cs:209, 339`); `Event.RealInputEventCount` is
bumped only after the `RealData` check (`:223, 345`). It is the second one
`SendAwakeBeat` compares (§3.3), so a machine being driven remotely does not
keep its own screensaver awake.
9. **Monitor enumeration seeds the desktop from the primary and never unions
it.** `GetScreenConfig` copies `Screen.PrimaryScreen.Bounds` into both
rectangles first (`WinAPI.cs:122-125`), and `MonitorEnumProc` extends
`newDesktopBounds` only in the `else` branch, i.e. only for monitors that are
*not* at the origin (`:70-102`). The corner list (`SensitivePoints`,
`:104-109`) is built from `rcMonitor`'s exclusive right/bottom, so the
corners of a 1920×1080 monitor at the origin are (0,0), (1920,0),
(1920,1080), (0,1080) — one pixel outside the monitor on two sides.
`CGDisplayBounds` uses the same half-open convention, so the macOS corners
are computed the same way.
10. **macOS-side facts this lane established.** Left and right modifiers are
distinguished by the device bits of `CGEvent.flags`, which `CGEventFlags`
does not expose: `NX_DEVICELCTLKEYMASK 0x01`, `LSHIFT 0x02`, `RSHIFT 0x04`,
`LCMD 0x08`, `RCMD 0x10`, `LALT 0x20`, `RALT 0x40` and — not adjacent to the
others — `NX_DEVICERCTLKEYMASK 0x2000`, with Caps Lock's state in
`NX_ALPHASHIFTMASK 0x10000`. Keys with no Windows virtual-key code (`fn`,
the keypad `=`, the JIS-only keys) cannot be sent at all and stay local. The
sign convention of `scrollWheelEventFixedPtDeltaAxis2` against Windows'
"positive `WM_MOUSEHWHEEL` means scroll right" is **not yet verified** and
is a CP1 question.