Files
mac_without_borders/Sources/MWBMac/Injector.swift
T
lucioandClaude Opus 5 e0123a1745 input-inject: KeyState and Injector — CGEvent posting for Keyboard/Mouse packets
Ports InputSimulation.SendKey/SendMouse/InputProcessKeyEx and
InitAndCleanup.ReleaseAllKeys onto CGEvent posting: one tagged
hidSystemState source, held-key/button bookkeeping on the injector's
serial queue, click counting macOS needs and Windows drops, the
relative/absolute coordinate rules of Receiver.cs:147-153, and the
remote Win+L / Ctrl+Alt+Del interception.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-16 02:47:10 -07:00

408 lines
18 KiB
Swift

// The Mac's `InputSimulation`: trusted `Keyboard` and `Mouse` packets turned
// into `CGEvent`s and posted to the HID event tap.
//
// Ported from App/Class/InputSimulation.cs — `SendKey` (108-157), `SendMouse`
// (160-233), `MoveMouseRelative` (283-301) and `InputProcessKeyEx` (372-480) —
// with the receive-side coordinate rules of App/Core/Receiver.cs (117-186).
//
// Three things macOS needs that Windows gets for free from `SendInput`, all of
// them in `KeyState.swift`: the modifier flag word every event carries, the
// click count that makes a double click a double click, and the list of what we
// are holding down so `releaseAll()` can let go of it (contracts C2).
//
// CLAUDE.md invariant 2: nothing here is reached by a packet that did not
// decrypt and validate — `Session` delivers only trusted packets — and no key
// this file posts is ever logged, at any level. The counters are counters.
import AppKit
import CoreGraphics
import Foundation
import MWBCore
import os
/// The settings the injector needs. app-shell maps `Settings` onto this
/// (contracts C4); nothing here reads a settings file.
public struct InjectorConfig: Sendable, Equatable {
/// `HotKeyLockMachine`: the chord that, arriving from the machine in
/// control, locks *this* Mac (`InputSimulation.cs:406-416`).
public var lockMachine: Hotkey
/// The PowerToys default, ⌘⌃⌥L.
public init(lockMachine: Hotkey = HotkeyConfig().lock) {
self.lockMachine = lockMachine
}
}
/// Posts the input a peer sends us.
///
/// `@unchecked Sendable`: every mutable field is touched only on `queue`, the
/// injector's own serial queue, and the two immutable ones (`source`, `log`) are
/// read-only after `init`. The accessors and `releaseAll()` reach the state with
/// `queue.sync`, so nothing escapes. `CGEventSource` is a CF type without a
/// `Sendable` conformance, which is the only reason the check has to be
/// suppressed.
public final class Injector: @unchecked Sendable {
/// The Fast User Switching lock, the closest macOS equivalent of
/// `LockWorkStation` (README, Windows→macOS mapping table).
public static let cgSessionPath =
"/System/Library/CoreServices/Menu Extras/User.menu/Contents/Resources/CGSession"
private let queue = DispatchQueue(label: "com.luciochen.mwb-mac.inject")
private let log = Logger(subsystem: "com.luciochen.mwb-mac", category: "inject")
private let source: CGEventSource?
// Queue-only, from here down.
private var config: InjectorConfig
private var state = KeyState()
private var clicks: ClickTracker
private var lastPosted: CGPoint?
private var dropped: UInt64 = 0
/// An injector whose events are tagged so our own tap passes them through
/// (`InputTypes.injectedEventTag`, contracts C4, topo.md handshake 5).
///
/// `.hidSystemState` is the source `SendInput` behaves like: the events join
/// the system's own stream rather than a private one, so modifier state and
/// click counts are interpreted the way a real keyboard's are.
public init(config: InjectorConfig = InjectorConfig()) {
self.config = config
clicks = ClickTracker(interval: Injector.systemDoubleClickInterval())
source = CGEventSource(stateID: .hidSystemState)
source?.userData = InputTypes.injectedEventTag
if source == nil {
log.error("no CGEventSource: remote input cannot be injected")
}
}
/// Replaces the configuration; takes effect on the next packet.
public func reconfigure(_ config: InjectorConfig) {
queue.async { self.config = config }
}
/// How many keys arrived with a virtual-key code this keyboard has no key
/// for and were dropped. Never says *which* (invariant 2).
public var droppedUnmappedKeys: UInt64 { queue.sync { dropped } }
/// The modifiers the controlling machine is holding, as the chord logic sees
/// them (`InputSimulation.cs:358-361`). For the menu bar and debugging.
public var remoteModifiers: ModifierState { queue.sync { state.chord } }
/// Whether the event source could be created at all. False means every
/// `inject` is a no-op and the menu bar should say so.
public var canInject: Bool { source != nil }
/// Whether we believe anything is still down — a mouse button included.
public var isHoldingAnything: Bool {
queue.sync { !state.heldKeys.isEmpty || !state.heldButtons.isEmpty }
}
// MARK: - Entry point
/// Posts one `Keyboard` or `Mouse` packet. Every other type is ignored.
///
/// `layout` is this Mac's display geometry, passed in rather than read here
/// so the injector never touches `Screens` (feature README, Assumptions).
public func inject(_ packet: Packet, layout: ScreenLayout) {
switch packet.type {
case .keyboard:
let data = packet.keyboard
queue.async { self.injectKey(data) }
case .mouse:
let data = packet.mouse
queue.async { self.injectMouse(data, layout: layout) }
default:
break
}
}
// MARK: - Keyboard (`SendKey`, `InputSimulation.cs:108-157`)
private func injectKey(_ data: KeyboardData) {
let vk = KeyState.normalise(vk: data.virtualKey)
let isUp = (data.flags & KeyFlag.up) != 0
let decision = state.process(vk: vk, isUp: isUp, lockMachine: config.lockMachine)
if decision.releaseAllKeys { releaseAllOnQueue() }
if decision.lockMachine { runLock() }
if decision.eatKey {
// Ctrl+Alt+Del and the lock chord are the two the receiver swallows;
// the key itself is never named in the log (invariant 2).
log.debug("remote chord intercepted; key swallowed")
return
}
guard let keycode = keycode(for: vk, flags: data.flags) else {
dropped &+= 1
return
}
postKey(keycode: keycode, vk: vk, down: !isUp)
}
/// The macOS keycode for a virtual key, resolving the one collision Windows
/// leaves us: Return and the keypad's Enter are both `VK_RETURN`, told apart
/// by `LLKHF_EXTENDED` (`InputSimulation.cs:120-123`, docs/protocol.md §5.1).
private func keycode(for vk: Int32, flags: Int32) -> Int64? {
if vk == KeyMap.return && (flags & KeyFlag.extended) != 0 {
return KeyMap.keypadEnterKeycode
}
return KeyMap.keycode(forVK: vk)
}
private func postKey(keycode: Int64, vk: Int32, down: Bool) {
let isRepeat = down && state.isHeld(vk)
state.note(vk: vk, down: down)
guard
let event = CGEvent(
keyboardEventSource: source, virtualKey: CGKeyCode(truncatingIfNeeded: keycode),
keyDown: down)
else { return }
event.flags = CGEventFlags(
rawValue: state.eventFlags | KeyState.positionalFlags(forKeycode: keycode))
if isRepeat { event.setIntegerValueField(.keyboardEventAutorepeat, value: 1) }
event.post(tap: .cghidEventTap)
}
// MARK: - Mouse (`SendMouse`, `InputSimulation.cs:160-233`)
private func injectMouse(_ data: MouseData, layout: ScreenLayout) {
let universal = UniversalPoint(x: data.x, y: data.y)
let isMove = data.flags == WindowsMessage.mouseMove
if Coordinates.isRelative(universal) {
// `Receiver.cs:147-153`: a relative move is a delta on the current
// pointer; anything else in relative mode carries no usable position
// at all, so Windows re-reads the cursor (`:170-172`) and we do the
// same by falling through to `pointer()`.
if isMove {
let delta = Coordinates.untagRelative(universal)
let from = pointer(layout: layout)
postMove(
to: CGPoint(x: from.x + CGFloat(delta.x), y: from.y + CGFloat(delta.y)),
layout: layout)
return
}
} else if isMove {
postMove(to: absolutePoint(universal, layout: layout), layout: layout)
return
}
postButtonOrWheel(data, at: pointer(layout: layout))
}
/// Where an absolute `Mouse` packet lands: the sender scaled its pointer to
/// 0..65535 across *its* primary monitor (`Event.cs:112-113`), the receiver
/// stretches that across its own desktop and hands it back to `SendInput` as
/// a universal value over its primary monitor (`InputSimulation.cs:160-173`).
/// `Coordinates` does both halves; the pixels come out of the second one.
private func absolutePoint(_ universal: UniversalPoint, layout: ScreenLayout) -> CGPoint {
let stretched = Coordinates.absoluteMove(
universal, desktop: layout.desktop, primary: layout.primary)
return Coordinates.fromUniversal(stretched, in: layout.primary)
}
private func postMove(to point: CGPoint, layout: ScreenLayout) {
let target = Injector.clamp(point, to: layout.desktop)
let button = state.draggingButton
let type = Injector.moveType(button: button)
guard
let event = CGEvent(
mouseEventSource: source, mouseType: type, mouseCursorPosition: target,
mouseButton: Injector.cgButton(button ?? 0))
else { return }
if let button { event.setIntegerValueField(.mouseEventButtonNumber, value: button) }
let previous = lastPosted ?? target
event.setIntegerValueField(.mouseEventDeltaX, value: Int64(target.x - previous.x))
event.setIntegerValueField(.mouseEventDeltaY, value: Int64(target.y - previous.y))
event.flags = CGEventFlags(rawValue: state.eventFlags)
event.post(tap: .cghidEventTap)
lastPosted = target
}
/// The `WM_*` switch of `SendMouse` (`InputSimulation.cs:181-219`). The three
/// `*DBLCLK` messages have no case there either: Windows drops them and so do
/// we, because a double click already arrives as two downs.
private func postButtonOrWheel(_ data: MouseData, at point: CGPoint) {
switch data.flags {
case WindowsMessage.leftDown: postButton(0, down: true, at: point)
case WindowsMessage.leftUp: postButton(0, down: false, at: point)
case WindowsMessage.rightDown: postButton(1, down: true, at: point)
case WindowsMessage.rightUp: postButton(1, down: false, at: point)
case WindowsMessage.middleDown: postButton(2, down: true, at: point)
case WindowsMessage.middleUp: postButton(2, down: false, at: point)
case WindowsMessage.extraDown, WindowsMessage.extraUp:
// `WheelDelta` is the X-button index 1 or 2 here (docs/protocol.md
// §10.4 note 2); macOS numbers them 3 and 4.
let number: Int64 = data.wheelDelta == 2 ? 4 : 3
postButton(number, down: data.flags == WindowsMessage.extraDown, at: point)
case WindowsMessage.wheel: postWheel(vertical: data.wheelDelta, horizontal: 0, at: point)
case WindowsMessage.horizontalWheel:
postWheel(vertical: 0, horizontal: data.wheelDelta, at: point)
default: break
}
}
private func postButton(_ number: Int64, down: Bool, at point: CGPoint) {
let clickState: Int64
if down {
clickState = clicks.click(
button: number, at: point, now: Date().timeIntervalSinceReferenceDate)
state.buttonDown(number, clickState: clickState)
} else {
clickState = state.buttonUp(number)
}
postButtonEvent(number, down: down, at: point, clickState: clickState)
}
private func postButtonEvent(_ number: Int64, down: Bool, at point: CGPoint, clickState: Int64) {
let type = Injector.buttonType(button: number, down: down)
guard
let event = CGEvent(
mouseEventSource: source, mouseType: type, mouseCursorPosition: point,
mouseButton: Injector.cgButton(number))
else { return }
event.setIntegerValueField(.mouseEventButtonNumber, value: number)
event.setIntegerValueField(.mouseEventClickState, value: clickState)
event.flags = CGEventFlags(rawValue: state.eventFlags)
event.post(tap: .cghidEventTap)
lastPosted = point
}
/// `MOUSEEVENTF_WHEEL` / `HWHEEL` (`InputSimulation.cs:204-209`). Windows
/// counts in 120ths of a notch and macOS counts lines, so the packet's
/// `WheelDelta` divides straight down (docs/protocol.md §5.2).
private func postWheel(vertical: Int32, horizontal: Int32, at point: CGPoint) {
let lines = vertical / WindowsMessage.wheelDelta
let columns = horizontal / WindowsMessage.wheelDelta
guard lines != 0 || columns != 0 else { return }
guard
let event = CGEvent(
scrollWheelEvent2Source: source, units: .line,
wheelCount: columns != 0 ? 2 : 1, wheel1: lines, wheel2: columns, wheel3: 0)
else { return }
event.location = point
event.flags = CGEventFlags(rawValue: state.eventFlags)
event.post(tap: .cghidEventTap)
}
// MARK: - Recovery (contracts C2)
/// `InitAndCleanup.ReleaseAllKeys` (`:214-243`): let go of everything we
/// believe is down.
///
/// Windows rate-limits this to once per 2 s (`:215-220`); we do not, because
/// every trigger in contracts C2 must work the moment it fires. Safe to call
/// at any time, including from a signal handler — it blocks until the events
/// are posted, which is what an `atexit` needs.
public func releaseAll() {
queue.sync { releaseAllOnQueue() }
}
private func releaseAllOnQueue() {
for vk in state.releaseOrder() {
guard let keycode = KeyMap.keycode(forVK: vk) else {
state.note(vk: vk, down: false)
continue
}
postKey(keycode: keycode, vk: vk, down: false)
}
for button in state.buttonReleaseOrder() {
_ = state.buttonUp(button.number)
postButtonEvent(
button.number, down: false, at: lastPosted ?? CGPoint(x: 0, y: 0),
clickState: button.clickState)
}
clicks.reset()
// `ResetSystemKeyFlags` (`InputSimulation.cs:477-480`). Windows leaves the
// chord booleans alone here; we clear them, because we have just released
// the keys they describe and a stale `winDown` would swallow the next L.
state.resetChord()
}
/// Locks this Mac, the local half of a remote Win+L
/// (`InputSimulation.cs:450-460`).
public func lockThisMac() {
queue.async { self.runLock() }
}
private func runLock() {
let process = Process()
process.executableURL = URL(fileURLWithPath: Injector.cgSessionPath)
process.arguments = ["-suspend"]
do {
try process.run()
} catch {
log.error("could not run CGSession -suspend to lock this Mac")
}
}
/// The key packets a lock hotkey has to be replayed as, downs then ups, in
/// Windows' order (`InputHook.cs:485-512, 548-562`).
///
/// The tap swallowed the chord, so the machine in control sees nothing unless
/// these are forwarded to it; *sending* them is the Engine's job (contracts
/// C1 — only the Engine stamps and distributes), so this is the encoding half
/// only, and the Engine's answer to the input-capture lane's request 2.
public static func lockChord(for hotkey: Hotkey) -> [KeyboardData] {
guard !hotkey.isEmpty else { return [] }
var codes: [Int32] = []
if hotkey.option { codes.append(KeyState.menu) }
if hotkey.shift { codes.append(KeyState.shift) }
if hotkey.command { codes.append(KeyMap.leftWin) }
if hotkey.control { codes.append(KeyState.control) }
codes.append(hotkey.vk)
let downs = codes.map { KeyboardData(virtualKey: $0, flags: 0) }
let ups = codes.map { KeyboardData(virtualKey: $0, flags: KeyFlag.up) }
return downs + ups
}
// MARK: - Helpers
/// The pointer right now. Windows reads it with `GetCursorPos` on the same
/// paths (`Receiver.cs:149, 156`).
private func pointer(layout: ScreenLayout) -> CGPoint {
if let here = CGEvent(source: nil)?.location { return here }
return lastPosted ?? Coordinates.centre(of: layout.primary)
}
/// Keeps an injected point on a real display. Windows relies on `SendInput`
/// to clip; macOS will happily place the pointer off-screen.
private static func clamp(_ point: CGPoint, to desktop: CGRect) -> CGPoint {
guard desktop.width > 0, desktop.height > 0 else { return point }
return CGPoint(
x: min(max(point.x, desktop.minX), desktop.maxX - 1),
y: min(max(point.y, desktop.minY), desktop.maxY - 1))
}
/// A move is a drag while a button is held — macOS delivers the two as
/// different event types, where Windows has only `WM_MOUSEMOVE`.
private static func moveType(button: Int64?) -> CGEventType {
switch button {
case .none: return .mouseMoved
case .some(0): return .leftMouseDragged
case .some(1): return .rightMouseDragged
default: return .otherMouseDragged
}
}
private static func buttonType(button: Int64, down: Bool) -> CGEventType {
switch button {
case 0: return down ? .leftMouseDown : .leftMouseUp
case 1: return down ? .rightMouseDown : .rightMouseUp
default: return down ? .otherMouseDown : .otherMouseUp
}
}
/// `CGMouseButton` only names three buttons, so the X-buttons are created as
/// `.center` and corrected with `mouseEventButtonNumber` afterwards.
private static func cgButton(_ number: Int64) -> CGMouseButton {
switch number {
case 0: return .left
case 1: return .right
default: return .center
}
}
private static func systemDoubleClickInterval() -> TimeInterval {
let interval = NSEvent.doubleClickInterval
return interval > 0 ? interval : 0.5
}
}