From c578e0a6569daade4e97b56cc217895a1456b857 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Wed, 16 Sep 2026 02:14:01 -0700 Subject: [PATCH] input-capture: the event tap, the hotkey matcher and Permissions.request EventTap is InputHook on CGEventTap: one dedicated run-loop thread, the injected-event tag passed through, keys/modifiers/mouse/scroll encoded to WM_*/LLKHF_*, the virtual cursor clamped to primary+-1 as InputHook does, Easy Mouse gating on edge candidates, and tap-loss re-enabling the tap AND routing local (C2). HotkeyMatcher ports ProcessHotKeys including the 500 ms double-press lock and the Shift/Win veto; Permissions gains request() and the 5 s health check. Co-Authored-By: Claude Opus 5 (1M context) --- Sources/MWBMac/EventTap.swift | 498 +++++++++++++++++++++++++++++++ Sources/MWBMac/Hotkeys.swift | 113 +++++++ Sources/MWBMac/Permissions.swift | 86 +++++- 3 files changed, 693 insertions(+), 4 deletions(-) create mode 100644 Sources/MWBMac/EventTap.swift create mode 100644 Sources/MWBMac/Hotkeys.swift diff --git a/Sources/MWBMac/EventTap.swift b/Sources/MWBMac/EventTap.swift new file mode 100644 index 0000000..65885b7 --- /dev/null +++ b/Sources/MWBMac/EventTap.swift @@ -0,0 +1,498 @@ +// The Mac's `InputHook`: one `CGEventTap` that sees every key, modifier, mouse +// and scroll event, decides synchronously whether it stays here or goes to a +// peer, encodes it the way Windows does, and returns. +// +// Ported from App/Class/InputHook.cs — `Start` (104-157), `MouseHookProc` +// (205-335), `KeyboardHookProc` (337-369), `ProcessKeyEx` (371-465) and +// `UpdateEasyMouseKeyDown` (467-473) — plus the encoding halves of +// App/Core/Event.cs `MouseEvent` (64-150) and `KeybdEvent` (250-278). +// +// The four rules this file exists to keep (CLAUDE.md invariants 3 and 4, +// contracts C2 and C3): +// * the callback never blocks — it reads one lock-protected snapshot, pushes +// a value into a ring, and returns; no network, no disk, no awaiting; +// * events we posted ourselves are passed through untouched, by their tag; +// * a tap disabled by timeout or by the user is re-enabled *and* control is +// routed home, because a tap that was off has lost key-ups; +// * the escape hotkeys take effect before the callback returns, so the user +// can always get their own keyboard back. + +import CoreGraphics +import Foundation +import MWBCore +import os + +/// The settings the tap callback needs. app-shell maps `Settings` onto this +/// (contracts C4); nothing here knows about a settings file. +public struct CaptureConfig: Sendable, Equatable { + /// The configured hotkeys (docs/protocol.md §4.5). + public var hotkeys: HotkeyConfig + /// `EasyMouse`: whether the pointer at a screen edge switches machines. + public var easyMouse: EasyMouseMode + /// `MoveMouseRelatively` (docs/protocol.md §4.4). + public var moveMouseRelatively: Bool + /// This Mac's matrix slot, so ⌃⌥F can be recognised as an escape. + public var localSlot: Int? + + /// The PowerToys defaults. + public init( + hotkeys: HotkeyConfig = HotkeyConfig(), easyMouse: EasyMouseMode = .enable, + moveMouseRelatively: Bool = false, localSlot: Int? = nil + ) { + self.hotkeys = hotkeys + self.easyMouse = easyMouse + self.moveMouseRelatively = moveMouseRelatively + self.localSlot = localSlot + } +} + +/// Why the tap could not be installed. +public enum EventTapError: Error, Equatable { + /// `CGEvent.tapCreate` returned nil — almost always a missing Accessibility + /// or Input Monitoring grant (README §Permissions). + case creationFailed + /// The mach port could not be attached to a run loop. + case runLoopSourceFailed +} + +/// The session-wide event tap. +/// +/// `@unchecked Sendable`: every field that crosses a thread boundary is behind a +/// lock — the routing snapshot and virtual cursor in `RoutingState`, the queue's +/// own ring, the counters here, and `runLoop`, which `stop()` reads from another +/// thread. Everything else (`machPort`, the modifier bookkeeping, the wheel +/// remainders, the hotkey matcher) is created and touched only on the tap's own +/// run-loop thread, which is the single thread the callback ever runs on. `self` +/// reaches the C callback as an unretained opaque pointer, so the tap must +/// outlive the run loop — `stop()` is what ends it. +public final class EventTap: @unchecked Sendable { + private struct Counters: Sendable { + var realInput: UInt64 = 0 + var unmappedKeys: UInt64 = 0 + } + + private let routing: RoutingState + private let queue: CaptureQueue + private let screens: Screens + private let onWake: @Sendable () -> Void + private let counters = OSAllocatedUnfairLock(initialState: Counters()) + private let runLoopLock = NSLock() + + private var runLoopStorage: CFRunLoop? + private var thread: Thread? + + // Tap-thread only, from here down. + private var machPort: CFMachPort? + private var lastFlags: UInt64 = 0 + private var modifiers = ModifierState() + private var easyMouseKeyDown = false + private var hotkeys = HotkeyMatcher() + private var verticalWheelRemainder: Double = 0 + private var horizontalWheelRemainder: Double = 0 + + /// A tap that writes into `queue` and reads `routing`. `onWake` is called + /// after every push and **must not block** — signalling a + /// `DispatchSourceUserDataAdd` or a semaphore is the intended shape. + public init( + routing: RoutingState, queue: CaptureQueue, screens: Screens, + config: CaptureConfig = CaptureConfig(), onWake: @escaping @Sendable () -> Void + ) { + self.routing = routing + self.queue = queue + self.screens = screens + self.onWake = onWake + reconfigure(config) + } + + // MARK: - Lifecycle + + /// Installs the tap on a dedicated run-loop thread and returns once it is + /// live (contracts C3: never the main thread, so a busy UI cannot stall it). + public func start() throws { + guard thread == nil else { return } + let ready = DispatchSemaphore(value: 0) + let failure = OSAllocatedUnfairLock(initialState: nil) + let worker = Thread { [self] in run(ready: ready, failure: failure) } + worker.name = "com.mwb-mac.event-tap" + worker.qualityOfService = .userInteractive + thread = worker + worker.start() + ready.wait() + if let error = failure.withLock({ $0 }) { + thread = nil + throw error + } + } + + /// Removes the tap and lets its thread exit. Safe to call from any thread. + public func stop() { + runLoopLock.lock() + let loop = runLoopStorage + runLoopLock.unlock() + if let loop { CFRunLoopStop(loop) } + thread = nil + } + + /// Whether the tap thread is running. + public var isRunning: Bool { + runLoopLock.lock() + defer { runLoopLock.unlock() } + return runLoopStorage != nil + } + + /// Applies new settings. Only the snapshot changes; the tap keeps running. + public func reconfigure(_ config: CaptureConfig) { + routing.update { snapshot in + snapshot.hotkeys = config.hotkeys + snapshot.easyMouse = config.easyMouse + snapshot.moveMouseRelatively = config.moveMouseRelatively + snapshot.localSlot = config.localSlot + } + } + + /// `Event.RealInputEventCount` (`Event.cs:51-55`, bumped at + /// `InputHook.cs:223, 345`): every real, non-injected input event this + /// process has seen. Hand it to `Session.tick(now:inputEventCount:)` + /// unchanged — the sessions decide what it means. + public var realInputEventCount: UInt64 { counters.withLock { $0.realInput } } + + /// How many key presses were dropped because the key has no Windows + /// virtual-key code (`KeyMap`). For the menu bar and bug reports. + public var unmappedKeyCount: UInt64 { counters.withLock { $0.unmappedKeys } } + + /// The monotonic clock the tap timestamps with. Every consumer of + /// `.edgeCandidate` must measure `Switcher`/`Edge` times with this same + /// function, or the 100 ms jump debounce compares two different clocks. + public static func now() -> TimeInterval { + Double(mach_absolute_time()) * machSecondsPerTick + } + + private static let machSecondsPerTick: Double = { + var info = mach_timebase_info_data_t() + guard mach_timebase_info(&info) == KERN_SUCCESS, info.denom != 0 else { return 1e-9 } + return Double(info.numer) / Double(info.denom) * 1e-9 + }() + + private static let eventMask: CGEventMask = { + let types: [CGEventType] = [ + .keyDown, .keyUp, .flagsChanged, .mouseMoved, .scrollWheel, + .leftMouseDown, .leftMouseUp, .leftMouseDragged, + .rightMouseDown, .rightMouseUp, .rightMouseDragged, + .otherMouseDown, .otherMouseUp, .otherMouseDragged, + ] + return types.reduce(CGEventMask(0)) { $0 | (CGEventMask(1) << $1.rawValue) } + }() + + private func run(ready: DispatchSemaphore, failure: OSAllocatedUnfairLock) { + guard + let port = CGEvent.tapCreate( + tap: .cgSessionEventTap, place: .headInsertEventTap, options: .defaultTap, + eventsOfInterest: EventTap.eventMask, callback: eventTapCallback, + userInfo: Unmanaged.passUnretained(self).toOpaque()) + else { + failure.withLock { $0 = .creationFailed } + ready.signal() + return + } + guard let source = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, port, 0) else { + CFMachPortInvalidate(port) + failure.withLock { $0 = .runLoopSourceFailed } + ready.signal() + return + } + + machPort = port + let loop = CFRunLoopGetCurrent() + runLoopLock.lock() + runLoopStorage = loop + runLoopLock.unlock() + + CFRunLoopAddSource(loop, source, .commonModes) + CGEvent.tapEnable(tap: port, enable: true) + ready.signal() + CFRunLoopRun() + + CGEvent.tapEnable(tap: port, enable: false) + CFRunLoopRemoveSource(loop, source, .commonModes) + CFMachPortInvalidate(port) + machPort = nil + runLoopLock.lock() + runLoopStorage = nil + runLoopLock.unlock() + } + + // MARK: - The callback + + /// Classify, enqueue, return. Nothing here allocates, waits or awaits. + fileprivate func handle(type: CGEventType, event: CGEvent) -> Unmanaged? { + if type == .tapDisabledByTimeout || type == .tapDisabledByUserInput { + return handleTapDisabled() + } + // The `RealData` re-entrancy flag (`InputHook.cs:213-220, 340-343`): our + // own injected events are not input, they are output. + if event.getIntegerValueField(.eventSourceUserData) == InputTypes.injectedEventTag { + return Unmanaged.passUnretained(event) + } + counters.withLock { $0.realInput &+= 1 } + let snapshot = routing.read() + + switch type { + case .keyDown, .keyUp: + return handleKey(type: type, event: event, snapshot: snapshot) + case .flagsChanged: + return handleFlags(event: event, snapshot: snapshot) + case .scrollWheel: + return handleScroll(event: event, snapshot: snapshot) + default: + return handleMouse(type: type, event: event, snapshot: snapshot) + } + } + + /// contracts C2: a tap that was disabled has lost events, so held-key state + /// is unknown. Re-enable it and give the keyboard back to this Mac. + private func handleTapDisabled() -> Unmanaged? { + if let machPort { CGEvent.tapEnable(tap: machPort, enable: true) } + routing.routeLocal() + lastFlags = 0 + modifiers = ModifierState() + easyMouseKeyDown = false + queue.signal(.tapLost) + onWake() + return nil + } + + // MARK: - Keyboard + + private func handleKey( + type: CGEventType, event: CGEvent, snapshot: RoutingSnapshot + ) -> Unmanaged? { + let keycode = event.getIntegerValueField(.keyboardEventKeycode) + guard let vk = KeyMap.vk(forKeycode: keycode) else { + counters.withLock { $0.unmappedKeys &+= 1 } + return Unmanaged.passUnretained(event) // no VK to send: leave it here + } + let isUp = type == .keyUp + let isRepeat = event.getIntegerValueField(.keyboardEventAutorepeat) != 0 + + // Hotkeys are matched on the press only, and not on auto-repeats: a held + // lock hotkey would otherwise read as the double press of + // `InputHook.cs:544`. + if !isUp && !isRepeat, let match = matchHotkey(vk: vk, snapshot: snapshot) { + if match.routesLocal { routing.routeLocal() } + enqueue(.hotkey(match.action)) + return nil + } + + var flags: Int32 = isUp ? KeyFlag.up : 0 + if KeyMap.isExtended(vk: vk, keycode: keycode) { flags |= KeyFlag.extended } + if modifiers.option { flags |= KeyFlag.altDown } + if snapshot.destination.isRemote { enqueue(.key(vk: vk, flags: flags)) } + return snapshot.swallowKeys ? nil : Unmanaged.passUnretained(event) + } + + private func matchHotkey(vk: Int32, snapshot: RoutingSnapshot) -> HotkeyMatch? { + hotkeys.config = snapshot.hotkeys + return hotkeys.match( + vk: vk, modifiers: modifiers, localSlot: snapshot.localSlot, + destinationIsRemote: snapshot.destination.isRemote, now: EventTap.now()) + } + + /// macOS reports modifiers as a state word; Windows' hook sees a key-down and + /// a key-up per modifier (`InputHook.cs:379-425`). Diff the word. + private func handleFlags( + event: CGEvent, snapshot: RoutingSnapshot + ) -> Unmanaged? { + let keycode = event.getIntegerValueField(.keyboardEventKeycode) + let newFlags = event.flags.rawValue + let oldFlags = lastFlags + lastFlags = newFlags + modifiers = KeyMap.modifiers(from: newFlags) + updateEasyMouseKey(snapshot.easyMouse) + + if snapshot.destination.isRemote { + KeyMap.forEachModifierTransition(old: oldFlags, new: newFlags) { vk, down in + var flags: Int32 = down ? 0 : KeyFlag.up + if KeyMap.isExtended(vk: vk, keycode: keycode) { flags |= KeyFlag.extended } + enqueue(.key(vk: vk, flags: flags)) + } + if KeyMap.capsLockToggled(old: oldFlags, new: newFlags) { + // macOS reports the lock state, Windows a press and a release. + enqueue(.key(vk: KeyMap.capital, flags: 0)) + enqueue(.key(vk: KeyMap.capital, flags: KeyFlag.up)) + } + } + return snapshot.swallowKeys ? nil : Unmanaged.passUnretained(event) + } + + /// `UpdateEasyMouseKeyDown` (`InputHook.cs:467-473`), read from the live + /// modifier state rather than from the last key event — see the README work + /// log for why that deviation is the better of the two. + private func updateEasyMouseKey(_ mode: EasyMouseMode) { + switch mode { + case .ctrl: easyMouseKeyDown = modifiers.control + case .shift: easyMouseKeyDown = modifiers.shift + case .disable, .enable: easyMouseKeyDown = false + } + } + + // MARK: - Mouse + + private func handleMouse( + type: CGEventType, event: CGEvent, snapshot: RoutingSnapshot + ) -> Unmanaged? { + guard let message = EventTap.windowsMessage(for: type, event: event) else { + return Unmanaged.passUnretained(event) + } + let layout = screens.layout + let isMove = message.flags == WindowsMessage.mouseMove + + if snapshot.destination.isRemote { + let dx = Double(event.getIntegerValueField(.mouseEventDeltaX)) + let dy = Double(event.getIntegerValueField(.mouseEventDeltaY)) + let virtual = routing.advanceVirtualCursor(dx: dx, dy: dy, clampedTo: layout.primary) + let position = remotePosition( + dx: dx, dy: dy, virtual: virtual, snapshot: snapshot, layout: layout) + enqueue( + .mouse( + MouseData( + x: position.x, y: position.y, wheelDelta: message.wheelDelta, + flags: message.flags))) + if isMove { offerEdgeCandidate(virtual, snapshot: snapshot) } + } else { + // The pointer is ours; remember where it is so a switch away starts + // from the right place (Windows' `Common.LastPos`). + let location = event.location + routing.virtualCursor = location + if isMove { offerEdgeCandidate(location, snapshot: snapshot) } + } + return snapshot.swallowMouse ? nil : Unmanaged.passUnretained(event) + } + + /// What goes in `Md.X`/`Md.Y`: a tagged delta in relative mode, otherwise the + /// virtual pointer scaled across the primary monitor + /// (`Event.cs:105-114`, docs/protocol.md §4.4). + private func remotePosition( + dx: Double, dy: Double, virtual: CGPoint, snapshot: RoutingSnapshot, layout: ScreenLayout + ) -> UniversalPoint { + if snapshot.moveMouseRelatively { + // `InputHook.cs:311-312` tags every delta, zero included, so + // `Event.cs:105` always takes the relative branch in this mode. + return Coordinates.tagRelative( + dx: Int32(dx.rounded(.towardZero)), dy: Int32(dy.rounded(.towardZero))) + } + return Coordinates.mouseMove(virtual, primary: layout.primary) + } + + /// `Event.cs:71-79`: the pointer may only trigger a machine switch when Easy + /// Mouse allows it, and — in relative mode — only while the pointer is ours, + /// because the controlled machine does its own edge detection then. + private func offerEdgeCandidate(_ point: CGPoint, snapshot: RoutingSnapshot) { + guard snapshot.easyMouse == .enable || easyMouseKeyDown else { return } + guard !snapshot.destination.isRemote || !snapshot.moveMouseRelatively else { return } + enqueue(.edgeCandidate(point: point, now: EventTap.now())) + } + + /// The `WM_*` id and `WheelDelta` for a macOS mouse event + /// (`InputHook.cs:251-254`, `WM.cs:27-40`, docs/protocol.md §5.2). + /// + /// Dragging is a move with a button held, which is what the Windows hook + /// reports too. Buttons above the fourth have no Windows message and stay + /// local. + private static func windowsMessage( + for type: CGEventType, event: CGEvent + ) -> (flags: Int32, wheelDelta: Int32)? { + switch type { + case .mouseMoved, .leftMouseDragged, .rightMouseDragged, .otherMouseDragged: + return (WindowsMessage.mouseMove, 0) + case .leftMouseDown: return (WindowsMessage.leftDown, 0) + case .leftMouseUp: return (WindowsMessage.leftUp, 0) + case .rightMouseDown: return (WindowsMessage.rightDown, 0) + case .rightMouseUp: return (WindowsMessage.rightUp, 0) + case .otherMouseDown, .otherMouseUp: + let isDown = type == .otherMouseDown + switch event.getIntegerValueField(.mouseEventButtonNumber) { + case 2: + return (isDown ? WindowsMessage.middleDown : WindowsMessage.middleUp, 0) + case 3: + return (isDown ? WindowsMessage.extraDown : WindowsMessage.extraUp, 1) + case 4: + return (isDown ? WindowsMessage.extraDown : WindowsMessage.extraUp, 2) + default: + return nil + } + default: + return nil + } + } + + // MARK: - Scroll + + /// One `WM_MOUSEWHEEL` / `WM_MOUSEHWHEEL` per whole 120-unit notch. + /// + /// A trackpad produces a continuous stream of fractional line deltas, so the + /// fraction is carried in a remainder and only whole notches go on the wire — + /// a Windows peer's `SendInput` ignores anything smaller. + private func handleScroll( + event: CGEvent, snapshot: RoutingSnapshot + ) -> Unmanaged? { + guard snapshot.destination.isRemote else { + return snapshot.swallowMouse ? nil : Unmanaged.passUnretained(event) + } + let layout = screens.layout + let position = Coordinates.mouseMove(routing.virtualCursor, primary: layout.primary) + let vertical = EventTap.notches( + event.getDoubleValueField(.scrollWheelEventFixedPtDeltaAxis1), + remainder: &verticalWheelRemainder) + let horizontal = EventTap.notches( + event.getDoubleValueField(.scrollWheelEventFixedPtDeltaAxis2), + remainder: &horizontalWheelRemainder) + + if vertical != 0 { + enqueue( + .mouse( + MouseData( + x: position.x, y: position.y, wheelDelta: vertical, + flags: WindowsMessage.wheel))) + } + if horizontal != 0 { + enqueue( + .mouse( + MouseData( + x: position.x, y: position.y, wheelDelta: horizontal, + flags: WindowsMessage.horizontalWheel))) + } + return snapshot.swallowMouse ? nil : Unmanaged.passUnretained(event) + } + + private static func notches(_ lines: Double, remainder: inout Double) -> Int32 { + let step = Double(WindowsMessage.wheelDelta) + remainder += lines * step + let whole = (remainder / step).rounded(.towardZero) + remainder -= whole * step + return Int32(whole) * WindowsMessage.wheelDelta + } + + // MARK: - Queueing + + /// Push and wake. A ring that cannot take the value means the Engine is not + /// draining, so control comes home (contracts C2, C3) — losing a key-up on a + /// remote machine is worse than losing control. + private func enqueue(_ input: CapturedInput) { + if queue.push(input) { + onWake() + return + } + queue.signal(.overflow) + routing.routeLocal() + onWake() + } +} + +/// The C entry point. It has no captures, finds the tap through `userInfo` and +/// does nothing else (`InputHook.MouseHookProc`/`KeyboardHookProc` start the same +/// way). +private let eventTapCallback: CGEventTapCallBack = { _, type, event, userInfo in + guard let userInfo else { return Unmanaged.passUnretained(event) } + let tap = Unmanaged.fromOpaque(userInfo).takeUnretainedValue() + return tap.handle(type: type, event: event) +} diff --git a/Sources/MWBMac/Hotkeys.swift b/Sources/MWBMac/Hotkeys.swift new file mode 100644 index 0000000..52a343f --- /dev/null +++ b/Sources/MWBMac/Hotkeys.swift @@ -0,0 +1,113 @@ +// Which key presses are commands to this app rather than keystrokes for the +// machine in control. +// +// A direct port of `InputHook.ProcessHotKeys` (`InputHook.cs:516-658`) and the +// predicate it leans on, `Common.HotkeyMatched` (`Common.cs:127-129`). The +// matcher decides and swallows; carrying out an action — sending the lock chord, +// re-opening sockets, flipping a setting — is the Engine's job, because none of +// it can happen inside the tap callback (CLAUDE.md invariant 4). +// +// The one exception is the escape set (contracts C2): those must take effect +// *before* the callback returns, so the tap applies them to the routing snapshot +// itself and the match merely says so. + +import Foundation +import MWBCore + +/// A matched hotkey and what it means for the key event that triggered it. +public struct HotkeyMatch: Sendable, Equatable { + /// What the Engine should do. + public var action: HotkeyAction + /// Whether the tap must route control back to this Mac before returning + /// (contracts C2). True for the escape set only. + public var routesLocal: Bool + + /// A match. + public init(action: HotkeyAction, routesLocal: Bool = false) { + self.action = action + self.routesLocal = routesLocal + } +} + +/// The hotkey rules, plus the one piece of state they need: when the lock hotkey +/// was last pressed. +/// +/// A value type held by `EventTap` and touched only on the tap thread. +public struct HotkeyMatcher: Sendable { + /// Two presses of the lock hotkey inside this window lock every machine + /// instead of just the one in control (`InputHook.cs:544`). + public static let lockDoublePressWindow: TimeInterval = 0.5 + + /// The configured hotkeys. Replaced when settings change. + public var config: HotkeyConfig + + private var lastLockPress: TimeInterval? + + /// A matcher over these hotkeys. + public init(config: HotkeyConfig = HotkeyConfig()) { + self.config = config + } + + /// Classifies one key-down. Returns `nil` when the key is an ordinary + /// keystroke; any non-`nil` result means the key is swallowed locally. + /// + /// Windows checks in this order and so do we; only the order makes the + /// `else if` chain in `ProcessHotKeys` behave (`InputHook.cs:516-624`). The + /// mac-only escape is checked first because it must work even when the + /// Windows `Shift`/`Win` veto below would swallow the chord. + public mutating func match( + vk: Int32, modifiers: ModifierState, localSlot: Int?, destinationIsRemote: Bool, + now: TimeInterval + ) -> HotkeyMatch? { + if HotkeyConfig.escape.matches(vk: vk, modifiers: modifiers) { + return HotkeyMatch(action: .escapedToLocal, routesLocal: true) + } + if config.switchToAll.matches(vk: vk, modifiers: modifiers) { + return HotkeyMatch(action: .toggleSwitchToAll) // InputHook.cs:518-522 + } + if config.toggleEasyMouse.matches(vk: vk, modifiers: modifiers) { + return HotkeyMatch(action: .toggleEasyMouse) // InputHook.cs:524-537 + } + if config.lock.matches(vk: vk, modifiers: modifiers) { + return HotkeyMatch(action: lockAction(now: now)) // InputHook.cs:539-577 + } + if config.reconnect.matches(vk: vk, modifiers: modifiers) { + return HotkeyMatch(action: .reconnect) // InputHook.cs:578-584 + } + return switchMachineMatch( + vk: vk, modifiers: modifiers, localSlot: localSlot, + destinationIsRemote: destinationIsRemote) + } + + /// Forgets the last lock press, so the next one cannot be read as the second + /// half of a double press. Called when control changes machines. + public mutating func resetLockTimer() { + lastLockPress = nil + } + + /// One press sends the chord to the machine in control so *it* locks; a + /// second press inside 500 ms locks everything (`InputHook.cs:544-575`). + private mutating func lockAction(now: TimeInterval) -> HotkeyAction { + let isDouble = + lastLockPress.map { now - $0 < HotkeyMatcher.lockDoublePressWindow } ?? false + lastLockPress = now + return isDouble ? .lockAllMachines : .lockMachine + } + + /// ⌃⌥F1..F4 → matrix slot 0..3 (`InputHook.cs:611-620`). + /// + /// The two rules that come with it: Control and Option must both be down and + /// nothing else may be (`:586, 604-610` — issue #26597), and the slot naming + /// this Mac is an escape hotkey, so it routes control home from inside the + /// callback (contracts C2). + private func switchMachineMatch( + vk: Int32, modifiers: ModifierState, localSlot: Int?, destinationIsRemote: Bool + ) -> HotkeyMatch? { + guard modifiers.control && modifiers.option else { return nil } + guard !modifiers.shift && !modifiers.command else { return nil } + let slot = Int(vk - config.switchMachineVK) + guard slot >= 0 && slot < HotkeyConfig.switchMachineSlots else { return nil } + let comingHome = destinationIsRemote && slot == localSlot + return HotkeyMatch(action: .switchToSlot(slot), routesLocal: comingHome) + } +} diff --git a/Sources/MWBMac/Permissions.swift b/Sources/MWBMac/Permissions.swift index 7973ea7..8463cbe 100644 --- a/Sources/MWBMac/Permissions.swift +++ b/Sources/MWBMac/Permissions.swift @@ -1,4 +1,17 @@ +// The one wrapper around the `CGPreflight*EventAccess` / `CGRequest*EventAccess` +// C API (CLAUDE.md, Swift standards: C APIs are wrapped once), plus the health +// check that notices a grant being taken away while we run (contracts C2). +// +// Windows has no equivalent: a low-level hook needs no permission there. On +// macOS the tap simply stops existing, so the app has to watch for it. +// +// CLAUDE.md, Workflow: an agent never grants, requests or scripts these +// permissions. `request()` exists for a button the *user* clicks, and nothing in +// this repository may call it on its own initiative. + import CoreGraphics +import Foundation +import os /// Which macOS TCC permissions the current process holds. /// @@ -14,15 +27,80 @@ public struct PermissionState: Equatable, Sendable { public var isComplete: Bool { listen && post } } -/// The one wrapper around the `CGPreflight*EventAccess` C API (CLAUDE.md, -/// Swift standards: C APIs are wrapped once). Only *preflight* lives here; -/// requesting is the `event-tap` lane's job, and never happens on an agent's -/// own initiative (CLAUDE.md, Workflow). +/// Preflight, request and watch the two grants the app needs. public enum Permissions { + /// How often the health check re-reads the grants (contracts C2). + public static let healthCheckInterval: TimeInterval = 5 + /// Reads the current grants without prompting the user. public static func preflight() -> PermissionState { PermissionState( listen: CGPreflightListenEventAccess(), post: CGPreflightPostEventAccess()) } + + /// Asks macOS to show the system prompts for whichever grant is missing. + /// + /// **Only ever call this from a control the user clicked.** It shows modal + /// system UI, and macOS shows each prompt once per code signature — spending + /// it unasked leaves the user with a Settings pane and no explanation. + /// Returns the state as macOS reports it immediately afterwards, which is + /// normally still incomplete: the grant lands when the user flips the switch + /// in System Settings, and the health check is what notices. + @discardableResult + public static func request() -> PermissionState { + let state = preflight() + if !state.listen { _ = CGRequestListenEventAccess() } + if !state.post { _ = CGRequestPostEventAccess() } + return preflight() + } + + /// Starts re-reading the grants every `interval` seconds and calls `onChange` + /// whenever they differ from the last reading. + /// + /// contracts C2: a revoked grant means the tap is dead, so the caller routes + /// control local and shows the state in the menu bar. Keep the returned + /// object alive; dropping it stops the check. + public static func startHealthCheck( + interval: TimeInterval = healthCheckInterval, + onChange: @escaping @Sendable (PermissionState) -> Void + ) -> PermissionHealthCheck { + PermissionHealthCheck(interval: interval, onChange: onChange) + } +} + +/// A repeating permission check. Cancels itself when released. +/// +/// `@unchecked Sendable`: its only stored property is a `DispatchSourceTimer`, +/// which is safe to use from any thread by its own contract. +public final class PermissionHealthCheck: @unchecked Sendable { + private let timer: any DispatchSourceTimer + + fileprivate init(interval: TimeInterval, onChange: @escaping @Sendable (PermissionState) -> Void) + { + let queue = DispatchQueue(label: "com.mwb-mac.permission-health", qos: .utility) + let timer = DispatchSource.makeTimerSource(queue: queue) + let last = OSAllocatedUnfairLock(initialState: Permissions.preflight()) + timer.schedule(deadline: .now() + interval, repeating: interval, leeway: .seconds(1)) + timer.setEventHandler { + let current = Permissions.preflight() + let changed = last.withLock { previous -> Bool in + guard previous != current else { return false } + previous = current + return true + } + if changed { onChange(current) } + } + self.timer = timer + timer.resume() + } + + /// Stops the check. Idempotent. + public func cancel() { + timer.cancel() + } + + deinit { + timer.cancel() + } }