From c4c04914b32ba7ce7840a229f6ca48b8aa0b3709 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Wed, 16 Sep 2026 02:06:31 -0700 Subject: [PATCH] input-capture: InputTypes and KeyMap in MWBCore The shared vocabulary of the input path (contracts C3, C4): the injected event tag, the WM_*/LLKHF_* numbers, the routing snapshot, CapturedInput, the hotkey config with the PowerToys defaults, and the macOS keycode <-> Windows VK table with the NX device modifier masks. Co-Authored-By: Claude Opus 5 (1M context) --- Sources/MWBCore/InputTypes.swift | 306 +++++++++++++++++++++++++++++ Sources/MWBCore/KeyMap.swift | 325 +++++++++++++++++++++++++++++++ 2 files changed, 631 insertions(+) create mode 100644 Sources/MWBCore/InputTypes.swift create mode 100644 Sources/MWBCore/KeyMap.swift diff --git a/Sources/MWBCore/InputTypes.swift b/Sources/MWBCore/InputTypes.swift new file mode 100644 index 0000000..d3f46e2 --- /dev/null +++ b/Sources/MWBCore/InputTypes.swift @@ -0,0 +1,306 @@ +// The vocabulary the capture side and the injection side share: the tag that +// tells our own synthetic events apart from the user's, the Windows message and +// flag numbers input travels as, the snapshot the event tap reads to decide +// where an event goes, and the values it hands to the Engine. +// +// Everything here is plain data with no platform types beyond `CGPoint`, so it +// lives in `MWBCore` and both `MWBMac/EventTap.swift` (producer) and +// `MWBMac/Injector.swift` (consumer) can depend on it (contracts C3, C4). +// +// Ported from App/Core/WM.cs (27-54), App/Class/InputHook.cs (84, 213-220, +// 337-343, 467-473), App/Class/EasyMouseOption.cs and +// src/settings-ui/Settings.UI.Library/MouseWithoutBordersProperties.cs (30-39, +// 188-192). + +import Foundation + +/// Constants both halves of the input path must agree on. +public enum InputTypes { + /// The value we stamp into `CGEventField.eventSourceUserData` on every event + /// we post ourselves, and which the tap passes through untouched. + /// + /// This is the macOS stand-in for the Windows `RealData` re-entrancy flag + /// (`InputHook.cs:84, 213-220, 340-343`): without it the tap would capture + /// the events the injector posts and echo them back to the peer. The value + /// is arbitrary but must be non-zero and unlikely to collide with another + /// app's tagging — it spells "MWBmac" in ASCII (contracts C4). + public static let injectedEventTag: Int64 = 0x4D57_4262_6D61_6300 +} + +/// The `WM_*` message ids a `Mouse` packet carries in `dwFlags` +/// (`WM.cs:27-40`, docs/protocol.md §5.2). +public enum WindowsMessage { + /// `WM_MOUSEMOVE`. + public static let mouseMove: Int32 = 0x200 + /// `WM_LBUTTONDOWN`. + public static let leftDown: Int32 = 0x201 + /// `WM_LBUTTONUP`. + public static let leftUp: Int32 = 0x202 + /// `WM_LBUTTONDBLCLK`. + public static let leftDoubleClick: Int32 = 0x203 + /// `WM_RBUTTONDOWN`. + public static let rightDown: Int32 = 0x204 + /// `WM_RBUTTONUP`. + public static let rightUp: Int32 = 0x205 + /// `WM_RBUTTONDBLCLK`. + public static let rightDoubleClick: Int32 = 0x206 + /// `WM_MBUTTONDOWN`. + public static let middleDown: Int32 = 0x207 + /// `WM_MBUTTONUP`. + public static let middleUp: Int32 = 0x208 + /// `WM_MBUTTONDBLCLK`. + public static let middleDoubleClick: Int32 = 0x209 + /// `WM_MOUSEWHEEL`, vertical. + public static let wheel: Int32 = 0x20A + /// `WM_XBUTTONDOWN`; the button index goes in `WheelDelta`. + public static let extraDown: Int32 = 0x20B + /// `WM_XBUTTONUP`; the button index goes in `WheelDelta`. + public static let extraUp: Int32 = 0x20C + /// `WM_MOUSEHWHEEL`, horizontal. + public static let horizontalWheel: Int32 = 0x20E + + /// One notch of the wheel. Windows reports wheel movement in multiples of + /// this (`InputHook.cs:254`, docs/protocol.md §5.2). + public static let wheelDelta: Int32 = 120 +} + +/// The `LLKHF_*` bits a `Keyboard` packet carries in `dwFlags` +/// (`WM.cs:47-54`, docs/protocol.md §5.1). +public enum KeyFlag { + /// `LLKHF_EXTENDED`: the key is one of the ones Windows marks extended. + public static let extended: Int32 = 0x01 + /// `LLKHF_INJECTED`: set by Windows on synthetic events. We never set it. + public static let injected: Int32 = 0x10 + /// `LLKHF_ALTDOWN`: an Alt key was down when this key was pressed. + public static let altDown: Int32 = 0x20 + /// `LLKHF_UP`: this is a key release. + public static let up: Int32 = 0x80 +} + +/// Which machine the user's input is going to right now. +public enum Destination: Sendable, Equatable { + /// This Mac keeps its own input. + case local + /// A peer machine id is receiving it (`MachineID.all` means every peer). + case remote(UInt32) + + /// True when input is leaving this machine. + public var isRemote: Bool { + if case .remote = self { return true } + return false + } +} + +/// `EasyMouseOption` — whether sliding the pointer off a screen edge switches +/// machines (`EasyMouseOption.cs:7-13`, default 1). +public enum EasyMouseMode: Int, Sendable, Equatable { + /// Never switch by moving the mouse. + case disable = 0 + /// Always switch by moving the mouse. + case enable = 1 + /// Switch only while a Control key is held. + case ctrl = 2 + /// Switch only while a Shift key is held. + case shift = 3 +} + +/// Which modifiers are physically down, in macOS terms. +/// +/// `command` is what Windows calls Win and `option` is what it calls Alt +/// (README D4), so a Windows hotkey spelled Win+Ctrl+Alt+L is ⌘⌃⌥L here. +public struct ModifierState: Sendable, Equatable { + /// ⌘, the Windows key. + public var command: Bool + /// ⌃. + public var control: Bool + /// ⌥, the Alt key. + public var option: Bool + /// ⇧. + public var shift: Bool + + /// All modifiers up. + public init(command: Bool = false, control: Bool = false, option: Bool = false, shift: Bool = false) + { + self.command = command + self.control = control + self.option = option + self.shift = shift + } +} + +/// One hotkey: a Windows virtual-key code plus the modifiers that must be held. +/// +/// The shape is `HotkeySettings` from the PowerToys settings library +/// (`HotkeySettings.cs:50-58`), which is what the settings file stores. +public struct Hotkey: Sendable, Equatable { + /// The Windows virtual-key code; 0 means "not configured". + public var vk: Int32 + /// Requires ⌘ (`HotkeySettings.Win`). + public var command: Bool + /// Requires ⌃ (`HotkeySettings.Ctrl`). + public var control: Bool + /// Requires ⌥ (`HotkeySettings.Alt`). + public var option: Bool + /// Requires ⇧ (`HotkeySettings.Shift`). + public var shift: Bool + + /// A hotkey. `vk == 0` disables it, as an empty `HotkeySettings` does. + public init(vk: Int32, command: Bool = false, control: Bool = false, option: Bool = false, + shift: Bool = false + ) { + self.vk = vk + self.command = command + self.control = control + self.option = option + self.shift = shift + } + + /// `HotkeySettings.IsEmpty()`: nothing configured, never matches. + public var isEmpty: Bool { vk == 0 } + + /// `Common.HotkeyMatched` (`Common.cs:127-129`): the code must be equal and + /// every modifier the hotkey asks for must be down. Modifiers the hotkey + /// does *not* ask for are not checked here — the extra Shift/⌘ veto lives in + /// `ProcessHotKeys` (`InputHook.cs:604-610`) and is applied by the matcher. + public func matches(vk key: Int32, modifiers: ModifierState) -> Bool { + guard !isEmpty, key == vk else { return false } + if command && !modifiers.command { return false } + if control && !modifiers.control { return false } + if option && !modifiers.option { return false } + if shift && !modifiers.shift { return false } + return true + } +} + +/// The five hotkeys the module defines, with the PowerToys defaults +/// (`MouseWithoutBordersProperties.cs:30-39, 188-192`, docs/protocol.md §4.5). +public struct HotkeyConfig: Sendable, Equatable { + /// `HotKeySwitchMachine`: this VK switches to matrix slot 0, the next three + /// VKs to slots 1..3, with ⌃⌥ held (`InputHook.cs:611-620`). + public var switchMachineVK: Int32 + /// `LockMachineShortcut`, default ⌘⌃⌥L. + public var lock: Hotkey + /// `ReconnectShortcut`, default ⌘⌃⌥R. + public var reconnect: Hotkey + /// `ToggleEasyMouseShortcut`, default ⌘⌃⌥E. + public var toggleEasyMouse: Hotkey + /// `Switch2AllPCShortcut`, disabled by default. + public var switchToAll: Hotkey + + /// The PowerToys defaults. + public init( + switchMachineVK: Int32 = 0x70, // VK.F1 (MouseWithoutBordersProperties.cs:188) + lock: Hotkey = Hotkey(vk: 0x4C, command: true, control: true, option: true), // L, :33 + reconnect: Hotkey = Hotkey(vk: 0x52, command: true, control: true, option: true), // R, :36 + toggleEasyMouse: Hotkey = Hotkey(vk: 0x45, command: true, control: true, option: true), // E, :39 + switchToAll: Hotkey = Hotkey(vk: 0) // empty, :30 + ) { + self.switchMachineVK = switchMachineVK + self.lock = lock + self.reconnect = reconnect + self.toggleEasyMouse = toggleEasyMouse + self.switchToAll = switchToAll + } + + /// How many machine slots the switch hotkey covers (`InputHook.cs:611-614`). + public static let switchMachineSlots = 4 + + /// The mac-only hard escape, ⌃⌥⌘Escape: always routes control back to this + /// Mac and is never forwarded (contracts C2). It has no Windows equivalent — + /// Windows relies on the switch-machine hotkey naming the local slot, which + /// we honour too. + public static let escape = Hotkey(vk: 0x1B, command: true, control: true, option: true) +} + +/// What a matched hotkey asks the Engine to do. The tap only classifies and +/// swallows; sending packets, locking and re-opening sockets are the Engine's. +public enum HotkeyAction: Sendable, Equatable { + /// ⌃⌥F1..F4: give control to matrix slot `slot` (`InputHook.cs:611-658`). + case switchToSlot(Int) + /// A single press of the lock hotkey: the chord goes to the machine in + /// control so *it* locks (`InputHook.cs:570`). + case lockMachine + /// Two presses within 500 ms: broadcast the chord to everyone and lock this + /// machine too (`InputHook.cs:544-566`). + case lockAllMachines + /// `PleaseReopenSocket` (`InputHook.cs:578-584`). + case reconnect + /// Flip `EasyMouse` between Disable and Enable (`InputHook.cs:524-537`). + case toggleEasyMouse + /// Turn ALL-machines (broadcast) mode on or off (`InputHook.cs:518-522`). + case toggleSwitchToAll + /// Control came home by an escape hotkey; the tap has already routed local + /// and the Engine must release held keys (contracts C2). + case escapedToLocal +} + +/// One thing the event tap saw, in the encoding the wire wants, queued for the +/// Engine (contracts C3). Values only: the tap must not call into the Engine. +public enum CapturedInput: Sendable { + /// A key transition ready for a `Keyboard` packet: Windows virtual-key code + /// and `LLKHF` flags (docs/protocol.md §5.1). + case key(vk: Int32, flags: Int32) + /// A mouse event ready for a `Mouse` packet (docs/protocol.md §5.2). + case mouse(MouseData) + /// The pointer moved while this Mac still owns it (or owns the virtual + /// cursor): `Edge`/`Switcher` decide whether that means a machine switch. + /// The point is in this Mac's screen coordinates. + case edgeCandidate(point: CGPoint, now: TimeInterval) + /// A hotkey fired. Already swallowed; `escapedToLocal` is already applied. + case hotkey(HotkeyAction) + /// The tap was disabled by timeout or by the user. It has been re-enabled + /// and control routed local; held-key state is unknown (contracts C2). + case tapLost + /// The capture ring filled and input was dropped. Control has been routed + /// local (contracts C3). + case overflow +} + +/// The state the tap callback reads on every event to decide, synchronously, +/// where the event goes. Small enough to copy under a lock (contracts C3). +public struct RoutingSnapshot: Sendable, Equatable { + /// Who receives input right now. + public var destination: Destination + /// Swallow key events locally instead of passing them on + /// (`InputHook.cs:361-368`). + public var swallowKeys: Bool + /// Swallow mouse events locally (`InputHook.cs:322-325`). + public var swallowMouse: Bool + /// `EasyMouse`: whether a pointer at the edge may switch machines. + public var easyMouse: EasyMouseMode + /// `MoveMouseRelatively`: send deltas rather than absolute positions, and + /// let the controlled machine do its own edge detection (§4.4). + public var moveMouseRelatively: Bool + /// The configured hotkeys. + public var hotkeys: HotkeyConfig + /// This Mac's own slot in the matrix, if it has one. ⌃⌥F is then an + /// escape hotkey: it must route control home from inside the callback + /// (contracts C2). + public var localSlot: Int? + + /// Everything local and nothing swallowed — the state a fresh process, a + /// lost tap and every recovery path in contracts C2 land in. + public init( + destination: Destination = .local, swallowKeys: Bool = false, swallowMouse: Bool = false, + easyMouse: EasyMouseMode = .enable, moveMouseRelatively: Bool = false, + hotkeys: HotkeyConfig = HotkeyConfig(), localSlot: Int? = nil + ) { + self.destination = destination + self.swallowKeys = swallowKeys + self.swallowMouse = swallowMouse + self.easyMouse = easyMouse + self.moveMouseRelatively = moveMouseRelatively + self.hotkeys = hotkeys + self.localSlot = localSlot + } + + /// The same snapshot with control back on this Mac and nothing swallowed. + /// Used by every local-recovery path (contracts C2). + public func routedLocal() -> RoutingSnapshot { + var copy = self + copy.destination = .local + copy.swallowKeys = false + copy.swallowMouse = false + return copy + } +} diff --git a/Sources/MWBCore/KeyMap.swift b/Sources/MWBCore/KeyMap.swift new file mode 100644 index 0000000..14741c3 --- /dev/null +++ b/Sources/MWBCore/KeyMap.swift @@ -0,0 +1,325 @@ +// macOS virtual keycodes ↔ Windows virtual-key codes, and the modifier bookkeeping +// that turns a macOS `flagsChanged` event into the down/up pairs Windows sends. +// +// Windows puts a virtual-key code on the wire and nothing else (docs/protocol.md +// §5.1, `InputHook.cs:347-349`), so a static layout-independent table is the only +// thing a Mac and a PC can agree on (README D4). The table is for the US ANSI +// physical layout: it maps *positions*, exactly as a VK does. +// +// This file is longer than the 300-600 line guidance in CLAUDE.md because the +// table is a table — one line per key, no logic. Everything that is logic is in +// the last third of the file and is short. +// +// Ported from App/Core/VK.cs (the whole enum), App/Core/WM.cs (47-54), +// App/Class/InputHook.cs (371-473) and App/Core/InitAndCleanup.cs +// ReleaseAllKeys (225-229, for the modifier VKs that matter). + +import Foundation + +/// The Windows-VK ↔ macOS-keycode table and the modifier diffing the event tap +/// and the injector share. +public enum KeyMap { + // MARK: - Windows virtual-key codes we name + + // Only the ones referenced below or by other modules; the rest of the table + // uses literals with the key in a comment. Values from `VK.cs:17-87` and, for + // the ones Windows' own enum omits, from the Win32 `virtual-key codes` list. + + /// `VK_BACK` — the key macOS calls Delete (`VK.cs:23`). + public static let back: Int32 = 0x08 + /// `VK_RETURN` (`VK.cs:25`). + public static let `return`: Int32 = 0x0D + /// `VK_CAPITAL`, Caps Lock (`VK.cs:17`). + public static let capital: Int32 = 0x14 + /// `VK_ESCAPE` (`VK.cs:22`). + public static let escape: Int32 = 0x1B + /// `VK_LWIN`, ⌘ on the left (`VK.cs:80`). + public static let leftWin: Int32 = 0x5B + /// `VK_RWIN`, ⌘ on the right (`VK.cs:81`). + public static let rightWin: Int32 = 0x5C + /// `VK_LSHIFT` (`VK.cs:82`). + public static let leftShift: Int32 = 0xA0 + /// `VK_RSHIFT` (`VK.cs:83`). + public static let rightShift: Int32 = 0xA1 + /// `VK_LCONTROL` (`VK.cs:84`). + public static let leftControl: Int32 = 0xA2 + /// `VK_RCONTROL` (`VK.cs:85`). + public static let rightControl: Int32 = 0xA3 + /// `VK_LMENU`, ⌥ on the left (`VK.cs:86`). + public static let leftMenu: Int32 = 0xA4 + /// `VK_RMENU`, ⌥ on the right (`VK.cs:87`). + public static let rightMenu: Int32 = 0xA5 + + // MARK: - macOS keycodes we name + + // `Carbon`'s `kVK_*` constants, written as literals because `MWBCore` may not + // import Carbon (README D2). Names are Apple's. + + /// `kVK_ANSI_KeypadEnter`. Windows calls it `VK_RETURN` *extended*, which is + /// the one collision the table cannot express. + public static let keypadEnterKeycode: Int64 = 0x4C + + // MARK: - The table + + /// Every key we can name, in `(macOS keycode, Windows VK)` pairs. + /// + /// Order matters in one place: where two keycodes map to the same VK, the + /// first one listed is the one `keycode(forVK:)` gives back. That is why + /// Return (0x24) precedes the keypad's Enter (0x4C). + private static let table: [(keycode: Int64, vk: Int32)] = [ + // Letters — kVK_ANSI_A … Z → VK 'A'..'Z' (0x41..0x5A). + (0x00, 0x41), // A + (0x0B, 0x42), // B + (0x08, 0x43), // C + (0x02, 0x44), // D + (0x0E, 0x45), // E + (0x03, 0x46), // F + (0x05, 0x47), // G + (0x04, 0x48), // H + (0x22, 0x49), // I + (0x26, 0x4A), // J + (0x28, 0x4B), // K + (0x25, 0x4C), // L + (0x2E, 0x4D), // M + (0x2D, 0x4E), // N + (0x1F, 0x4F), // O + (0x23, 0x50), // P + (0x0C, 0x51), // Q + (0x0F, 0x52), // R + (0x01, 0x53), // S + (0x11, 0x54), // T + (0x20, 0x55), // U + (0x09, 0x56), // V + (0x0D, 0x57), // W + (0x07, 0x58), // X + (0x10, 0x59), // Y + (0x06, 0x5A), // Z + + // Digit row — VK '0'..'9' (0x30..0x39). + (0x1D, 0x30), // 0 + (0x12, 0x31), // 1 + (0x13, 0x32), // 2 + (0x14, 0x33), // 3 + (0x15, 0x34), // 4 + (0x17, 0x35), // 5 + (0x16, 0x36), // 6 + (0x1A, 0x37), // 7 + (0x1C, 0x38), // 8 + (0x19, 0x39), // 9 + + // Punctuation — the OEM keys (`VK.cs:69-75` plus OEM_4/5/6/7/102). + (0x18, 0xBB), // = → VK_OEM_PLUS + (0x1B, 0xBD), // - → VK_OEM_MINUS + (0x21, 0xDB), // [ → VK_OEM_4 + (0x1E, 0xDD), // ] → VK_OEM_6 + (0x27, 0xDE), // ' → VK_OEM_7 + (0x29, 0xBA), // ; → VK_OEM_1 + (0x2A, 0xDC), // \ → VK_OEM_5 + (0x2B, 0xBC), // , → VK_OEM_COMMA + (0x2C, 0xBF), // / → VK_OEM_2 + (0x2F, 0xBE), // . → VK_OEM_PERIOD + (0x32, 0xC0), // ` → VK_OEM_3 + (0x0A, 0xE2), // ISO § / < > → VK_OEM_102 (ISO keyboards only) + + // Editing and navigation (`VK.cs:22-40`). + (0x24, 0x0D), // Return → VK_RETURN + (0x30, 0x09), // Tab → VK_TAB + (0x31, 0x20), // Space → VK_SPACE + (0x33, 0x08), // Delete → VK_BACK (macOS Delete is Backspace) + (0x35, 0x1B), // Escape → VK_ESCAPE + (0x39, 0x14), // Caps Lock → VK_CAPITAL + (0x72, 0x2D), // Help → VK_INSERT (same position on a PC keyboard) + (0x73, 0x24), // Home → VK_HOME + (0x74, 0x21), // Page Up → VK_PRIOR + (0x75, 0x2E), // Fwd Delete → VK_DELETE + (0x77, 0x23), // End → VK_END + (0x79, 0x22), // Page Down → VK_NEXT + (0x7B, 0x25), // Left → VK_LEFT + (0x7C, 0x27), // Right → VK_RIGHT + (0x7D, 0x28), // Down → VK_DOWN + (0x7E, 0x26), // Up → VK_UP + + // Function keys — VK_F1..VK_F20 (0x70..0x83; `VK.cs:57-68` stops at F12). + (0x7A, 0x70), // F1 + (0x78, 0x71), // F2 + (0x63, 0x72), // F3 + (0x76, 0x73), // F4 + (0x60, 0x74), // F5 + (0x61, 0x75), // F6 + (0x62, 0x76), // F7 + (0x64, 0x77), // F8 + (0x65, 0x78), // F9 + (0x6D, 0x79), // F10 + (0x67, 0x7A), // F11 + (0x6F, 0x7B), // F12 + (0x69, 0x7C), // F13 + (0x6B, 0x7D), // F14 + (0x71, 0x7E), // F15 + (0x6A, 0x7F), // F16 + (0x40, 0x80), // F17 + (0x4F, 0x81), // F18 + (0x50, 0x82), // F19 + (0x5A, 0x83), // F20 + + // Keypad (`VK.cs:41-56`). + (0x52, 0x60), // keypad 0 → VK_NUMPAD0 + (0x53, 0x61), // keypad 1 + (0x54, 0x62), // keypad 2 + (0x55, 0x63), // keypad 3 + (0x56, 0x64), // keypad 4 + (0x57, 0x65), // keypad 5 + (0x58, 0x66), // keypad 6 + (0x59, 0x67), // keypad 7 + (0x5B, 0x68), // keypad 8 + (0x5C, 0x69), // keypad 9 + (0x41, 0x6E), // keypad . → VK_DECIMAL + (0x43, 0x6A), // keypad * → VK_MULTIPLY + (0x45, 0x6B), // keypad + → VK_ADD + (0x4E, 0x6D), // keypad - → VK_SUBTRACT + (0x4B, 0x6F), // keypad / → VK_DIVIDE + (0x4C, 0x0D), // keypad Enter → VK_RETURN, extended (see isExtended) + (0x47, 0x90), // keypad Clear → VK_NUMLOCK (`VK.cs:18`), same position + + // Volume keys — VK_VOLUME_MUTE/DOWN/UP (0xAD..0xAF). + (0x4A, 0xAD), // Mute + (0x49, 0xAE), // Volume Down + (0x48, 0xAF), // Volume Up + + // Modifiers. macOS reports these through `flagsChanged`, but the injector + // needs the reverse direction, so they belong in the table + // (`VK.cs:80-87`; ⌘ = Win and ⌥ = Alt, README D4). + (0x37, 0x5B), // Left ⌘ → VK_LWIN + (0x36, 0x5C), // Right ⌘ → VK_RWIN + (0x38, 0xA0), // Left ⇧ → VK_LSHIFT + (0x3C, 0xA1), // Right ⇧ → VK_RSHIFT + (0x3B, 0xA2), // Left ⌃ → VK_LCONTROL + (0x3E, 0xA3), // Right ⌃ → VK_RCONTROL + (0x3A, 0xA4), // Left ⌥ → VK_LMENU + (0x3D, 0xA5), // Right ⌥ → VK_RMENU, + ] + + // Deliberately absent, because no Windows VK means the same thing: `fn` + // (0x3F), the keypad `=` (0x51) and the JIS-only keys 0x5D Yen, 0x5E + // underscore, 0x5F keypad comma, 0x66 Eisu and 0x68 Kana. Keys with no VK are + // passed through to this Mac rather than sent (docs/protocol.md §10.4). + + private static let byKeycode: [Int64: Int32] = { + var map: [Int64: Int32] = [:] + for entry in table { map[entry.keycode] = entry.vk } + return map + }() + + private static let byVK: [Int32: Int64] = { + var map: [Int32: Int64] = [:] + for entry in table where map[entry.vk] == nil { map[entry.vk] = entry.keycode } + return map + }() + + /// The Windows virtual-key code for a macOS keycode, or `nil` if the key has + /// no Windows equivalent. + public static func vk(forKeycode keycode: Int64) -> Int32? { byKeycode[keycode] } + + /// The macOS keycode for a Windows virtual-key code, or `nil` if this + /// keyboard has no such key. Used by the injector. + public static func keycode(forVK vk: Int32) -> Int64? { byVK[vk] } + + // MARK: - LLKHF_EXTENDED + + /// The virtual keys Windows marks `LLKHF_EXTENDED` (`WM.cs:50`): the + /// navigation block, the right-hand Control and Alt, the Windows keys, the + /// keypad's divide and Num Lock. + private static let extendedVKs: Set = [ + 0x21, 0x22, 0x23, 0x24, // PgUp, PgDn, End, Home + 0x25, 0x26, 0x27, 0x28, // Left, Up, Right, Down + 0x2D, 0x2E, 0x2F, // Insert, Delete, Help + 0x5B, 0x5C, // LWIN, RWIN + 0x6F, 0x90, // keypad /, Num Lock + 0xA3, 0xA5, // RCONTROL, RMENU + ] + + /// Whether a key carries `LLKHF_EXTENDED` (docs/protocol.md §5.1). + /// + /// The keycode is needed as well as the VK for exactly one key: the keypad's + /// Enter is `VK_RETURN` *with* the extended bit, while the main Return is + /// `VK_RETURN` without it, and the receiver uses the bit to tell them apart + /// (`InputSimulation.cs:108-157`). + public static func isExtended(vk: Int32, keycode: Int64) -> Bool { + keycode == keypadEnterKeycode || extendedVKs.contains(vk) + } + + // MARK: - Modifier flags + + // The device-specific bits of `CGEvent.flags` (`IOKit/hidsystem/IOLLEvent.h`), + // which is what tells a left modifier from a right one. `CGEventFlags` itself + // only has the device-independent masks, so the raw word is read instead. + + /// `NX_DEVICELCTLKEYMASK`. + public static let leftControlMask: UInt64 = 0x0000_0001 + /// `NX_DEVICELSHIFTKEYMASK`. + public static let leftShiftMask: UInt64 = 0x0000_0002 + /// `NX_DEVICERSHIFTKEYMASK`. + public static let rightShiftMask: UInt64 = 0x0000_0004 + /// `NX_DEVICELCMDKEYMASK`. + public static let leftCommandMask: UInt64 = 0x0000_0008 + /// `NX_DEVICERCMDKEYMASK`. + public static let rightCommandMask: UInt64 = 0x0000_0010 + /// `NX_DEVICELALTKEYMASK`. + public static let leftOptionMask: UInt64 = 0x0000_0020 + /// `NX_DEVICERALTKEYMASK`. + public static let rightOptionMask: UInt64 = 0x0000_0040 + /// `NX_DEVICERCTLKEYMASK`. Not 0x80: the right Control bit sits well above + /// the other seven. + public static let rightControlMask: UInt64 = 0x0000_2000 + /// `NX_ALPHASHIFTMASK` / `kCGEventFlagMaskAlphaShift`: Caps Lock is *on*. + public static let capsLockMask: UInt64 = 0x0001_0000 + + /// Every device modifier bit and the Windows VK it stands for, in the order + /// transitions are reported. + private static let modifierMasks: [(mask: UInt64, vk: Int32)] = [ + (leftShiftMask, leftShift), (rightShiftMask, rightShift), + (leftControlMask, leftControl), (rightControlMask, rightControl), + (leftOptionMask, leftMenu), (rightOptionMask, rightMenu), + (leftCommandMask, leftWin), (rightCommandMask, rightWin), + ] + + /// Which modifiers a `CGEvent.flags` word says are down, in macOS terms. + public static func modifiers(from flags: UInt64) -> ModifierState { + ModifierState( + command: flags & (leftCommandMask | rightCommandMask) != 0, + control: flags & (leftControlMask | rightControlMask) != 0, + option: flags & (leftOptionMask | rightOptionMask) != 0, + shift: flags & (leftShiftMask | rightShiftMask) != 0) + } + + /// Calls `body` once per modifier key that went down or up between two flag + /// words, with the Windows VK and whether it is now down. + /// + /// macOS reports modifiers as a *state* word on a `flagsChanged` event; + /// Windows' hook sees discrete key-down and key-up events for `VK_LSHIFT` + /// and friends (`InputHook.cs:379-425`). Diffing the word reconstructs them. + /// This is the allocation-free form, for the tap callback (CLAUDE.md + /// invariant 4); `modifierTransitions(old:new:)` is the convenient one. + public static func forEachModifierTransition( + old: UInt64, new: UInt64, _ body: (_ vk: Int32, _ down: Bool) -> Void + ) { + let changed = old ^ new + for entry in modifierMasks where changed & entry.mask != 0 { + body(entry.vk, new & entry.mask != 0) + } + } + + /// The modifier transitions between two flag words, as a list. + public static func modifierTransitions(old: UInt64, new: UInt64) -> [(vk: Int32, down: Bool)] { + var result: [(vk: Int32, down: Bool)] = [] + forEachModifierTransition(old: old, new: new) { vk, down in result.append((vk, down)) } + return result + } + + /// Whether Caps Lock toggled between two flag words. + /// + /// macOS reports the lock *state*, Windows sends a press and a release, so + /// the tap turns each toggle into a `VK_CAPITAL` down followed by an up. + public static func capsLockToggled(old: UInt64, new: UInt64) -> Bool { + (old ^ new) & capsLockMask != 0 + } +}