diff --git a/Sources/mwb/AppLifecycle.swift b/Sources/mwb/AppLifecycle.swift new file mode 100644 index 0000000..e3d9312 --- /dev/null +++ b/Sources/mwb/AppLifecycle.swift @@ -0,0 +1,282 @@ +// The process: one instance, one `NSApplication`, one placeholder status item, +// and the handlers that make sure a crash or a `kill` never leaves this Mac with +// a frozen pointer or a stuck modifier key. +// +// Ported from App/Class/Program.cs (`Main`, the single-instance check at +// 139-175), App/Core/InitAndCleanup.cs (`Cleanup`, 192-215) and +// App/Form/frmScreen.cs (the tray icon and its menu). The menu here is +// deliberately the smallest thing that can run — the real one is the app-ui +// lane; this is enough for the lead to smoke the app (TODO §6). + +import AppKit +import Foundation +import MWBCore +import MWBMac +import MWBNet + +/// This Mac's name on the wire (README D7). +/// +/// Protocol §1.1 gives the field 32 ASCII bytes and the Windows side resolves us +/// by exactly this string (§7), so a name that does not fit, or is not ASCII, is +/// refused up front rather than silently mangled by `Packet.setMachineName`. +enum Hostname { + /// The longest name a `DATA` packet can carry. + static let maximumLength = 32 + + /// The name, plus a sentence explaining why it is unusable when it is. + static func local() -> (name: String, problem: String?) { + var buffer = [CChar](repeating: 0, count: 256) + guard gethostname(&buffer, buffer.count - 1) == 0 else { + return ("", "gethostname() failed") + } + let bytes = buffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) } + let full = String(decoding: bytes, as: UTF8.self) + // `my-mac.local` and `my-mac.example.com` are both `my-mac` on the wire. + let name = full.split(separator: ".").first.map(String.init) ?? full + if name.isEmpty { + return (name, "this Mac has no host name; set one in System Settings > General > Sharing") + } + if !name.allSatisfy(\.isASCII) { + return (name, "host name \"\(name)\" is not ASCII; the protocol allows ASCII only") + } + if name.count > maximumLength { + return (name, "host name \"\(name)\" is longer than \(maximumLength) characters") + } + return (name, nil) + } +} + +/// The `flock` that makes a second launch exit instead of fighting over the tap. +/// +/// Windows uses a named window title (`MachineStuff.CheckSecondInstance`, +/// `:1052-1062`); a lock file is the boring macOS equivalent and releases itself +/// when the process dies, however it dies. +enum SingleInstance { + /// `~/Library/Application Support/mwb-mac/mwb.pid`. + static func pidFileURL() -> URL { + Settings.defaultURL().deletingLastPathComponent().appendingPathComponent("mwb.pid") + } + + /// Takes the lock, returning the descriptor to hold open for the process's + /// lifetime, or `nil` if another copy already holds it. + static func acquire(at url: URL) -> Int32? { + try? FileManager.default.createDirectory( + at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + let descriptor = open(url.path, O_CREAT | O_RDWR, 0o600) + guard descriptor >= 0 else { return nil } + guard flock(descriptor, LOCK_EX | LOCK_NB) == 0 else { + close(descriptor) + return nil + } + ftruncate(descriptor, 0) + let pid = "\(ProcessInfo.processInfo.processIdentifier)\n" + _ = pid.withCString { write(descriptor, $0, strlen($0)) } + return descriptor + } +} + +/// The last thing that runs, however the process ends (contracts C2, last row). +/// +/// Everything here is **synchronous and never touches the Engine actor**: an +/// `atexit` handler cannot `await`, and a Mac left with held modifiers or a +/// pointer still disassociated from the mouse is exactly the failure CLAUDE.md +/// invariant 3 forbids. `Injector.releaseAll()` and `Cursor.restoreEverything()` +/// are both documented safe from any thread by their own lanes. +final class EmergencyRelease: @unchecked Sendable { + static let shared = EmergencyRelease() + + private let lock = NSLock() + private var injector: Injector? + private var cursor: Cursor? + private var done = false + + /// Hands over the two objects the handlers may touch. Called once, at start. + func arm(injector: Injector, cursor: Cursor) { + lock.lock() + self.injector = injector + self.cursor = cursor + lock.unlock() + } + + /// Releases every held key and gives the pointer back. Idempotent. + func run() { + lock.lock() + let alreadyDone = done + done = true + let injector = self.injector + let cursor = self.cursor + lock.unlock() + guard !alreadyDone else { return } + cursor?.restoreEverything() + injector?.releaseAll() + } +} + +/// The app. +@MainActor +final class AppDelegate: NSObject, NSApplicationDelegate { + private var engine: Engine? + private var store: SettingsStore? + private var statusItem: NSStatusItem? + private var titleItem: NSMenuItem? + private var lockDescriptor: Int32? + private var signalSources: [any DispatchSourceSignal] = [] + private var terminating = false + + func applicationDidFinishLaunching(_ notification: Notification) { + guard let descriptor = SingleInstance.acquire(at: SingleInstance.pidFileURL()) else { + FileHandle.standardError.write(Data("mwb: another instance is already running\n".utf8)) + exit(1) + } + lockDescriptor = descriptor + + Log.startFileLogging() + Log.app.info("mwb \(MWBVersion.string) starting") + + buildStatusItem() + installSignalHandlers() + atexit { EmergencyRelease.shared.run() } + + do { + try startEngine() + } catch { + Log.app.error("could not start: \(error)") + setTitle("mwb — settings error") + } + } + + func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply { + guard let engine, !terminating else { return .terminateNow } + terminating = true + Task { + await engine.stop() + NSApp.reply(toApplicationShouldTerminate: true) + } + return .terminateLater + } + + func applicationWillTerminate(_ notification: Notification) { + EmergencyRelease.shared.run() + Log.stopFileLogging() + } + + // MARK: - Startup + + private func startEngine() throws { + let store = try SettingsStore() + self.store = store + + let host = Hostname.local() + let engine = Engine(store: store, localName: host.name, hostnameProblem: host.problem) + self.engine = engine + EmergencyRelease.shared.arm(injector: engine.injector, cursor: engine.cursor) + + // input-capture request 4: display-change observation is main-thread work + // and needs `NSApplication.shared` to exist first. + engine.screens.startObserving() + observeWorkspace(engine) + store.onExternalChange { [emit = engine.emit] settings in emit(.settingsChanged(settings)) } + store.startWatching() + + // A `@MainActor` class is `Sendable`, so the snapshot callback may hold + // the delegate and hop back to the main actor to draw. + Task { [weak self] in + await engine.observe { snapshot in + Task { @MainActor in self?.render(snapshot) } + } + await engine.start() + } + } + + private func observeWorkspace(_ engine: Engine) { + NSWorkspace.shared.notificationCenter.addObserver( + forName: NSWorkspace.didWakeNotification, object: nil, queue: .main + ) { [emit = engine.emit] _ in + emit(.systemWoke) + } + } + + private func installSignalHandlers() { + // `DispatchSourceSignal` rather than `signal(2)`: the handler then runs + // on an ordinary queue, where posting key-ups and talking to the window + // server are legal, instead of in signal context where they are not. + for number in [SIGTERM, SIGINT, SIGHUP] { + signal(number, SIG_IGN) + let source = DispatchSource.makeSignalSource(signal: number, queue: .main) + source.setEventHandler { + EmergencyRelease.shared.run() + exit(0) + } + source.resume() + signalSources.append(source) + } + } + + // MARK: - The placeholder status item (app-ui replaces all of this) + + private func buildStatusItem() { + let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) + item.button?.title = "mwb" + let menu = NSMenu() + let title = NSMenuItem(title: "mwb \(MWBVersion.string) — starting", action: nil, keyEquivalent: "") + title.isEnabled = false + menu.addItem(title) + menu.addItem(.separator()) + menu.addItem( + NSMenuItem( + title: "Request Permissions…", action: #selector(requestPermissions), + keyEquivalent: "")) + menu.addItem( + NSMenuItem(title: "Reconnect", action: #selector(reconnect), keyEquivalent: "")) + menu.addItem(.separator()) + menu.addItem(NSMenuItem(title: "Quit mwb", action: #selector(quit), keyEquivalent: "q")) + for entry in menu.items where entry.action != nil { entry.target = self } + item.menu = menu + statusItem = item + titleItem = title + } + + /// One line of state: what the lead needs to see that the app is alive. + func render(_ snapshot: EngineSnapshot) { + if let problem = snapshot.hostnameProblem { + setTitle("mwb — host name unusable: \(problem)") + statusItem?.button?.title = "mwb!" + return + } + var parts: [String] = [] + if !snapshot.permissions.isComplete { + var missing: [String] = [] + if !snapshot.permissions.listen { missing.append("Input Monitoring") } + if !snapshot.permissions.post { missing.append("Accessibility") } + parts.append("permissions missing: \(missing.joined(separator: ", "))") + } else if !snapshot.canInject { + parts.append("cannot inject events") + } else { + parts.append("running") + } + let connected = snapshot.peers.filter { $0.status == .connected }.count + parts.append("\(connected) connected") + if let controlled = snapshot.controlled { parts.append("controlling \(controlled)") } + setTitle("mwb \(MWBVersion.string) — " + parts.joined(separator: " — ")) + statusItem?.button?.title = snapshot.controlled == nil ? "mwb" : "mwb →" + } + + private func setTitle(_ text: String) { + titleItem?.title = text + } + + /// CLAUDE.md, Workflow: the **only** call to `Permissions.request()` in the + /// repository, and it happens because the user clicked this item. + @objc private func requestPermissions() { + _ = Permissions.request() + } + + @objc private func reconnect() { + guard let engine else { return } + Task { await engine.reconnect() } + } + + @objc private func quit() { + NSApp.terminate(nil) + } +} diff --git a/Sources/mwb/Engine.swift b/Sources/mwb/Engine.swift new file mode 100644 index 0000000..ff622b3 --- /dev/null +++ b/Sources/mwb/Engine.swift @@ -0,0 +1,606 @@ +// 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. + 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 + 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() + 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()) + } +} diff --git a/Sources/mwb/EngineActions.swift b/Sources/mwb/EngineActions.swift new file mode 100644 index 0000000..4d5de27 --- /dev/null +++ b/Sources/mwb/EngineActions.swift @@ -0,0 +1,299 @@ +// What the Engine *does*: the `SwitchAction` list `Switcher` hands back, the +// hotkeys the tap classified, and the mapping from `Settings` onto every lane's +// config struct (contracts C4). +// +// Ported from App/Core/MachineStuff.cs `SwitchToMachine` (1008-1028) and +// `SwitchToMultipleMode` (1030-1050), App/Core/Helper.cs `HelperThread` +// (73-127), App/Class/InputHook.cs `ProcessHotKeys` (516-621) and `Switch2` +// (623-655), App/Core/InitAndCleanup.cs `ReleaseAllKeys` (214-243). + +import AppKit +import Foundation +import MWBCore +import MWBMac +import MWBNet + +extension Engine { + + // MARK: - Applying a `[SwitchAction]` + + /// Runs a switch's actions in order, then brings the routing snapshot, the + /// channel and the cursor into line with the result. + /// + /// Always call this rather than `perform(_ action:)` directly: the tail is + /// what tells the tap to start or stop swallowing, what arms the 30 s stall + /// rule (control-channel request 2) and what hands the pointer back. + func perform(_ actions: [SwitchAction]) { + for action in actions { perform(action) } + syncRouting() + publish() + } + + private func perform(_ action: SwitchAction) { + switch action { + case .send(let packet): + // Already sequenced and addressed by `Switcher` (contracts C1). + channel?.forward(packet, to: Engine.destination(for: packet.des)) + + case .parkCursor(let destinationIsRemote, let byHideMouseMessage): + lastLocalPosition = cursor.park( + hideMouse: settings.hideMouseAtScreenEdge, layout: screens.layout, + destinationIsRemote: destinationIsRemote, + byHideMouseMessage: byHideMouseMessage) + + case .moveCursor(let landing): + noteCursorLanding(landing) + + case .releaseAllKeys: + injector.releaseAll() + + case .desMachineChanged(let id, let name): + Log.engine.info("control → \(name ?? "id \(id)")") + + case .persistMatrix: + persist { settings in settings.matrix = self.switcher.matrix } + + case .persistMachinePool: + persist { settings in settings.setPool(self.switcher.pool) } + + case .reopenSockets: + reconfigureChannel() + + case .remoteClipboardWanted: + break // the clipboard lane asks the machine we just left for its data. + } + } + + /// `Helper.HelperThread` (`:96-113`) moves the pointer to the switch + /// location **only when the machine being switched to is this one**; on the + /// way out it parks instead. Pixel-tagged values are pixels, everything else + /// is 0..65535 over the primary monitor (`InputSimulation.MoveMouseEx`). + private func noteCursorLanding(_ landing: UniversalPoint) { + guard !switcher.destinationIsRemote, !switcher.isBroadcasting else { return } + let target = + Coordinates.isPixels(landing) + ? Coordinates.untagPixels(landing) + : Coordinates.fromUniversal(landing, in: screens.layout.primary) + pendingCursorTarget = target + } + + /// Rewrites the routing snapshot, tells the channel which peer is being + /// driven, and couples or decouples the pointer. + func syncRouting() { + let remote = switcher.destinationIsRemote + let broadcasting = switcher.isBroadcasting + // Read out of the actor's state *before* the closure: `update` takes a + // `@Sendable` body, and `Switcher` may not leave the actor. + let destination: MWBCore.Destination = + remote || broadcasting ? .remote(switcher.desMachineID) : .local + routing.update { snapshot in + snapshot.destination = destination + // input-capture request 2: a single remote destination swallows, ALL + // mode does not — this Mac is one of "all" and must still act on the + // input it is broadcasting. + snapshot.swallowKeys = remote + snapshot.swallowMouse = remote + } + channel?.markControlled(peerID: remote ? switcher.desMachineID : nil) + + if remote { + if !cursor.isDecoupled { + lastLocalPosition = cursor.decouple( + parkHidden: settings.hideMouseAtScreenEdge, layout: screens.layout) + } + } else if cursor.isDecoupled || pendingCursorTarget != nil { + let target = pendingCursorTarget ?? lastLocalPosition + cursor.recouple(to: target) + if let target { routing.virtualCursor = target } + } + pendingCursorTarget = nil + } + + // MARK: - Hotkeys (`InputHook.ProcessHotKeys`, `:516-621`) + + /// Performs what the tap classified. The tap has already swallowed the keys + /// and, for `.escapedToLocal`, already flipped the routing snapshot + /// (input-capture request 3). + func perform(_ action: HotkeyAction) { + switch action { + case .switchToSlot(let slot): switchTo(slot: slot) + case .lockMachine: lockControlledMachine() + case .lockAllMachines: lockAll() + case .reconnect: reconnect() + case .toggleEasyMouse: toggleEasyMouse() + case .toggleSwitchToAll: switchToAll() + case .escapedToLocal: recoverLocal(reason: .escapeHotkey) + } + } + + /// `Switch2` (`InputHook.cs:623-655`): release everything, then hand control + /// to the machine in that matrix slot. An empty slot does nothing. + public func switchTo(slot: Int) { + let names = switcher.matrix.names + guard slot >= 0, slot < names.count else { return } + let name = names[slot].trimmingCharacters(in: .whitespaces) + guard !name.isEmpty else { return } + injector.releaseAll() // InputHook.cs:632 + perform(switcher.switchToMachine(named: name, now: EventTap.now())) + } + + /// `SwitchToMultipleMode(DesMachineID != ID.ALL, true)` (`InputHook.cs:518-522`). + public func switchToAll() { + perform(switcher.switchToBroadcast(!switcher.isBroadcasting, centerCursor: true)) + } + + /// `PleaseReopenSocket = REOPEN_WHEN_HOTKEY` (`InputHook.cs:578-584`). + public func reconnect() { + Log.engine.info("reconnect requested") + secondsWithoutConnection = 0 + channel?.reopenAll() + } + + /// `EasyMouse` flips between Disable and Enable only; the Ctrl and Shift + /// modes are left alone (`InputHook.cs:524-537`). + public func toggleEasyMouse() { + let mode = settings.easyMouse + guard mode == .disable || mode == .enable else { return } + let next: EasyMouseMode = mode == .disable ? .enable : .disable + persist { settings in settings.easyMouse = next } + applyConfiguration() + publish() + } + + /// A single press of the lock hotkey (`InputHook.cs:570`): the chord goes to + /// the machine in control so *it* locks. Nothing happens locally. + /// + /// input-inject request 1: `Injector.lockChord(for:)` is the encoder, the + /// Engine is the only thing that may stamp and distribute (contracts C1). + public func lockControlledMachine() { + guard let des = lockDestination() else { return } + forwardLockChord(to: des) + } + + /// A double press (`InputHook.cs:546-566`): broadcast the chord to everyone, + /// come back out of ALL mode, then lock this Mac too. + public func lockAll() { + perform(switcher.switchToBroadcast(true, centerCursor: true)) + forwardLockChord(to: MachineID.all) + perform(switcher.switchToBroadcast(false, centerCursor: true)) + injector.lockThisMac() + } + + private func lockDestination() -> UInt32? { + if switcher.isBroadcasting { return MachineID.all } + return switcher.destinationIsRemote ? switcher.desMachineID : nil + } + + /// Replays the hotkey as ordinary `Keyboard` packets, downs then ups, in the + /// Windows order (`InputHook.cs:485-512, 548-562`). + private func forwardLockChord(to des: UInt32) { + for key in Injector.lockChord(for: settings.lockMachineShortcut) { + var packet = Packet(type: .keyboard) + packet.des = des + packet.keyboard = KeyboardData( + dateTime: Engine.tick(), virtualKey: key.virtualKey, flags: key.flags) + stampAndForward(packet) + } + } + + // MARK: - Settings → configs (contracts C4) + + /// Re-derives every lane's config from the current settings and hands it + /// over. Called at startup, on a settings change and on a display change. + func applyConfiguration() { + switcher.edge.config = screens.layout.edgeConfig( + blockCorners: settings.blockMouseAtScreenCorners, + moveRelatively: settings.moveMouseRelatively) + tap?.reconfigure(captureConfig()) + injector.reconfigure(InjectorConfig(lockMachine: settings.lockMachineShortcut)) + syncRouting() + } + + /// The tap's half of the settings (contracts C4). + func captureConfig() -> CaptureConfig { + CaptureConfig( + hotkeys: settings.hotkeys, easyMouse: settings.easyMouse, + moveMouseRelatively: settings.moveMouseRelatively, + localSlot: switcher.matrix.slot(of: switcher.localName)) + } + + /// The channel's half. The local name is dropped from the matrix list: the + /// channel dials every name it has no client for, and dialling ourselves + /// only earns a `.selfConnection` (`SocketStuff.cs:1430-1437`). + func channelConfig() -> ChannelConfig { + let peers = switcher.matrix.names.filter { name in + !name.isEmpty && name.caseInsensitiveCompare(switcher.localName) != .orderedSame + } + return ChannelConfig( + localName: switcher.localName, localID: switcher.localID, port: settings.tcpPort, + securityKey: settings.securityKey, matrixNames: peers, name2IP: settings.name2IP, + sameSubnetOnly: settings.sameSubnetOnly, + validateRemoteIP: settings.validateRemoteMachineIP, + blockScreenSaver: settings.blockScreenSaverOnOtherMachines) + } + + func reconfigureChannel() { + channel?.reconfigure(channelConfig()) + } + + /// The settings file changed underneath us (`Setting.cs:197-207`). + /// + /// A key, port, name or id change reopens every socket; a matrix change is + /// replicated to the peers the way a local edit is; everything else just + /// rewrites the configs. + public func apply(_ new: Settings) { + let before = channelConfig() + settings = new + if new.matrix != switcher.matrix { + perform(switcher.setMatrix(new.matrix).filter { !isPersistMatrix($0) }) + } + applyConfiguration() + let after = channelConfig() + if after != before { channel?.reconfigure(after) } + publish() + } + + /// A matrix that arrived *from* the settings file must not be written back + /// to it — that is the change we are reacting to. + private func isPersistMatrix(_ action: SwitchAction) -> Bool { + if case .persistMatrix = action { return true } + return false + } + + // MARK: - Identity and permissions + + /// `SocketStuff.cs:1980-1992`: a peer we dialled claims our machine id, so we + /// pick another one and start over (control-channel Handshakes). + func replaceMachineID() { + let fresh = Int32.random(in: 1...Int32.max) + Log.engine.error("machine id collision; taking a new id") + persist { settings in settings.machineID = fresh } + reconfigureChannel() + channel?.reopenAll() + publish() + } + + /// The 5 s health check noticed a grant change (contracts C2). + func notePermissions(_ state: PermissionState) { + let lostListening = permissions.listen && !state.listen + permissions = state + if lostListening { + recoverLocal(reason: .permissionsLost) + } else { + publish() + } + } + + // MARK: - Persistence + + /// Edits the settings file and keeps our copy in step. A write failure is + /// logged, never thrown at a caller that cannot do anything about it. + func persist(_ body: (inout Settings) -> Void) { + do { + try store.update(body) + settings = store.current + } catch { + Log.settings.error("could not save settings: \(error)") + } + } +} diff --git a/Sources/mwb/Recovery.swift b/Sources/mwb/Recovery.swift new file mode 100644 index 0000000..0b5e9d1 --- /dev/null +++ b/Sources/mwb/Recovery.swift @@ -0,0 +1,119 @@ +// Getting the keyboard and the mouse back: every row of contracts C2, and the +// countdown that keeps dialling when nothing is connected. +// +// CLAUDE.md invariant 3 is what this file exists for. Each row ends the same +// way — control local, held keys released, pointer re-associated — and none of +// it waits on the network: `recoverLocal` touches the routing snapshot, the +// injector and the cursor, all of which are local and lock-free enough to run +// from a disconnect callback or a signal handler. +// +// Ported from App/Core/Common.cs `ProcessByeByeMessage` (622-630), +// App/Core/MachineStuff.cs `RemoveDeadMachines` (675-694), +// App/Core/InitAndCleanup.cs `ReleaseAllKeys` (214-243) and `Cleanup` (192-215), +// App/Form/frmScreen.cs `HelperTimer_Tick` (427-461). + +import Foundation +import MWBCore +import MWBMac +import MWBNet + +extension Engine { + + /// Brings control home and puts this Mac back in a usable state. + /// + /// Idempotent: calling it while control is already local still releases held + /// keys and re-associates the pointer, which is exactly what `.tapLost` and + /// a revoked permission need — after either of those the held-key state is + /// unknown even though nothing switched. + public func recoverLocal(reason: RecoveryReason) { + routing.routeLocal() + + // `SwitchToMachine(MachineName)` is what Windows uses on every one of + // these rows (`Common.cs:626`, `MachineStuff.cs:691`), so control comes + // home the same way a hotkey would: the machine we were driving is told + // to park, and our own pointer lands in the middle of the primary screen. + var actions: [SwitchAction] = [] + if switcher.desMachineID != switcher.localID { + actions = switcher.switchToMachine(named: switcher.localName, now: EventTap.now()) + } + injector.releaseAll() + perform(actions) + // Belt and braces for CLAUDE.md invariant 3: this shows the pointer and + // re-associates it with the mouse **without moving it**, and is a no-op + // when `syncRouting` has already done so. A recovery that fires while + // control was never remote (`.tapLost`, a revoked grant) must not jerk + // the user's own pointer anywhere. + cursor.recouple(to: nil) + + lastRecovery = RecoveryNote(reason: reason, at: Date()) + Log.engine.info("control back on this Mac: \(reason.text)") + publish() + } + + /// A connection ended, for any of the reasons in contracts C2's table: a + /// `ByeBye`, a socket close, a read or send error, an invalid key, the 30 s + /// stall rule or a force close. + func noteDisconnected(peerID: UInt32?, peerName: String?, reason: DisconnectReason) { + if let peerName { switcher.connectedNames.remove(peerName) } + guard let peerID else { + // Died before the handshake named it: nothing was ever controlled by + // it, so there is nothing to recover from (control-channel Handshakes). + Log.engine.debug("connection to \(peerName ?? "?") ended: \(reason)") + publish() + return + } + + let wasDriving = peerID == switcher.desMachineID + switcher.connectedIDs.remove(peerID) + perform(switcher.connectionLost(id: peerID, now: EventTap.now())) + Log.engine.info("\(peerName ?? peerNames[peerID] ?? "peer") disconnected: \(reason)") + peerNames[peerID] = nil + + if wasDriving { + recoverLocal(reason: .controlledPeerLost(peerName)) + } else { + publish() + } + } + + /// The 1 s timer: the reopen countdown, and nothing else. + /// + /// `Session` beats on the channel's own 100 ms tick and the stall rule is + /// armed by `markControlled`, so neither needs anything from here. + func tick() { + reopenCountdown() + } + + /// `frmScreen.cs:427-450`: while no socket is established, dial again. + /// + /// The channel stops dialling 30 s after `start()` or `reopenAll()` + /// (control-channel Handshakes, request 1), so without this a machine that + /// boots late is never reached. Windows re-checks on its 100 ms timer every + /// `count % 300` ticks — 30 s — which is also the channel's connect budget, + /// so the two line up exactly. + private func reopenCountdown() { + guard channel != nil else { return } + guard switcher.connectedIDs.isEmpty else { + secondsWithoutConnection = 0 + return + } + secondsWithoutConnection += 1 + guard secondsWithoutConnection >= Engine.reopenAfterSecondsIdle else { return } + secondsWithoutConnection = 0 + Log.engine.info("nothing connected; reopening sockets") + channel?.reopenAll() + } + + /// What `Setting.Values` holds on exit: the packet counter so ids keep + /// rising across restarts (`Common.cs:906`), the pointer's last position and + /// the machine pool. + func persistOnExit() { + persist { settings in + settings.packageID = self.sequencer.current + settings.lastX = self.switcher.edge.lastX + settings.lastY = self.switcher.edge.lastY + settings.setPool(self.switcher.pool) + settings.matrix = self.switcher.matrix + } + } +} diff --git a/Sources/mwb/main.swift b/Sources/mwb/main.swift index 863676a..30718a7 100644 --- a/Sources/mwb/main.swift +++ b/Sources/mwb/main.swift @@ -1,13 +1,19 @@ // mwb — the executable. Wires MWBCore, MWBNet and MWBMac together. -// Until the menubar-app lane lands this is a smoke binary: it proves the -// three targets link, and reports the two TCC permissions the app needs. +// +// With no arguments it runs the app: an `LSUIElement` `NSApplication` with the +// placeholder status item of `AppLifecycle.swift`. The two diagnostic flags stay +// because the build and the bundle script use them, and because they must work +// without creating a settings file, a log file or an event tap. + +import AppKit import Foundation import MWBCore import MWBMac import MWBNet let usage = """ - usage: mwb --version | --check-permissions + usage: mwb [--version | --check-permissions] + (no arguments) run the app in the menu bar --version print the build version and exit 0 --check-permissions print Input Monitoring / Accessibility state; exit 0 if both granted, 3 otherwise """ @@ -22,8 +28,21 @@ func checkPermissions() -> Int32 { return state.isComplete ? 0 : 3 } +@MainActor +func runApp() -> Never { + let application = NSApplication.shared + let delegate = AppDelegate() + application.delegate = delegate + // No Dock icon and no menu bar of our own; the status item is the whole UI. + application.setActivationPolicy(.accessory) + application.run() + exit(0) +} + let arguments = Array(CommandLine.arguments.dropFirst()) switch arguments { +case []: + runApp() case ["--version"]: print("mwb \(MWBVersion.string)") exit(0)