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, plustapDisabledByTimeout/tapDisabledByUserInput. The run-loop source is added to aCFRunLoopon a dedicatedThread, never the main thread (C3). A.defaultTapneeds 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 WindowsRealDataflag (InputHook.cs:213-220, 340-343); (2) read theRoutingSnapshot; (3) match hotkeys — the escape set (InputTypes) flips the snapshot to local inside the callback and is swallowed; other hotkeys are queued as.hotkeyand swallowed; (4) if the destination is remote, convert toCapturedInput, push, returnnil(swallow:InputHook.cs:361-368keyboard,:322-325mouse); if local, push mouse moves only (soEdgecan watch for a crossing) and pass everything through. No allocation-heavy work, no locks beyond the snapshot's uncontendedOSAllocatedUnfairLock(invariant 4). - The queue is a bounded ring of 4096
CapturedInputs inMWBMac/CaptureQueue.swift(it needs a lock, whichMWBCoremay 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:
wVkfromKeyMap.vk(forKeycode:);dwFlags=LLKHFbits (WM.cs:47-54):UP 0x80on key-up,EXTENDED 0x01for the keys Windows marks extended (right Ctrl/Alt, arrows, Ins/Del/ Home/End/PgUp/PgDn, numpad Enter/divide, Win keys),ALTDOWN 0x20while 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 ofVK_LCONTROL 0xA2/RCONTROL 0xA3,LSHIFT 0xA0/RSHIFT 0xA1,LWIN 0x5B/RWIN 0x5C(⌘ = Win, README D4),LMENU 0xA4/RMENU 0xA5(⌥ = Alt). Caps Lock isVK_CAPITAL 0x14as a down+up pair on each toggle;fnis ignored. KeyMapis a static table inMWBCorekeyed by macOS virtual keycode (thekVK_*numbers written as literals with their names in comments —Carbonmay 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 whatinput-injectuses.- Mouse encoding (
InputHook.cs:245-260,WM.cs:27-40):dwFlags= theWM_*id; buttons 0/1/2 = L/R/M, buttons 3/4 =WM_XBUTTON*withWheelDelta= 1/2; moves are absolute 0..65535 against the primary display (Event.cs:112-113) — or, inMoveMouseRelativelymode,mouseEventDeltaX/Ybiased byCoordinates(§4.4). Scroll: the fixed-point line delta × 120 accumulated into a remainder so trackpad scrolling emits whole 120-unit steps (WM_MOUSEWHEELaxis 1,WM_MOUSEHWHEELaxis 2, sign as Windows: up/away = +120). - Hotkeys (
InputHook.cs:539-658,MouseWithoutBordersProperties.cs): switch-machine = ⌃⌥ +HotKeySwitchMachineVK 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 inCaptureConfigas 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 forEnable, only while ⌃ / ⇧ is held for those modes, never forDisable; 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 onNSApplication.didChangeScreenParametersNotificationand reported to the Engine so it can rebuildEdgeConfig. - Cursor (
Common.cs:1482-1496,InputHook.cs:293-309): while a remote is controlled,CGAssociateMouseAndMouseCursorPosition(false)keeps the real pointer parked (deltas still arrive) andCGDisplayHideCursorhides it; parking = warp to (primary centre-x, y = 4) whenHideMouseis on, else primary centre; on return, re-associate, show, warp to the last local position.parkCursoractions fromSwitcherare applied by the consumer rule in the session-matrix Handshakes (move only whendestinationIsRemote || byHideMouseMessage). - Permissions:
Permissions.preflight()stays;request()callsCGRequestListenEventAccess()/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 callrequest()themselves. - Tap loss (
InputHook.cshas no equivalent; C2): ontapDisabledByTimeout/ByUserInputthe callback re-enables the tap withCGEvent.tapEnableand flips the snapshot to local, then reports.tapLost; the Engine releases keys.
Handshakes
Consumed
session-matrix:Coordinates(universal/relative encoding),EdgeConfigshape,Direction,SwitchAction.parkCursorconsumer rule.wire-core:Packet,MouseData/KeyboardDatafield layout for the valuesCapturedInputcarries.
Promised (to input-inject, app-shell, extras)
// 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: addrequest()and the health check.docs/protocol.md: append §10.4 with anything learned, cited.