// The Engine: the one actor that owns every piece of mutable shared state // (contracts C3), the drain loop that turns captured input into packets // (contracts C1) and the dispatcher that turns received packets into actions. // // This is the macOS shape of what Windows spreads across `Core/Receiver.cs` // (`ProcessPackage`), `Core/Event.cs` (`MouseEvent`/`KeybdEvent`), // `Core/Helper.cs` (`HelperThread`) and the statics in `Core/Common.cs` and // `Core/MachineStuff.cs`. Windows guards those statics with locks taken from // half a dozen threads; we have one actor, one routing snapshot readable by the // tap callback, and two bounded queues (contracts C3). // // Nothing outside this file holds the `Switcher`, the `PacketSequencer`, the // `ReplayFilter`, the `ControlChannel` or the `EventTap`. import AppKit import Foundation import MWBCore import MWBMac import MWBNet /// Why control came back to this Mac (contracts C2). public enum RecoveryReason: Sendable, Equatable { /// An escape hotkey — ⌃⌥F or ⌃⌥⌘Escape. case escapeHotkey /// The event tap was disabled by timeout or by the user. case tapLost /// The capture ring filled and input was dropped. case captureOverflow /// The peer receiving our input went away, for any reason. case controlledPeerLost(String?) /// Input Monitoring or Accessibility was revoked while we were running. case permissionsLost /// The app is quitting. case quitting /// One line for the log and the menu bar. public var text: String { switch self { case .escapeHotkey: return "escape hotkey" case .tapLost: return "event tap disabled" case .captureOverflow: return "capture queue overflow" case .controlledPeerLost(let name): return "lost \(name ?? "the controlled machine")" case .permissionsLost: return "permissions revoked" case .quitting: return "quitting" } } } /// When control last came home, and why. public struct RecoveryNote: Sendable, Equatable { /// Why it happened. public var reason: RecoveryReason /// When it happened. public var at: Date } /// Everything the menu bar needs, in one value. public struct EngineSnapshot: Sendable { /// One row per connection or name being dialled. public var peers: [PeerStatus] = [] /// The machine currently receiving input, `nil` when that is this Mac. public var controlled: String? /// Whether ALL-machines mode is on. public var broadcasting = false /// Input Monitoring / Accessibility as macOS reports them. The default is /// "neither", not a `preflight()`: building a snapshot must not query TCC. public var permissions = PermissionState(listen: false, post: false) /// Whether the event tap is installed. public var tapRunning = false /// False when the process could not make a `CGEventSource`, so nothing this /// Mac receives can be injected (input-inject request 5). public var canInject = false /// `EasyMouse` as it stands. public var easyMouse: EasyMouseMode = .enable /// This Mac's name on the wire. public var localName = "" /// Why the hostname is unusable, when it is (README D7). public var hostnameProblem: String? /// The last thing that took control back (contracts C2). public var lastRecovery: RecoveryNote? } /// Everything that reaches the Engine from outside it, in the order it happened. /// /// The channel's sink, the tap's wake-up, the timers and the notification /// observers all funnel through one `AsyncStream`, so callbacks arriving on four /// different queues are serialised once rather than racing as independent /// `Task`s (contracts C3). enum EngineEvent: Sendable { case connectionStatus(SocketStatus, String?, Bool) case connected(String, UInt32) case received(Packet, UInt32) case disconnected(UInt32?, String?, DisconnectReason) case idCollision case capturedInput case tick case screensChanged case permissions(PermissionState) case systemWoke case settingsChanged(Settings) } /// Turns the channel's `EngineSink` calls into `EngineEvent`s. /// /// The channel calls this on its own serial queue and must not be blocked there /// (control-channel Handshakes), so every method does one `yield` and returns. final class ChannelSink: EngineSink { private let emit: @Sendable (EngineEvent) -> Void init(emit: @escaping @Sendable (EngineEvent) -> Void) { self.emit = emit } func channel( _ channel: ControlChannel, connectionStatus: SocketStatus, peerName: String?, isOutbound: Bool ) { emit(.connectionStatus(connectionStatus, peerName, isOutbound)) } func channel(_ channel: ControlChannel, connected peerName: String, peerID: UInt32) { emit(.connected(peerName, peerID)) } func channel(_ channel: ControlChannel, received packet: Packet, from peerID: UInt32) { emit(.received(packet, peerID)) } func channel( _ channel: ControlChannel, disconnected peerID: UInt32?, peerName: String?, reason: DisconnectReason ) { emit(.disconnected(peerID, peerName, reason)) } func channelDetectedIDCollision(_ channel: ControlChannel) { emit(.idCollision) } } /// The running app, minus its window dressing. public actor Engine { /// How often the reopen countdown is examined. static let tickInterval: TimeInterval = 1 /// How long everything may stay unconnected before we dial again /// (`frmScreen.cs:427-450`: `count % 300` on a 100 ms timer). static let reopenAfterSecondsIdle = 30 let store: SettingsStore var settings: Settings let hostnameProblem: String? let sequencer: PacketSequencer let replay: ReplayFilter let switcher: Switcher let routing = RoutingState() let captureQueue = CaptureQueue() let screens: Screens let cursor = Cursor() let injector: Injector /// The receiving half of `BlockScreenSaverOnOtherMachines`: every `Awake` /// packet renews a power assertion (the extras lane, `Awake.swift`). let displayAwake = DisplayAwake() /// `DrawMouseCursor`: the arrow drawn where the remote pointer is while a /// peer drives this Mac (the extras lane, `FakeCursor.swift`). let fakeCursor = FakeCursor() var tap: EventTap? var channel: ControlChannel? /// Clipboard sharing: the bulk channel, the pasteboard watcher and the /// policy that drives them (the clipboard lane, `ClipboardBridge.swift`). var clipboard: ClipboardBridge? private let events: AsyncStream let emit: @Sendable (EngineEvent) -> Void private var pump: Task? private var ticker: (any DispatchSourceTimer)? private var captureSignal: (any DispatchSourceUserDataAdd)? private var health: PermissionHealthCheck? var peerNames: [UInt32: String] = [:] var lastLocalPosition: CGPoint? var pendingCursorTarget: CGPoint? var secondsWithoutConnection = 0 var lastRecovery: RecoveryNote? var permissions = Permissions.preflight() var observer: (@Sendable (EngineSnapshot) -> Void)? /// Builds the whole machine from the settings file. /// /// `localName` is this Mac's name on the wire and `hostnameProblem` says why /// it is unusable when it is (README D7); with a problem the Engine starts /// nothing, so the menu bar can explain rather than a half-running app /// joining a matrix under a name nobody can resolve. public init(store: SettingsStore, localName: String, hostnameProblem: String? = nil) { self.store = store self.hostnameProblem = hostnameProblem var loaded = store.current let now = EventTap.now() // `InitAndCleanup.InitializeMachinePoolFromSettings` (`:46-60`) and // `UpdateMachineTimeAndID` (`:40-44`): load the pool, forget the ids of // machines the matrix no longer lists, then put ourselves in it. var matrix = loaded.matrix if matrix.names.allSatisfy(\.isEmpty) { // Nothing configured yet. Seeding our own slot makes the settings // file self-explanatory; a peer's name still has to be added by // hand (or by app-ui) before anything is dialled. matrix.setName(localName, at: 0) loaded.matrix = matrix } let localID = UInt32(bitPattern: loaded.machineID) var pool = loaded.pool(now: now) pool.resetDeadMachineIDs( localName: localName, matrix: matrix, now: now, connectedIDs: [], firstLoaded: true) _ = pool.learn(localName, keeping: matrix) pool.updateID(name: localName, id: localID, updateTimestamp: true, now: now) settings = loaded sequencer = PacketSequencer(start: loaded.packageID) replay = ReplayFilter() injector = Injector(config: InjectorConfig(lockMachine: loaded.lockMachineShortcut)) let (stream, continuation) = AsyncStream.makeStream( bufferingPolicy: .unbounded) events = stream let emit: @Sendable (EngineEvent) -> Void = { continuation.yield($0) } self.emit = emit screens = Screens(onChange: { emit(.screensChanged) }) let edge = Edge( config: screens.layout.edgeConfig( blockCorners: loaded.blockMouseAtScreenCorners, moveRelatively: loaded.moveMouseRelatively)) switcher = Switcher( localName: localName, localID: localID, matrix: matrix, pool: pool, edge: edge, sequencer: sequencer) } // MARK: - Lifecycle /// Starts the tap, the channel, the timers and the event pump. /// /// A missing permission is not fatal: the channel still runs, so this Mac /// can be controlled by a peer even before the user grants Input Monitoring. public func start() { guard hostnameProblem == nil else { Log.app.error("not starting: \(hostnameProblem ?? "")") publish() return } permissions = Permissions.preflight() startPump() startCaptureSignal() startTicker() startHealthCheck() applyConfiguration() startTap() startChannel() startClipboard() // the clipboard lane Log.app.info("engine started as \(switcher.localName), id \(switcher.localID)") publish() } /// Stops everything and persists what Windows persists on exit. /// /// `Cleanup` (`InitAndCleanup.cs:192-215`) says goodbye, waits for its helper /// threads and only then closes the sockets; the wait here is what gives the /// queued `ByeBye` time to reach the wire before the connections go. public func stop() async { if switcher.destinationIsRemote || switcher.isBroadcasting { recoverLocal(reason: .quitting) } stopClipboard() // the clipboard lane channel?.sayGoodbye() try? await Task.sleep(for: .milliseconds(150)) channel?.stop() channel = nil EmergencyRelease.shared.arm(channel: nil) tap?.stop() tap = nil health?.cancel() health = nil ticker?.cancel() ticker = nil captureSignal?.cancel() captureSignal = nil pump?.cancel() pump = nil injector.releaseAll() cursor.restoreEverything() // Nothing may outlive the process: an assertion we still hold would keep // the display awake, and the overlay would be the last thing on screen. displayAwake.release() fakeCursor.hide() persistOnExit() Log.app.info("engine stopped") } /// Publishes a snapshot whenever anything the menu bar shows changes. public func observe(_ handler: @escaping @Sendable (EngineSnapshot) -> Void) { observer = handler publish() } /// The current snapshot, for a UI that asks rather than observes. public var snapshot: EngineSnapshot { currentSnapshot() } private func startPump() { guard pump == nil else { return } // `Task {}` started inside the actor inherits its isolation, so every // event is handled on the actor, in arrival order (contracts C3). pump = Task { [events] in for await event in events { self.handle(event) } } } /// The tap's `onWake` must not block or allocate (CLAUDE.md invariant 4), so /// it only bumps this source; the source's handler is what yields into the /// stream. Coalescing is free: many wake-ups become one drain. private func startCaptureSignal() { guard captureSignal == nil else { return } let queue = DispatchQueue(label: "com.mwb-mac.capture-wake", qos: .userInteractive) let source = DispatchSource.makeUserDataAddSource(queue: queue) let emit = emit source.setEventHandler { emit(.capturedInput) } captureSignal = source source.resume() } private func startTicker() { guard ticker == nil else { return } let queue = DispatchQueue(label: "com.mwb-mac.engine-tick", qos: .utility) let timer = DispatchSource.makeTimerSource(queue: queue) timer.schedule( deadline: .now() + Engine.tickInterval, repeating: Engine.tickInterval, leeway: .milliseconds(200)) let emit = emit timer.setEventHandler { emit(.tick) } ticker = timer timer.resume() } private func startHealthCheck() { guard health == nil else { return } let emit = emit health = Permissions.startHealthCheck { state in emit(.permissions(state)) } } private func startTap() { let source = captureSignal let tap = EventTap( routing: routing, queue: captureQueue, screens: screens, config: captureConfig(), onWake: { source?.add(data: 1) }) self.tap = tap do { try tap.start() } catch { Log.app.error("event tap not installed (\(error)); this Mac cannot control a peer") } } private func startChannel() { let sink = ChannelSink(emit: emit) let channel = ControlChannel( config: channelConfig(), sequencer: sequencer, replay: replay, sink: sink) self.channel = channel // The signal/atexit path may say `ByeBye` without waking this actor // (contracts C2, last row). EmergencyRelease.shared.arm(channel: channel) channel.start() } // MARK: - The pump private func handle(_ event: EngineEvent) { switch event { case .capturedInput: drainCapture() case .received(let packet, let peerID): dispatch(packet, from: peerID) case .connected(let name, let peerID): noteConnected(name: name, peerID: peerID) case .disconnected(let peerID, let name, let reason): noteDisconnected(peerID: peerID, peerName: name, reason: reason) case .connectionStatus(let status, let name, _): Log.engine.debug("\(name ?? "?"): \(status)") publish() case .idCollision: replaceMachineID() case .tick: tick() case .screensChanged: applyConfiguration() channel?.reopenAll() publish() case .permissions(let state): notePermissions(state) case .systemWoke: Log.app.info("woke; reopening sockets") screens.refresh() applyConfiguration() channel?.reopenAll() case .settingsChanged(let new): apply(new) } } private func noteConnected(name: String, peerID: UInt32) { peerNames[peerID] = name switcher.connectedIDs.insert(peerID) switcher.connectedNames.insert(name) secondsWithoutConnection = 0 Log.engine.info("connected to \(name)") publish() } // MARK: - Captured input (contracts C1, C3) /// Empties the capture ring in order and turns each entry into a packet, a /// switch or a recovery. private func drainCapture() { let items = captureQueue.drain() guard !items.isEmpty else { return } var sawRealInput = false for item in items { switch item { case .key(let vk, let flags): sawRealInput = true sendKey(vk: vk, flags: flags) case .mouse(let data): sawRealInput = true sendMouse(data) case .edgeCandidate(let point, let now): sawRealInput = true considerCrossing(at: point, now: now) case .hotkey(let action): sawRealInput = true perform(action) case .tapLost: recoverLocal(reason: .tapLost) case .overflow: recoverLocal(reason: .captureOverflow) } } // `Event.RealInputEventCount++` (`Event.cs:51-55`): the sessions only // ask whether it moved since their own previous beat, so one bump per // drain that saw input says exactly what `SendAwakeBeat` needs. guard sawRealInput else { return } channel?.noteUserActivity() // `InputHook.cs:256-264`: real input with the pointer on this Mac — // `local`, i.e. the destination is us or ALL — takes the drawn cursor // away. `hide()` is a no-op when it is already gone. if !switcher.destinationIsRemote { fakeCursor.hide() } } private func sendKey(vk: Int32, flags: Int32) { guard let des = inputDestination() else { return } var packet = Packet(type: .keyboard) packet.des = des packet.keyboard = KeyboardData( dateTime: Engine.tick(), virtualKey: vk, flags: flags) // Event.cs:260 stampAndForward(packet) } private func sendMouse(_ data: MouseData) { guard let des = inputDestination() else { return } var packet = Packet(type: .mouse) packet.des = des packet.mouse = data stampAndForward(packet) } /// Where captured input goes, or `nil` when it stays here. /// /// The tap decides from its own snapshot copy, which can be one event stale /// after a switch; this is the authoritative test, so a packet is never sent /// to a peer we have already stopped controlling (`Event.cs:98`). private func inputDestination() -> UInt32? { switcher.destinationIsRemote || switcher.isBroadcasting ? switcher.desMachineID : nil } private func considerCrossing(at point: CGPoint, now: TimeInterval) { guard let jump = switcher.crossing(at: point, now: now) else { return } // `Event.cs:79`: the fullscreen rule is asked *after* the edge geometry // says a switch would happen, so a blocked switch still updates // `LastX`/`LastY` inside `crossing`, exactly as Windows does. guard easyMouseSwitchAllowed() else { Log.engine.debug("edge \(jump.direction) blocked: full-screen app in front") return } Log.engine.debug("edge \(jump.direction) → \(jump.targetName)") perform(switcher.prepareToSwitch(to: jump.targetID, landing: jump.landing, now: now)) } /// `Common.IsEasyMouseSwitchAllowed` (`Common.cs:1638-1650`). /// /// Two early outs before anything looks at a window: the setting is off, or /// this Mac is not the one holding the pointer — "never prevent a switch if /// we are not moving out of the host machine" (`:1646`). That second test is /// also what keeps the check off the relative-mode path, where the machine /// doing the edge detection is the one being controlled /// (`Receiver.cs:156-170`, which never consults it). private func easyMouseSwitchAllowed() -> Bool { guard settings.disableEasyMouseWhenFullscreen else { return true } guard switcher.desMachineID == switcher.localID else { return true } return !Fullscreen.frontmostIsFullscreen( excluding: Set(settings.easyMouseFullscreenExcludedApps), displays: screens.layout.displays) } // MARK: - Received packets (`Receiver.ProcessPackage`, `Receiver.cs:86-390`) /// The port of `ProcessPackage`'s switch. Long on purpose (CLAUDE.md, file /// and function size: a `switch` over `PackageType` is the named exception) /// so that it can be read beside the Windows original case for case. /// /// Everything that reaches here is framed, trusted and de-duplicated by /// `Session` (CLAUDE.md invariant 2); `PreProcess` has already happened. private func dispatch(_ packet: Packet, from peerID: UInt32) { let now = EventTap.now() let forUs = packet.des == switcher.localID || packet.des == MachineID.all switch packet.type { case .keyboard: guard forUs else { break } injector.inject(packet, layout: screens.layout) case .mouse: guard forUs else { break } takeControlBack() // Receiver.cs:122-125 injector.inject(packet, layout: screens.layout) // `Receiver.cs:186-188`: the pointer has just been moved, so this is // where Windows records `LastX`/`LastY` and draws the fake cursor. fakeCursor.show(at: pointerPosition()) reportEdgeToController(packet, now: now) case .nextMachine: // `Receiver.cs:192-198`: the machine we are controlling hit its own // edge in relative mode and is telling us where to go next. // // Windows tests `Event.IsSwitchingByMouseEnabled()` (`Event.cs:152-155`), // which is `EasyMouse == Enable` **or** the Ctrl/Shift Easy-Mouse key // being held. That second half lives in the tap // (`EventTap.easyMouseKeyDown`) and is not published, so with Easy // Mouse set to Ctrl or Shift a relative-mode `NextMachine` is ignored // here where Windows would switch. Filed in the extras README as a // Handshake request to input-capture. guard settings.easyMouse == .enable else { break } let data = packet.mouse perform( switcher.prepareToSwitch( to: UInt32(bitPattern: data.wheelDelta), landing: UniversalPoint(x: data.x, y: data.y), now: now)) case .awake: // `Receiver.cs:244-249`: learn the sender, then // `Common.HumanBeingDetected()` (`Common.cs:561-572`) — a human is // busy on that machine, so this one's display stays on. The sender's // `BlockScreenSaverOnOtherMachines` decides whether `Awake` is sent // at all (`Common.cs:545-559`); the receiver always honours it. perform(switcher.learn(from: packet, now: now)) displayAwake.renew() case .heartbeat, .heartbeatEx, .hello: // `AddToMachinePool` (`Receiver.cs:207-262`). `Heartbeat_ex` and its // two follow-ups are the Windows key-propagation handshake, which is // out of scope (README D6); the packet still identifies its sender, // so it is learned from like any other beat. perform(switcher.learn(from: packet, now: now)) case .hi: break // `Receiver.cs:264-266`: counted, nothing else. case .byeBye: perform(switcher.handleByeBye(packet, now: now)) case .hideMouse: // `Receiver.cs:378-384`: a peer took control; park and let go. perform(switcher.handleHideMouse()) case .clipboard, .machineSwitched, .clipboardAsk, .clipboardText, .clipboardImage, .clipboardDataEnd: clipboardDispatch(packet, from: peerID) // the clipboard lane case .clipboardPush, .clipboardCapture, .clipboardDragDrop, .clipboardDragDropEnd, .clipboardDragDropOperation, .explorerDragDrop, .captureScreenCommand: // `ClipboardPush` only ever appears on a bulk connection; the rest // are drag-and-drop and screen capture, out of scope (README D6). break case .heartbeatExL2, .heartbeatExL3: break // key propagation, out of scope (README D6). default: if packet.type.isMatrix { perform(switcher.applyMatrix(packet)) // `MachineStuff.UpdateMachineMatrix` } } } /// `Receiver.cs:122-125`: mouse input arriving for us means somebody else is /// driving, so control comes home first. /// /// Windows assigns `DesMachineID` directly here rather than switching, so the /// `.moveCursor` half of `switchToMachine` is dropped — the injector is about /// to place the pointer itself and a jump to the screen centre would fight it. private func takeControlBack() { guard switcher.desMachineID != switcher.localID else { return } let actions = switcher.switchToMachine(named: switcher.localName, now: EventTap.now()) perform( actions.filter { if case .moveCursor = $0 { return false } return true }) } /// `Receiver.cs:145-172`: in relative mode the *controlled* machine does the /// edge detection and tells its controller which machine is next. private func reportEdgeToController(_ packet: Packet, now: TimeInterval) { let data = packet.mouse guard data.flags == WindowsMessage.mouseMove, Coordinates.isRelative(UniversalPoint(x: data.x, y: data.y)), let jump = switcher.crossing(at: pointerPosition(), now: now), let next = switcher.nextMachinePacket( toController: packet.src, target: jump.targetID, landing: jump.landing, now: now) else { return } channel?.forward(next, to: .peer(packet.src)) } // MARK: - Helpers /// `Common.GetTick()`: milliseconds, monotonic. Only ever a `DateTime` field /// on the wire; nothing reads it back. static func tick() -> Int64 { Int64(EventTap.now() * 1000) } /// `GetCursorPos`. A null `CGEvent` carries the pointer without posting /// anything, which is the only read-only way to ask CoreGraphics. func pointerPosition() -> CGPoint { CGEvent(source: nil)?.location ?? Coordinates.centre(of: screens.layout.primary) } /// Stamps `Id` and `Src` once and hands the identical packet to every /// matching connection (contracts C1). func stampAndForward(_ packet: Packet) { var stamped = packet stamped.id = sequencer.next() stamped.src = switcher.localID channel?.forward(stamped, to: Engine.destination(for: stamped.des)) } static func destination(for des: UInt32) -> MWBNet.Destination { des == MachineID.all ? .all : .peer(des) } func currentSnapshot() -> EngineSnapshot { EngineSnapshot( peers: channel?.statuses ?? [], controlled: controlledName(), broadcasting: switcher.isBroadcasting, permissions: permissions, tapRunning: tap?.isRunning ?? false, canInject: injector.canInject, easyMouse: settings.easyMouse, localName: switcher.localName, hostnameProblem: hostnameProblem, lastRecovery: lastRecovery) } private func controlledName() -> String? { if switcher.isBroadcasting { return "all machines" } guard switcher.destinationIsRemote else { return nil } return switcher.desMachineName ?? peerNames[switcher.desMachineID] } func publish() { observer?(currentSnapshot()) } }