Files
mac_without_borders/Sources/MWBMac/EventTap.swift
T
lucioandClaude Opus 5 8af26751a8 input-capture: one lock for the tap's run loop and its thread
QA finding 1: `EventTap.thread` was a plain `var` read in `start()` and
written in both `start()` and `stop()`, while the class comment claimed
every cross-thread field was locked and `stop()` claimed to be safe from
any thread (the contracts-C2 signal-handler recovery calls it off the tap
thread). `runLoopLock` becomes `stateLock` and guards both fields;
`start()` claims the slot and tests it in one critical section so two
concurrent starts cannot both install a tap.

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

515 lines
21 KiB
Swift

// 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<slot+1> 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 the two lifecycle fields `runLoopStorage`
/// and `thread`, which `stop()` reads and writes from another thread and which
/// `stateLock` guards together. Everything else (`machPort`, the modifier
/// bookkeeping, the wheel remainders, the hotkey matcher) is touched only on the
/// tap's own run-loop thread, 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 stateLock = NSLock()
// Both guarded by `stateLock`: `start()` runs on whatever thread the app
// shell calls it from, `stop()` on any thread at all (a signal handler
// included, contracts C2), and the tap thread clears the run loop as it
// exits.
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 {
let ready = DispatchSemaphore(value: 0)
let failure = OSAllocatedUnfairLock<EventTapError?>(initialState: nil)
// Claiming the slot and testing it are one step, so two `start()`s can
// never both install a tap.
stateLock.lock()
guard thread == nil else {
stateLock.unlock()
return
}
let worker = Thread { [self] in run(ready: ready, failure: failure) }
worker.name = "com.mwb-mac.event-tap"
worker.qualityOfService = .userInteractive
thread = worker
stateLock.unlock()
worker.start()
ready.wait()
if let error = failure.withLock({ $0 }) {
stateLock.lock()
thread = nil
stateLock.unlock()
throw error
}
}
/// Removes the tap and lets its thread exit. Safe to call from any thread.
public func stop() {
stateLock.lock()
let loop = runLoopStorage
thread = nil
stateLock.unlock()
if let loop { CFRunLoopStop(loop) }
}
/// Whether the tap thread is running.
public var isRunning: Bool {
stateLock.lock()
defer { stateLock.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<EventTapError?>) {
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()
stateLock.lock()
runLoopStorage = loop
stateLock.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
stateLock.lock()
runLoopStorage = nil
stateLock.unlock()
}
// MARK: - The callback
/// Classify, enqueue, return. Nothing here allocates, waits or awaits.
fileprivate func handle(type: CGEventType, event: CGEvent) -> Unmanaged<CGEvent>? {
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<CGEvent>? {
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<CGEvent>? {
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<CGEvent>? {
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<CGEvent>? {
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<CGEvent>? {
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<EventTap>.fromOpaque(userInfo).takeUnretainedValue()
return tap.handle(type: type, event: event)
}