diff --git a/Sources/mwb/EngineActions.swift b/Sources/mwb/EngineActions.swift index c04d42d..4f7675f 100644 --- a/Sources/mwb/EngineActions.swift +++ b/Sources/mwb/EngineActions.swift @@ -24,11 +24,34 @@ extension Engine { /// 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]) { + let wasDes = switcher.desMachineID + let wasBroadcasting = switcher.isBroadcasting for action in actions { perform(action) } + releaseKeysIfControlCameHome(wasDes: wasDes, wasBroadcasting: wasBroadcasting) syncRouting() publish() } + /// `Helper.HelperThread` releases every held key as soon as + /// `NewDesMachineID == MachineID` (`Helper.cs:120-123`), and the event it + /// waits on is set by *every* switch — `SwitchToMachine` + /// (`MachineStuff.cs:1024`) and `PrepareToSwitchToMachine` (`Event.cs:203`) + /// alike. So a received `ByeBye`, an edge crossing and a `NextMachine` + /// packet that land control back on this Mac release too, not only the + /// hotkey and the broadcast toggle, which carry their own + /// `.releaseAllKeys`. Calling it twice is harmless: `releaseAll()` is + /// idempotent. + /// + /// Only on an actual change of target, though. While a peer is driving + /// *this* Mac our own destination is local the whole time, and releasing on + /// a switch that did not move it — a matrix edit, say — would drop the + /// modifiers that peer is holding down, mid-keystroke. + private func releaseKeysIfControlCameHome(wasDes: UInt32, wasBroadcasting: Bool) { + let moved = switcher.desMachineID != wasDes || switcher.isBroadcasting != wasBroadcasting + guard moved, !switcher.destinationIsRemote, !switcher.isBroadcasting else { return } + injector.releaseAll() + } + private func perform(_ action: SwitchAction) { switch action { case .send(let packet):