// 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 = [ KeyMap.leftWin, KeyMap.rightWin, KeyMap.leftControl, KeyMap.rightControl, KeyMap.leftMenu, KeyMap.rightMenu, KeyMap.leftShift, KeyMap.rightShift, ] /// Whether macOS reports this key as a `flagsChanged` event rather than a /// key press — the eight modifiers and Caps Lock. public static func reportsAsFlagsChanged(vk: Int32) -> Bool { vk == KeyMap.capital || modifierVKs.contains(vk) } /// 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. /// /// **Posting path only.** `process(vk:isUp:lockMachine:)` must be given the /// raw wire VK: Windows' chord switches are side-specific, so the side-less /// forms deliberately change nothing there (§10.5 note 3). 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 = [] /// 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. /// /// `vk` is the **raw** virtual key off the wire, not a normalised one. /// `InputProcessKeyEx` matches side-specific VKs only — `VK.LSHIFT`/ /// `VK.RSHIFT`, `VK.LCONTROL`/`VK.RCONTROL`, `VK.LMENU`/`VK.RMENU`, /// `VK.LWIN`/`VK.RWIN` in both its switches (`InputSimulation.cs:372-403` /// for the `LLKHF.UP` half, `:418-438` for the down half) — so the side-less /// `VK_SHIFT`/`VK_CONTROL`/`VK_MENU` a lock-chord replay puts on the wire /// (`InputHook.cs:485-512`) hit `default` and never move `shiftDown`/ /// `ctrlDown`/`altDown`. `Common.HotkeyMatched` (`:406`) sees the raw code /// too. Normalising before this point would let a replayed chord match lock /// hotkeys a Windows peer would not match from the same bytes /// (docs/protocol.md §10.5 note 3). 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 = [ 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 = [ 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 } }