# input-capture ## Goal The Mac's side of `InputHook.cs`: a `CGEventTap` that sees every key, modifier, mouse and scroll event, decides *synchronously* whether the event stays on this Mac or is swallowed for a remote one, turns it into the Windows encoding (`docs/protocol.md` §5), matches the hotkeys (§4.5) and hands everything to the Engine through a bounded queue (contracts C3). With it come the pieces the tap needs and the injector will share: the Windows-VK ↔ macOS-keycode table, the screen geometry that feeds `Edge`, the cursor parking/decoupling that keeps the real pointer still while a remote machine is controlled, and the permission preflight/ request wrapper. Invariants 3 and 4 (CLAUDE.md) and contract C2 are this lane's. ## Assumptions - **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). - **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. - **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** 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). - **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. - **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. ## 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. ### Promised (to input-inject, app-shell, extras) ```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)] } // 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:) } ``` ## Status / TODO - [ ] `Sources/MWBCore/InputTypes.swift`: tag, `RoutingSnapshot`, `CapturedInput`, `HotkeyConfig`, `Hotkey`, `EasyMouseMode` (C3, C4). - [ ] `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, overflow policy (C3). `Sources/MWBMac/RoutingState.swift`: the snapshot lock. - [ ] `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, the ignore-with-Shift/⌘ rule, escape set (`InputHook.cs:539-658`). - [ ] `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 health check. - [ ] `docs/protocol.md`: append §10.4 with anything learned, cited. ## Work log ## QA log ## Review