Files
mac_without_borders/Sources/mwb/EngineActions.swift
T
lucioandClaude Opus 5 bb873807b8 app-engine: install the event tap when the permission finally arrives
The 5 s health check already had to notice Input Monitoring being
revoked (contracts C2). Noticing it being granted and retrying
EventTap.start() means a first run does not have to be restarted after
the user ticks the box in System Settings.

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

314 lines
13 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`
// (626-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:626-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:635
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:544-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).
///
/// Losing Input Monitoring means the tap is dead, so control comes home.
/// *Gaining* it is the other half: the tap that could not be installed at
/// startup is retried here, so granting the permission does not need a
/// restart. `EventTap.start()` is a no-op when one is already running.
func notePermissions(_ state: PermissionState) {
let lostListening = permissions.listen && !state.listen
permissions = state
if lostListening {
recoverLocal(reason: .permissionsLost)
return
}
if state.isComplete, let tap, !tap.isRunning {
do {
try tap.start()
tap.reconfigure(captureConfig())
Log.app.info("permissions granted; event tap installed")
} catch {
Log.app.error("event tap still not installable: \(error)")
}
}
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)")
}
}
}