Files
mac_without_borders/docs/features/input-inject/README.md
T

18 KiB

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) per Injector, with userData = InputTypes.injectedEventTag so every event it creates carries the tag in eventSourceUserData and the tap's RealData check (InputHook.cs:213-220) passes it through. Events are posted with .post(tap: .cghidEventTap), the closest thing to SendInput.
  • Keyboard (InputSimulation.cs:108-157): wVk → KeyMap.keycode(forVK:); unknown VKs are dropped and counted (Windows would MapVirtualKey them; we have no keycode to post). LLKHF.UP → key up. Modifier VKs (LSHIFT…RWIN, SHIFT/CONTROL/MENU generic forms mapped to the left key) post as key events for the modifier keycode, (amended) re-typed to .flagsChanged before posting — macOS does not do that conversion for us, and a keyDown for keycode 56 is not how anything learns that Shift is down (docs/protocol.md §10.5 note 7). The injector keeps a KeyState of held modifiers and sets event.flags on every posted key and mouse event from it, otherwise ⌘C from a Windows keyboard arrives as a bare C. (amended) EXTENDED is not informational: VK_RETURN with 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 with keyboardEventAutorepeat = 1 after 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_CAPITAL down+up toggles; post the keycode pair and let the system toggle the LED state. (amended) The pair is posted as .flagsChanged like the other modifiers, and the injector also tracks the lock itself so kCGEventFlagMaskAlphaShift is set on the events it posts whether or not the hardware state followed.
  • Mouse (InputSimulation.cs:160-219): dwFlags is a WM_* id. WM_MOUSEMOVE with absolute coordinates → (amended) Coordinates.absoluteMove(…) onto the desktop and then fromUniversal over the primary bounds, because MOUSEEVENTF_ABSOLUTE is 0..65535 over the primary monitor and that second scaling is what SendMouse (: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 *MouseDragged type (macOS needs it for drags; Windows does not distinguish). Buttons: L/R/M down/up → the CG button types with mouseEventButtonNumber 0/1/2; WM_XBUTTON* with WheelDelta 1/2 → .otherMouseDown/Up with button number 3/4. Windows drops *DBLCLK (no MOUSEEVENTF case); double clicks arrive as two downs, so click count is ours: consecutive downs of the same button within NSEvent.doubleClickInterval and 4 px set mouseEventClickState 2, 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_L with Win held) locks this Mac by running /System/Library/CoreServices/Menu Extras/User.menu/Contents/Resources/CGSession -suspend rather 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 own HotKeyLockMachine (: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.lockMachine carries 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 clears KeyState. 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. inject is async onto the queue; the accessors and releaseAll are queue.sync.
  • Cursor bounds come from ScreenLayout passed in with each packet; the injector never calls Screens itself.

Handshakes

Consumed

  • input-capture: InputTypes.injectedEventTag, WindowsMessage, KeyFlag, KeyMap.keycode(forVK:), KeyMap modifier 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:

  • Injector takes an InjectorConfig. 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 than Settings.
  • Injector is @unchecked Sendable, so the quit and signal handlers of C2 can call releaseAll().
  • KeyState and ClickTracker are public. They are the injector's state, but the Engine will want remoteModifiers and the menu bar isHoldingAnything, 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

  1. Every posted event carries InputTypes.injectedEventTag. Done: the tag is on the single CGEventSource the 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.
  2. Injector performs .lockMachine / .lockAllMachines by 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 is Injector.lockChord(for:), the encoding half — Windows' GetVkCodesList order, downs then ups (InputHook.cs:485-512, 548-562) — which the Engine forwards, plus lockThisMac() for the local half.

Requested of app-shell (open)

  1. On HotkeyAction.lockMachine, forward Injector.lockChord(for: settings.lockMachineShortcut) to the machine in control. On .lockAllMachines, switch to ALL mode, forward the same chord, switch back, then call Injector.lockThisMac() (InputHook.cs:544-566).
  2. Call injector.releaseAll() on every C2 recovery row, and on every switch, mode change and lock — it is the ReleaseAllKeys those rows name.
  3. Hand ScreenLayout in on every inject(_:layout:) from Screens.layout; the injector never reads the displays itself.
  4. Map Settings.HotKeyLockMachine onto InjectorConfig.lockMachine and call reconfigure(_:) when it changes, or a remote lock chord will be matched against the default ⌘⌃⌥L.
  5. canInject == false means the process has no CGEventSource; 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.EXTENDED used to pick the keypad's Enter over Return, MapVirtualKey dropped (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) and MoveMouseRelative (:283-301) → Injector.injectMouse and the WM_* switch, with the receive-side coordinate rules of Receiver.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).

  1. Modifiers post as .flagsChanged, not as key presses. The Assumptions said macOS "delivers" a modifier keycode as flagsChanged; it does not — that conversion has to be made by the poster. A keyDown for keycode 56 leaves every app believing Shift is up. The event is built with CGEvent(keyboardEventSource:…) and its type set 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.
  2. Absolute moves go through Coordinates.absoluteMove and fromUniversal over the primary bounds, not fromUniversal over the desktop as the Assumptions said. MOUSEEVENTF_ABSOLUTE is 0..65535 over the primary monitor, which is the whole reason SendMouse rescales 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.
  3. Buttons and wheels are posted at the current pointer. Windows computes a position for them and SendInput throws 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 what Receiver.cs:149-151 does by hand.
  4. KeyState keeps the chord booleans and the held-key set apart. Folding them together looked tempting and is a bug: the lock hotkey runs ResetModifiersState, 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 vs GetAsyncKeyState.
  5. 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.
  6. 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 LLKHF bits against WM_KEYUP. §10.5 note 1.
  7. Click counting and NSEvent.doubleClickInterval are as the Assumptions describe; the clock is EventTap.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.
  8. 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 synthesising LLKHF_EXTENDED (§10.4 note 6).
  9. 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).

QA log

Review