Files
mac_without_borders/Sources/mwb/EngineActions.swift
T
lucioandClaude Opus 5 c4741fcfeb app-engine: the Engine actor, its actions, recovery and the app shell
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]>
2026-09-16 03:30:27 -07:00

300 lines
12 KiB
Swift

// 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)")
}
}
}