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]>
This commit is contained in:
lucioandClaude Opus 5 committed 2026-09-16 02:47:10 -07:00
1 parent 3c51e95969
commit e0123a1745
2 files changed
+763

No files matched your search

+407
View File
@@ -0,0 +1,407 @@
// 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
}
}
+356
View File
@@ -0,0 +1,356 @@
// What the injector believes the *remote* keyboard and mouse are doing, and
// what this Mac is therefore holding down.
//
// Windows gets all of this for free: `SendInput` updates the real keyboard
// state, `GetAsyncKeyState` reads it back, and the receiver only has to keep
// four booleans for the chords it intercepts (`InputSimulation.cs:358-361`).
// macOS gives none of it — a posted `CGEvent` carries the modifier flags the
// poster puts on it, nothing accumulates, and nothing tells us later what we
// pressed. So the bookkeeping is explicit here:
//
// * `chord` is the Windows `winDown/ctrlDown/altDown/shiftDown` pair of
// booleans, used only to recognise the chords the receiver intercepts;
// * `heldKeys`/`heldButtons` are what we have actually posted a down for and
// not yet an up — the list `releaseAll()` walks (contracts C2), and the
// source of the flag word every posted event carries.
//
// The two are deliberately separate, exactly as Windows keeps them separate:
// `ResetModifiersState` (`InputSimulation.cs:364-370`) edits the chord state
// while `ReleaseAllKeys` (`InitAndCleanup.cs:214-243`) reads the real keyboard,
// and folding them together would let a key that the chord logic "used up" stay
// physically down forever.
//
// Ported from App/Class/InputSimulation.cs (358-480), App/Core/VK.cs and
// App/Core/InitAndCleanup.cs ReleaseAllKeys (214-243).
import CoreGraphics
import Foundation
import MWBCore
/// What `InputProcessKeyEx` decided about one incoming key
/// (`InputSimulation.cs:372-475`).
public struct KeyDecision: Sendable, Equatable {
/// Windows' `eatKey`: the key is intercepted and never posted.
public var eatKey: Bool
/// `InitAndCleanup.ReleaseAllKeys()` must run before anything else.
public var releaseAllKeys: Bool
/// `NativeMethods.LockWorkStation()`: lock this machine.
public var lockMachine: Bool
/// A key that is simply posted.
public static let inject = KeyDecision(eatKey: false, releaseAllKeys: false, lockMachine: false)
/// A decision.
public init(eatKey: Bool, releaseAllKeys: Bool, lockMachine: Bool) {
self.eatKey = eatKey
self.releaseAllKeys = releaseAllKeys
self.lockMachine = lockMachine
}
}
/// The held-key, chord and Caps Lock state of the injector.
///
/// A plain value: the `Injector` owns one and mutates it only on its own serial
/// queue, so nothing here locks.
public struct KeyState: Sendable {
// MARK: - Virtual keys this file names
/// `VK_END` (`VK.cs:28`).
public static let end: Int32 = 0x23
/// `VK_DELETE` (`VK.cs:39`).
public static let delete: Int32 = 0x2E
/// `VK_L`, the Win+L of `InputSimulation.cs:450`.
public static let letterL: Int32 = 0x4C
/// `VK_SHIFT`, the side-less form `ReleaseAllKeys` and `GetVkCodesList`
/// send (`VK.cs:19`).
public static let shift: Int32 = 0x10
/// `VK_CONTROL` (`VK.cs:20`).
public static let control: Int32 = 0x11
/// `VK_MENU`, side-less Alt (`VK.cs:21`).
public static let menu: Int32 = 0x12
/// The eight side-specific modifier keys `InputProcessKeyEx` tracks
/// (`InputSimulation.cs:380-398`).
public static let modifierVKs: Set<Int32> = [
KeyMap.leftWin, KeyMap.rightWin, KeyMap.leftControl, KeyMap.rightControl,
KeyMap.leftMenu, KeyMap.rightMenu, KeyMap.leftShift, KeyMap.rightShift,
]
/// The side-less `VK_SHIFT`/`VK_CONTROL`/`VK_MENU` mapped onto the left key,
/// everything else unchanged.
///
/// Windows' hook never produces the side-less forms, but `ReleaseAllKeys`
/// (`InitAndCleanup.cs:225-229`) and the lock-chord replay
/// (`InputHook.cs:485-512`) both send them, and macOS has no key that means
/// "either Shift". Mapping to the left key is the only thing we can post.
public static func normalise(vk: Int32) -> Int32 {
switch vk {
case shift: return KeyMap.leftShift
case control: return KeyMap.leftControl
case menu: return KeyMap.leftMenu
default: return vk
}
}
// MARK: - State
/// The remote keyboard's modifiers as the chord logic sees them — Windows'
/// `winDown`/`ctrlDown`/`altDown`/`shiftDown` (`InputSimulation.cs:358-361`).
public private(set) var chord = ModifierState()
/// Every virtual key we have posted a down for and not an up.
public private(set) var heldKeys: Set<Int32> = []
/// Every mouse button we have posted a down for, with the click count that
/// down carried — the up must repeat it or AppKit sees no double click.
public private(set) var heldButtons: [Int64: Int64] = [:]
/// Whether the remote keyboard has Caps Lock on. macOS carries the lock in
/// the event's flags rather than in a key state, so we track the toggles.
public private(set) var capsLockOn = false
/// Everything up.
public init() {}
// MARK: - Chord tracking (`InputProcessKeyEx`, `InputSimulation.cs:372-475`)
/// Updates the chord state for one incoming key and says what the receiver
/// must do about it.
public mutating func process(vk: Int32, isUp: Bool, lockMachine: Hotkey) -> KeyDecision {
guard !isUp else {
releaseChord(vk)
return .inject
}
return processDown(vk: vk, lockMachine: lockMachine)
}
private mutating func releaseChord(_ vk: Int32) {
switch vk {
case KeyMap.leftWin, KeyMap.rightWin: chord.command = false
case KeyMap.leftControl, KeyMap.rightControl: chord.control = false
case KeyMap.leftMenu, KeyMap.rightMenu: chord.option = false
case KeyMap.leftShift, KeyMap.rightShift: chord.shift = false
default: break
}
}
// The hotkey test comes first and the `switch` runs regardless, exactly as
// `InputSimulation.cs:406-473` does: the lock hotkey is matched against the
// modifiers held *before* this key, and Win+L then matches again on the way
// through the switch. Both paths lock, so the duplication is harmless.
private mutating func processDown(vk: Int32, lockMachine: Hotkey) -> KeyDecision {
var decision = KeyDecision.inject
if lockMachine.matches(vk: vk, modifiers: chord) {
resetChord(keeping: lockMachine) // ResetModifiersState, :364-370
decision = KeyDecision(eatKey: true, releaseAllKeys: true, lockMachine: true)
}
switch vk {
case KeyMap.leftWin, KeyMap.rightWin: chord.command = true
case KeyMap.leftControl, KeyMap.rightControl: chord.control = true
case KeyMap.leftMenu, KeyMap.rightMenu: chord.option = true
case KeyMap.leftShift, KeyMap.rightShift: chord.shift = true
case KeyState.delete where chord.control && chord.option:
// Ctrl+Alt+Del: swallowed and logged, never posted (`:440-448`).
chord.control = false
chord.option = false
decision.eatKey = true
decision.releaseAllKeys = true
case KeyState.letterL where chord.command:
// Win+L (`:450-460`).
chord.command = false
decision.eatKey = true
decision.releaseAllKeys = true
decision.lockMachine = true
case KeyState.end where chord.control && chord.option:
// Ctrl+Alt+End starts the Windows service (`:462-469`); out of scope
// (README D6). Windows does not eat the key, so neither do we.
chord.control = false
chord.option = false
default: break
}
return decision
}
/// `ResetModifiersState` (`InputSimulation.cs:364-370`): keep only the
/// modifiers the matched hotkey asked for.
public mutating func resetChord(keeping hotkey: Hotkey) {
chord.command = chord.command && hotkey.command
chord.control = chord.control && hotkey.control
chord.option = chord.option && hotkey.option
chord.shift = chord.shift && hotkey.shift
}
/// `ResetSystemKeyFlags` (`InputSimulation.cs:477-480`), plus Shift, which
/// that routine forgets.
public mutating func resetChord() {
chord = ModifierState()
}
// MARK: - Held keys
/// Whether we have already posted a down for this key — a second down is a
/// key repeat.
public func isHeld(_ vk: Int32) -> Bool { heldKeys.contains(vk) }
/// Records a posted key event.
public mutating func note(vk: Int32, down: Bool) {
if down {
heldKeys.insert(vk)
if vk == KeyMap.capital { capsLockOn.toggle() }
} else {
heldKeys.remove(vk)
}
}
/// The keys to release, ordinary keys before modifiers.
///
/// Windows releases only the eleven modifier keys (`:225-229`) because
/// `SendInput` key-ups for everything else are the peer's job; we release
/// everything we posted, since a stuck letter is as bad as a stuck Shift
/// (feature README, contracts C2). Modifiers go last so nothing in between
/// turns into an unintended shortcut.
public func releaseOrder() -> [Int32] {
let modifiers = heldKeys.filter { KeyState.modifierVKs.contains($0) }.sorted()
let others = heldKeys.filter { !KeyState.modifierVKs.contains($0) }.sorted()
return others + modifiers
}
// MARK: - Held buttons
/// Records a posted button-down and the click count it carried.
public mutating func buttonDown(_ number: Int64, clickState: Int64) {
heldButtons[number] = clickState
}
/// Forgets a button and returns the click count its down carried, or 1 if we
/// never saw the down (a button that went down before we started injecting).
public mutating func buttonUp(_ number: Int64) -> Int64 {
heldButtons.removeValue(forKey: number) ?? 1
}
/// The button a move should be reported as dragging, if any. macOS needs
/// `*MouseDragged` while a button is held; Windows' `WM_MOUSEMOVE` does not
/// distinguish, so the state is ours to keep.
public var draggingButton: Int64? { heldButtons.keys.min() }
/// The buttons to release, with the click count each needs.
public func buttonReleaseOrder() -> [(number: Int64, clickState: Int64)] {
heldButtons.keys.sorted().map { ($0, heldButtons[$0] ?? 1) }
}
// MARK: - Event flags
/// The `CGEventFlags` word every event we post must carry.
///
/// macOS puts the modifier state on each event rather than in a global; a
/// key event posted without it arrives as a bare keystroke, so ⌘C from a
/// Windows keyboard would paste a "c". Both the device-independent masks and
/// the device-specific left/right bits are set, because apps read either.
public var eventFlags: UInt64 {
var flags: UInt64 = 0
if capsLockOn { flags |= KeyMap.capsLockMask }
for vk in heldKeys {
switch vk {
case KeyMap.leftWin: flags |= KeyMap.leftCommandMask | KeyState.commandMask
case KeyMap.rightWin: flags |= KeyMap.rightCommandMask | KeyState.commandMask
case KeyMap.leftControl: flags |= KeyMap.leftControlMask | KeyState.controlMask
case KeyMap.rightControl: flags |= KeyMap.rightControlMask | KeyState.controlMask
case KeyMap.leftMenu: flags |= KeyMap.leftOptionMask | KeyState.optionMask
case KeyMap.rightMenu: flags |= KeyMap.rightOptionMask | KeyState.optionMask
case KeyMap.leftShift: flags |= KeyMap.leftShiftMask | KeyState.shiftMask
case KeyMap.rightShift: flags |= KeyMap.rightShiftMask | KeyState.shiftMask
default: break
}
}
return flags
}
/// `kCGEventFlagMaskShift`.
public static let shiftMask: UInt64 = 0x0002_0000
/// `kCGEventFlagMaskControl`.
public static let controlMask: UInt64 = 0x0004_0000
/// `kCGEventFlagMaskAlternate`.
public static let optionMask: UInt64 = 0x0008_0000
/// `kCGEventFlagMaskCommand`.
public static let commandMask: UInt64 = 0x0010_0000
/// `kCGEventFlagMaskNumericPad`.
public static let numericPadMask: UInt64 = 0x0020_0000
/// `kCGEventFlagMaskSecondaryFn`.
public static let secondaryFnMask: UInt64 = 0x0080_0000
/// The flags macOS itself puts on a key by virtue of *where* it is: the
/// keypad and the arrows are `NumericPad`, the arrows, the navigation block
/// and the function keys are `SecondaryFn`.
///
/// Windows has no equivalent — the extended bit is a different idea — so
/// this is synthesised from the keycode, the way input-capture synthesises
/// `LLKHF_EXTENDED` in the other direction (docs/protocol.md §10.4 note 6).
public static func positionalFlags(forKeycode keycode: Int64) -> UInt64 {
var flags: UInt64 = 0
if numericPadKeycodes.contains(keycode) { flags |= numericPadMask }
if secondaryFnKeycodes.contains(keycode) { flags |= secondaryFnMask }
return flags
}
// The keypad block plus the four arrows (`kVK_ANSI_Keypad*`, `kVK_*Arrow`).
private static let numericPadKeycodes: Set<Int64> = [
0x41, 0x43, 0x45, 0x47, 0x4B, 0x4C, 0x4E, 0x51,
0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5B, 0x5C,
0x7B, 0x7C, 0x7D, 0x7E,
]
// F1..F20, the navigation block, forward delete and Help, plus the arrows.
private static let secondaryFnKeycodes: Set<Int64> = [
0x40, 0x4F, 0x50, 0x5A, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65,
0x67, 0x69, 0x6A, 0x6B, 0x6D, 0x6F, 0x71, 0x72, 0x73, 0x74,
0x75, 0x76, 0x77, 0x78, 0x79, 0x7A,
0x7B, 0x7C, 0x7D, 0x7E,
]
}
/// Consecutive clicks of the same button, turned into the click count macOS
/// expects on `mouseEventClickState`.
///
/// Windows never sends one: `WM_LBUTTONDBLCLK` has no `MOUSEEVENTF` case and
/// falls through `SendMouse`'s switch unhandled (`InputSimulation.cs:181-219`),
/// so a double click reaches us as two ordinary downs. macOS, on the other
/// hand, decides "double click" from the click count on the event, so we have to
/// count them here or nothing on this Mac will ever see one.
public struct ClickTracker: Sendable {
/// How far apart two downs may be and still be one double click. AppKit's
/// own hit-testing slop; Windows uses `SM_CXDOUBLECLK` for the same job.
public static let movementTolerance: CGFloat = 4
/// The system's double-click interval, `NSEvent.doubleClickInterval`.
public var interval: TimeInterval
private var lastButton: Int64?
private var lastTime: TimeInterval = 0
private var lastPoint = CGPoint(x: 0, y: 0)
private var count: Int64 = 0
/// A tracker using the given double-click interval.
public init(interval: TimeInterval) {
self.interval = interval
}
/// The click count for a button going down at `point`.
public mutating func click(button: Int64, at point: CGPoint, now: TimeInterval) -> Int64 {
let sameButton = lastButton == button
let inTime = now - lastTime <= interval
let nearby =
abs(point.x - lastPoint.x) <= ClickTracker.movementTolerance
&& abs(point.y - lastPoint.y) <= ClickTracker.movementTolerance
count = (sameButton && inTime && nearby) ? count + 1 : 1
lastButton = button
lastTime = now
lastPoint = point
return count
}
/// Forgets the run of clicks, so the next down starts at 1.
public mutating func reset() {
lastButton = nil
count = 0
}
}