Engine.swift is the actor contracts C3 names: it owns the Switcher, the sequencer, the replay filter, the channel, the tap, the routing state, the capture ring, the injector, the cursor and the screens, and it is the only thing that stamps an Id (contracts C1). Every callback — the channel's sink, the tap's wake-up, the timers, the workspace and settings observers — funnels through one AsyncStream so four queues are serialised once instead of racing as free Tasks. `dispatch` is the port of Receiver.ProcessPackage (Receiver.cs:86-390), long on purpose. EngineActions.swift performs [SwitchAction] (MachineStuff.cs:1008-1050, Helper.cs:73-127), the hotkeys (InputHook.cs:516-655) and the mapping from Settings onto every lane's config struct (contracts C4). Recovery.swift is contracts C2 end to end: escape hotkey, controlled peer lost, tap lost, capture overflow, revoked permission, quit — each ending in route-local, releaseAll and a pointer that is coupled again — plus the reopen countdown (frmScreen.cs:427-450). AppLifecycle.swift is the process: flock single instance, the LSUIElement NSApplication with a placeholder status item, the DispatchSourceSignal + atexit emergency release, and hostname validation (README D7). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
607 lines
23 KiB
Swift
607 lines
23 KiB
Swift
// 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<local slot> 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.
|
|
public var permissions = Permissions.preflight()
|
|
/// 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
|
|
var tap: EventTap?
|
|
var channel: ControlChannel?
|
|
|
|
private let events: AsyncStream<EngineEvent>
|
|
let emit: @Sendable (EngineEvent) -> Void
|
|
private var pump: Task<Void, Never>?
|
|
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<EngineEvent>.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()
|
|
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)
|
|
}
|
|
channel?.sayGoodbye()
|
|
try? await Task.sleep(for: .milliseconds(150))
|
|
channel?.stop()
|
|
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()
|
|
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
|
|
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.
|
|
if sawRealInput { channel?.noteUserActivity() }
|
|
}
|
|
|
|
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 }
|
|
Log.engine.debug("edge \(jump.direction) → \(jump.targetName)")
|
|
perform(switcher.prepareToSwitch(to: jump.targetID, landing: jump.landing, now: now))
|
|
}
|
|
|
|
// 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)
|
|
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.
|
|
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 .heartbeat, .heartbeatEx, .awake, .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 .machineSwitched, .clipboard, .clipboardAsk, .clipboardPush, .clipboardText,
|
|
.clipboardImage, .clipboardCapture, .clipboardDataEnd, .clipboardDragDrop,
|
|
.clipboardDragDropEnd, .clipboardDragDropOperation, .explorerDragDrop,
|
|
.captureScreenCommand:
|
|
break // the clipboard lane; nothing here interprets a payload.
|
|
|
|
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())
|
|
}
|
|
}
|