input-inject
Goal
The Mac's side of InputSimulation.cs: turn trusted Keyboard and
Mouse packets into CGEvents posted to the HID event tap, tagged so
our own EventTap passes them through, with the click-count, held-key
and cursor-bounds bookkeeping macOS needs and Windows gets for free from
SendInput. Also the local reactions to remote chords
(InputSimulation.cs:358-475): Win+L locks this Mac, Ctrl+Alt+Del is
ignored, and releaseAll() — the ReleaseAllKeys of
InitAndCleanup.cs:214-243 — that contracts C2 calls on every recovery.
Assumptions
Written before the work; amended 2026-09-16 where the code shipped differently. Each amendment is marked (amended) and explained in the work log.
- One
CGEventSource(stateID: .hidSystemState)perInjector, withuserData = InputTypes.injectedEventTagso every event it creates carries the tag ineventSourceUserDataand the tap'sRealDatacheck (InputHook.cs:213-220) passes it through. Events are posted with.post(tap: .cghidEventTap), the closest thing toSendInput. - Keyboard (
InputSimulation.cs:108-157):wVk→KeyMap.keycode(forVK:); unknown VKs are dropped and counted (Windows wouldMapVirtualKeythem; we have no keycode to post).LLKHF.UP→ key up. Modifier VKs (LSHIFT…RWIN,SHIFT/CONTROL/MENUgeneric forms mapped to the left key) post as key events for the modifier keycode, (amended) re-typed to.flagsChangedbefore posting — macOS does not do that conversion for us, and akeyDownfor keycode 56 is not how anything learns that Shift is down (docs/protocol.md §10.5 note 7). The injector keeps aKeyStateof held modifiers and setsevent.flagson every posted key and mouse event from it, otherwise ⌘C from a Windows keyboard arrives as a bare C. (amended)EXTENDEDis not informational:VK_RETURNwith the bit set is the keypad's Enter, which is the one key the table cannot distinguish (KeyMap.keycode(forVK:)gives back the main Return). Repeats arrive as repeated downs and are posted as such withkeyboardEventAutorepeat = 1after the first. The 10 ms sleep after key-up (Event.cs:268-271) is the sender's, not ours — and is dead code there too (docs/protocol.md §10.5 note 1). - Caps Lock:
VK_CAPITALdown+up toggles; post the keycode pair and let the system toggle the LED state. (amended) The pair is posted as.flagsChangedlike the other modifiers, and the injector also tracks the lock itself sokCGEventFlagMaskAlphaShiftis set on the events it posts whether or not the hardware state followed. - Mouse (
InputSimulation.cs:160-219):dwFlagsis aWM_*id.WM_MOUSEMOVEwith absolute coordinates → (amended)Coordinates.absoluteMove(…)onto the desktop and thenfromUniversalover the primary bounds, becauseMOUSEEVENTF_ABSOLUTEis 0..65535 over the primary monitor and that second scaling is whatSendMouse(:165-173) is undoing (docs/protocol.md §10.5 note 5); with the relative bias → delta applied to the current pointer (Receiver.cs:147-153); the result is clamped to the desktop union. (amended) Buttons and wheels are posted at the current pointer, never at the packet's coordinates, because Windows discards those (§10.5 note 4). A move while a button is held posts the matching*MouseDraggedtype (macOS needs it for drags; Windows does not distinguish). Buttons: L/R/M down/up → the CG button types withmouseEventButtonNumber0/1/2;WM_XBUTTON*withWheelDelta1/2 →.otherMouseDown/Upwith button number 3/4. Windows drops*DBLCLK(noMOUSEEVENTFcase); double clicks arrive as two downs, so click count is ours: consecutive downs of the same button withinNSEvent.doubleClickIntervaland 4 px setmouseEventClickState2, 3…, reset otherwise. - Wheel:
WM_MOUSEWHEEL→CGEvent(scrollWheelEvent2Source:units: .line, wheelCount: 1, wheel1: WheelDelta / 120);WM_MOUSEHWHEEL→wheelCount: 2, wheel2:. Sign: Windows +120 is away from the user, which is CG line +1. The user's "natural scrolling" preference is applied by the system to posted events too; whether that matches what they expect from a remote mouse is a CP1 question, recorded in §10.5. - Remote chords (
InputSimulation.cs:358-475): the injector tracks the remote's Win/Ctrl/Alt/Shift from the VKs it receives; Win+L (VK_Lwith Win held) locks this Mac by running/System/Library/CoreServices/Menu Extras/User.menu/Contents/Resources/CGSession -suspendrather than injecting the chord (which would open Spotlight-like shortcuts); Ctrl+Alt+Del is swallowed and logged; Ctrl+Alt+End (service start) is ignored (README D6). (amended) A fourth chord belongs here: the receiver's ownHotKeyLockMachine(:406-416), matched against the remote's modifiers and against this Mac's setting, which is how the lock hotkey actually reaches a peer (§10.5 note 2).InjectorConfig.lockMachinecarries it. Ctrl+Alt+End is not eaten by Windows, so the key still posts here. releaseAll()posts key-up for every key and button the injector believes is down — a superset of Windows' fixed modifier list (InitAndCleanup.cs:214-243) because a lost key-up for a letter is as bad as for Shift — then clearsKeyState. Rate limit of once per 2 s (:218) is not ported: recovery must always work (C2). (amended) Ordinary keys are released before modifiers, so a release cannot spell a shortcut on the way out, and the chord booleans are cleared afterwards (ResetSystemKeyFlags,:477-480) — Windows leaves them, but we have just released the keys they describe.- Threading: the injector is driven by the Engine actor and posts
from its own serial
DispatchQueue; posting is thread-safe but the bookkeeping is not, so all of it lives on that queue. (amended) The class is@unchecked Sendable(justified in the file header) rather than non-Sendable:releaseAll()has to be callable from the quit and signal handlers (C2, last row), which cannot hop onto an actor.injectisasynconto the queue; the accessors andreleaseAllarequeue.sync. - Cursor bounds come from
ScreenLayoutpassed in with each packet; the injector never callsScreensitself.
Handshakes
Consumed
input-capture:InputTypes.injectedEventTag,WindowsMessage,KeyFlag,KeyMap.keycode(forVK:),KeyMapmodifier VKs and device masks,KeyMap.keypadEnterKeycode,Hotkey/HotkeyConfig,ModifierState,ScreenLayout,EventTap.now()(the lane's monotonic clock), and the promise that tagged events are passed through untouched.session-matrix:Coordinates.absoluteMove,Coordinates.fromUniversal,Coordinates.isRelative/untagRelative,Coordinates.centre.wire-core:Packet.type,Packet.mouse,Packet.keyboard,MouseData,KeyboardData.
Promised (to app-shell)
As shipped 2026-09-16. Two public types in MWBMac, both in the lane's
own files; nothing else in the target changed.
// MWBMac/Injector.swift
public struct InjectorConfig: Sendable, Equatable {
public var lockMachine: Hotkey // HotKeyLockMachine, matched on receive
public init(lockMachine: Hotkey = HotkeyConfig().lock)
}
public final class Injector: @unchecked Sendable {
public static let cgSessionPath: String
public init(config: InjectorConfig = InjectorConfig())
public func reconfigure(_ config: InjectorConfig)
public func inject(_ packet: Packet, layout: ScreenLayout) // .keyboard / .mouse; else ignored
public func releaseAll() // C2; any thread, blocks until posted
public func lockThisMac() // CGSession -suspend
public static func lockChord(for hotkey: Hotkey) -> [KeyboardData] // downs then ups
public var canInject: Bool { get } // false ⇒ no CGEventSource, all injection is a no-op
public var droppedUnmappedKeys: UInt64 { get }
public var remoteModifiers: ModifierState { get }
public var isHoldingAnything: Bool { get }
}
// MWBMac/KeyState.swift
public struct KeyDecision: Sendable, Equatable { // InputProcessKeyEx's verdict
public var eatKey, releaseAllKeys, lockMachine: Bool
public static let inject: KeyDecision
}
public struct KeyState: Sendable {
public static let end, delete, letterL, shift, control, menu: Int32 // VK.cs
public static let modifierVKs: Set<Int32>
public static func reportsAsFlagsChanged(vk: Int32) -> Bool
public static func normalise(vk: Int32) -> Int32 // side-less VK → left key
public static func positionalFlags(forKeycode: Int64) -> UInt64
public static let shiftMask, controlMask, optionMask, commandMask,
numericPadMask, secondaryFnMask: UInt64
public init()
public private(set) var chord: ModifierState // the *remote* keyboard's modifiers
public private(set) var heldKeys: Set<Int32>
public private(set) var heldButtons: [Int64: Int64] // button → click count
public private(set) var capsLockOn: Bool
public mutating func process(vk: Int32, isUp: Bool, lockMachine: Hotkey) -> KeyDecision
public mutating func resetChord(keeping: Hotkey); public mutating func resetChord()
public func isHeld(_ vk: Int32) -> Bool
public mutating func note(vk: Int32, down: Bool)
public func releaseOrder() -> [Int32] // ordinary keys, then modifiers
public mutating func buttonDown(_ number: Int64, clickState: Int64)
public mutating func buttonUp(_ number: Int64) -> Int64
public var draggingButton: Int64? { get }
public func buttonReleaseOrder() -> [(number: Int64, clickState: Int64)]
public var eventFlags: UInt64 { get }
}
public struct ClickTracker: Sendable {
public static let movementTolerance: CGFloat // 4
public var interval: TimeInterval // NSEvent.doubleClickInterval
public init(interval: TimeInterval)
public mutating func click(button: Int64, at: CGPoint, now: TimeInterval) -> Int64
public mutating func reset()
}
Four deviations from the shape sketched at planning time, all deliberate:
Injectortakes anInjectorConfig. The receiver matches the lock hotkey itself (§10.5 note 2), so it needs that one setting; C4 says a lane before app-shell takes a config struct rather thanSettings.Injectoris@unchecked Sendable, so the quit and signal handlers of C2 can callreleaseAll().KeyStateandClickTrackerare public. They are the injector's state, but the Engine will wantremoteModifiersand the menu barisHoldingAnything, and a value type with no I/O is easier to reason about public than hidden.Injector.lockChord(for:)is a static encoder, not a send. See the request below.
Answering input-capture's open requests
- Every posted event carries
InputTypes.injectedEventTag. Done: the tag is on the singleCGEventSourcethe injector owns, so every event it creates carries it,releaseAll()'s synthetic ups included. There is no code path that posts an event from another source. Injectorperforms.lockMachine/.lockAllMachinesby sending the chord. Partly declined, redirected to app-shell. The injector has no peer connections and C1 says only the Engine stamps and distributes packets, so sending from here would be a contract violation. What ships instead isInjector.lockChord(for:), the encoding half — Windows'GetVkCodesListorder, downs then ups (InputHook.cs:485-512, 548-562) — which the Engine forwards, pluslockThisMac()for the local half.
Requested of app-shell (open)
- On
HotkeyAction.lockMachine, forwardInjector.lockChord(for: settings.lockMachineShortcut)to the machine in control. On.lockAllMachines, switch to ALL mode, forward the same chord, switch back, then callInjector.lockThisMac()(InputHook.cs:544-566). - Call
injector.releaseAll()on every C2 recovery row, and on every switch, mode change and lock — it is theReleaseAllKeysthose rows name. - Hand
ScreenLayoutin on everyinject(_:layout:)fromScreens.layout; the injector never reads the displays itself. - Map
Settings.HotKeyLockMachineontoInjectorConfig.lockMachineand callreconfigure(_:)when it changes, or a remote lock chord will be matched against the default ⌘⌃⌥L. canInject == falsemeans the process has noCGEventSource; show it next to the permissions state.
Status / TODO
Sources/MWBMac/KeyState.swift: held keys/buttons, modifier flag word, click-count tracking, remote-chord state (InputSimulation.cs:358-475,InitAndCleanup.cs:214-243).Sources/MWBMac/Injector.swift: the tagged source, keyboard and mouse posting per Assumptions, wheel, clamping,releaseAll,lockThisMac, Ctrl+Alt+Del handling (InputSimulation.cs:82-219, 440-475,Receiver.cs:147-153).docs/protocol.md: append §10.5 with anything learned, cited.
Work log
2026-09-16 — dev (lane input-inject, from 3c51e95)
Shipped Sources/MWBMac/KeyState.swift (362 lines) and
Sources/MWBMac/Injector.swift (425 lines); no other source file
touched. tools/gates.sh green. Nothing was run that posts a CGEvent,
locks the screen or moves the cursor (CLAUDE.md invariant 5) — this lane
was verified by building and by reading the Windows source, not by
injecting.
What was ported.
InputSimulation.SendKey(:108-157) →Injector.injectKey/postKey:LLKHF.UP→ key up,LLKHF.EXTENDEDused to pick the keypad's Enter over Return,MapVirtualKeydropped (macOS needs no scan code), unknown VKs counted rather than posted.InputSimulation.InputProcessKeyEx(:372-480) →KeyState.process: the four intercepted chords, the side-specific modifier booleans,ResetModifiersState,ResetSystemKeyFlags.InputSimulation.SendMouse(:160-233) andMoveMouseRelative(:283-301) →Injector.injectMouseand theWM_*switch, with the receive-side coordinate rules ofReceiver.cs:147-153.InitAndCleanup.ReleaseAllKeys(:214-243) →Injector.releaseAll.InputHook.GetVkCodesList(:485-512) →Injector.lockChord(for:).
Decisions and deviations (the amended Assumptions above say where; the reasoning here).
- Modifiers post as
.flagsChanged, not as key presses. The Assumptions said macOS "delivers" a modifier keycode asflagsChanged; it does not — that conversion has to be made by the poster. AkeyDownfor keycode 56 leaves every app believing Shift is up. The event is built withCGEvent(keyboardEventSource:…)and itstypeset to.flagsChanged; the flag word is still put on every other posted event, because injected input gets no global modifier state on macOS. Recorded as §10.5 note 7. - Absolute moves go through
Coordinates.absoluteMoveandfromUniversalover the primary bounds, notfromUniversalover the desktop as the Assumptions said.MOUSEEVENTF_ABSOLUTEis 0..65535 over the primary monitor, which is the whole reasonSendMouserescales the desktop into primary units; skipping the second step would have produced the right answer only when the desktop and the primary monitor are the same rectangle. §10.5 note 5. - Buttons and wheels are posted at the current pointer. Windows
computes a position for them and
SendInputthrows it away (§10.5 note 4); on macOS the location on a button event is load bearing, and the current pointer is the position the preceding move packet already put it at. This also makes the relative-mode path fall out for free — it is exactly whatReceiver.cs:149-151does by hand. KeyStatekeeps the chord booleans and the held-key set apart. Folding them together looked tempting and is a bug: the lock hotkey runsResetModifiersState, which would then delete keys from the release list while they are still physically down, and a modifier that is never released is exactly the failure invariant 3 forbids. Windows keeps them apart too — chord booleans vsGetAsyncKeyState.releaseAll()releases ordinary keys before modifiers and then clears the chord. Windows releases only its eleven modifier VKs and leaves the booleans; ours has to cover letters too because we, not the OS, are the only record of what we posted.- The 10 ms post-key-up sleep is not ported, and the TODO line that
asked for it "only if needed" is answered no. It is the sender's,
and it is dead code on Windows as well: the condition compares
LLKHFbits againstWM_KEYUP. §10.5 note 1. - Click counting and
NSEvent.doubleClickIntervalare as the Assumptions describe; the clock isEventTap.now()(monotonic) so an NTP step cannot manufacture a double click. The click count is remembered per button so the up repeats it, which AppKit requires. - Positional flags (
NumericPad,SecondaryFn) are synthesised from the keycode for the keypad, the arrows, the navigation block and the function keys — real macOS events carry them and some text views read them. Windows has no equivalent; this is the mirror image of input-capture synthesisingLLKHF_EXTENDED(§10.4 note 6). - Two CP1 questions recorded, not decided: remote ⌘L locks this Mac (faithful to Win+L with D4's Win=⌘, but ⌘L is a common Mac shortcut), and whether "natural scrolling" should apply to a remote wheel.
Open handshake requests are in Handshakes above: five to app-shell, and input-capture's request 2 partly declined with a redirect (the injector encodes the lock chord, the Engine sends it).