// Which machine the keyboard and mouse are driving right now, and everything // that changes it: an edge crossing, a hotkey, ALL mode, a `NextMachine` packet // from a controlled machine, a peer appearing or going away. // See docs/protocol.md §4.2-§4.4. // // Ported from App/Core/MachineStuff.cs (712-777, 1008-1050), App/Core/Event.cs // PrepareToSwitchToMachine (157-236), App/Core/Common.cs SendNextMachine // (516-539) and ProcessByeByeMessage (622-630), App/Core/Receiver.cs (156-170, // 284-291, 383-388). import Foundation /// A completed edge crossing: which way, to which machine, and where the cursor /// arrives there. public struct Jump: Sendable, Equatable { /// The direction the cursor left in. public var direction: Direction /// The machine it is going to. public var targetID: UInt32 /// That machine's name. public var targetName: String /// Where it lands, as a universal value (docs/protocol.md §4.4). public var landing: UniversalPoint } /// Something the app must do as a result of a switch. `Switcher` never performs /// I/O; it says what happened and the app's platform layers act. public enum SwitchAction: Sendable, Equatable { /// Queue this packet on every connection (`Des` is already set). case send(Packet) /// Park the real cursor at the top centre of the primary screen /// (`HideMouseCursor`, `Common.cs:1482-1496`). `byHideMouseMessage` is the /// Windows flag: true when a peer asked with `HideMouse (50)`. case parkCursor(byHideMouseMessage: Bool) /// Put the cursor at this switch location; pixel-tagged values mean pixels /// (`Coordinates.isPixels`, `Helper.cs:100-115`). case moveCursor(UniversalPoint) /// Synthesize key-up for every modifier still held /// (`ReleaseAllKeys`, `InitAndCleanup.cs:214-243`). case releaseAllKeys /// The controlled machine changed; update the menu bar. case desMachineChanged(id: UInt32, name: String?) /// Persist `MachineMatrixString` (and the two layout flags). case persistMatrix /// Persist `MachinePool`. case persistMachinePool /// Re-open client sockets, because the matrix changed. case reopenSockets /// Big clipboard data may be waiting on the machine we just left /// (`Receiver.cs:284-291`). case remoteClipboardWanted } /// The machine-switching state machine: matrix, pool and `desMachineID`. /// /// One instance per app. Not `Sendable`: the app owns it on the same queue as /// its sessions, exactly as Windows owns one set of statics behind locks. public final class Switcher { /// This machine's name, as peers see it. public let localName: String /// This machine's id (`MachineID` setting). public let localID: UInt32 /// The matrix, as edited locally or replicated from a peer. public private(set) var matrix: Matrix /// Everything known about the other machines. public private(set) var pool: MachinePool /// Edge geometry; the app updates `edge.config` when displays change. public var edge: Edge /// Ids with a live connection, maintained by the network layer /// (`Common.IsConnectedTo`, `Common.cs:849-887`). public var connectedIDs: Set = [] /// Names with a live connection, for `LiveMachineMatrix` /// (`MachineStuff.cs:940`). public var connectedNames: Set = [] /// The machine currently receiving input, or `MachineID.all` in ALL mode /// (`MachineStuff.desMachineID`). public private(set) var desMachineID: UInt32 /// Its name (`MachineStuff.DesMachineName`, `Common.cs:239-248`). public private(set) var desMachineName: String? /// The machine a switch is heading towards (`MachineStuff.newDesMachineID`). public private(set) var newDesMachineID: UInt32 private let sequencer: PacketSequencer private var lastJump: TimeInterval = 0 private var lastNextMachineSend: TimeInterval = 0 /// A switcher that starts out controlling its own machine /// (`InitAndCleanup.cs:70`). public init( localName: String, localID: UInt32, matrix: Matrix, pool: MachinePool, edge: Edge, sequencer: PacketSequencer ) { self.localName = localName self.localID = localID self.matrix = matrix self.pool = pool self.edge = edge self.sequencer = sequencer desMachineID = localID newDesMachineID = localID desMachineName = pool.name(for: localID) ?? localName } /// True while input goes to every machine at once (`ID.ALL`). public var isBroadcasting: Bool { desMachineID == MachineID.all } /// Whether a machine can be reached right now: itself always, others only /// with a live socket (`Common.cs:852-855`). public func isConnected(to id: UInt32) -> Bool { id == localID || connectedIDs.contains(id) } // MARK: - Edge crossings /// The jump this cursor position implies, or `nil` for "stay put". /// /// Puts `Edge` (which way did it leave) together with `Matrix` (what is that /// way) and `MachinePool` (can we reach it), as `MoveToMyNeighbourIfNeeded` /// and the `Move*` methods do between them (`MachineStuff.cs:203-673`). public func crossing(at point: CGPoint, now: TimeInterval) -> Jump? { let cursorIsLocal = desMachineID == localID guard let direction = edge.crossing( at: point, cursorIsLocal: cursorIsLocal, broadcasting: isBroadcasting, lastJump: lastJump, now: now), let current = pool.name(for: desMachineID) // NameFromID, MachineStuff.cs:298-302 else { return nil } // IsConnectedTo answers yes for our own id without a socket // (Common.cs:852-855), so the local machine is always live. let live = matrix.live(connectedNames: connectedNames.union([localName])) guard let targetName = matrix.neighbour( of: current, direction: direction, live: live, isReachable: { self.pool.resolveID(name: $0) != nil }), let targetID = pool.resolveID(name: targetName), targetID != desMachineID // MachineStuff.cs:381, 520, 589, 659 else { return nil } let landing = edge.landing( direction: direction, from: point, targetIsLocal: targetID == localID, cursorIsLocal: cursorIsLocal) return Jump( direction: direction, targetID: targetID, targetName: targetName, landing: landing) } /// Commits a switch (`PrepareToSwitchToMachine`, `Event.cs:157-236`). /// /// Refuses inside the 100 ms debounce or in ALL mode, and cancels silently /// when the target has no live connection. `landing` is where the cursor /// should appear. public func prepareToSwitch(to id: UInt32, landing: UniversalPoint, now: TimeInterval) -> [SwitchAction] { let sinceJump = now - lastJump if (sinceJump < Edge.jumpDebounce && sinceJump > 0) || isBroadcasting { return [] } lastJump = now guard isConnected(to: id) else { return [] } // Event.cs:171-177 newDesMachineID = id var actions: [SwitchAction] = [.moveCursor(landing)] guard desMachineID != id else { return actions } // Event.cs:207 // Ask the machine losing control to park its cursor (Event.cs:211-215). if id != MachineID.all && desMachineID != localID { actions.append(.send(packet(.hideMouse, to: desMachineID))) } setDesMachine(id) if desMachineID == localID { actions.append(.remoteClipboardWanted) // Event.cs:221-226 } else { actions.append(.send(packet(.machineSwitched, to: desMachineID))) // Event.cs:230 } actions.append(.desMachineChanged(id: desMachineID, name: desMachineName)) return actions } // MARK: - Explicit switches /// Switches to a machine by name: the hotkey and menu path /// (`SwitchToMachine`, `MachineStuff.cs:1008-1028`). /// /// The cursor is put at the centre of the primary screen in **pixels**, not /// as a universal value (`:1021-1022`). public func switchToMachine(named name: String, now: TimeInterval) -> [SwitchAction] { guard let id = pool.resolveID(name: name) else { return [] } var actions: [SwitchAction] = [] if desMachineID != localID { actions.append(.send(packet(.hideMouse, to: desMachineID))) // MachineStuff.cs:1017 } newDesMachineID = id setDesMachine(id) let centre = Coordinates.centre(of: edge.config.primary) // MachineStuff.cs:1021-1022 actions.append(.moveCursor(Coordinates.tagPixels(centre))) actions.append(.parkCursor(byHideMouseMessage: false)) // MachineStuff.cs:1025 actions.append(.desMachineChanged(id: desMachineID, name: desMachineName)) return actions } /// Turns ALL mode on or off (`SwitchToMultipleMode`, `MachineStuff.cs:1030-1050`). public func switchToBroadcast(_ on: Bool, centerCursor: Bool) -> [SwitchAction] { let id = on ? MachineID.all : localID newDesMachineID = id setDesMachine(id) var actions: [SwitchAction] = [] if centerCursor { // MoveMouseToCenter, Common.cs:1474-1480 actions.append( .moveCursor(Coordinates.tagPixels(Coordinates.centre(of: edge.config.primary)))) } actions.append(.releaseAllKeys) // MachineStuff.cs:1047 actions.append(.desMachineChanged(id: desMachineID, name: desMachineName)) return actions } // MARK: - Packets /// The `NextMachine (121)` packet a *controlled* machine sends back to its /// controller when the cursor hit its own edge in relative mode /// (`SendNextMachine`, `Common.cs:516-539`). /// /// The target machine's id rides in `Md.WheelDelta`. At most one per 100 ms; /// `nil` means the rate limit swallowed it. public func nextMachinePacket( toController controller: UInt32, target: UInt32, landing: UniversalPoint, now: TimeInterval ) -> Packet? { guard now - lastNextMachineSend >= 0.1 else { return nil } // Common.cs:520-524 lastNextMachineSend = now var p = Packet(type: .nextMachine) p.des = controller p.mouse = MouseData(x: landing.x, y: landing.y, wheelDelta: Int32(bitPattern: target)) return stamped(p) // Common.cs:534 goes out through SkSend } /// Learns the sender of a `Heartbeat`, `Awake` or `Hello` /// (`AddToMachinePool`, `MachineStuff.cs:712-777`). /// /// A known name just has its id and timestamp refreshed — no actions at /// all: the known-machine branch `return`s at `MachineStuff.cs:737`, before /// the `UpdateMachinePoolStringSetting()` at `:755`, so Windows does not /// write the pool to disk on every heartbeat from a peer it already knows. /// A new name is learned, the matrix is rebuilt from the pool so control is /// bidirectional straight away (`:758-772`), and only then is the caller /// asked to persist, reconnect and replicate. public func learn(from packet: Packet, now: TimeInterval) -> [SwitchAction] { guard let name = packet.machineName, !name.isEmpty else { return [] } if let known = pool.machine(named: name) { pool.updateID(name: known.name, id: packet.src, updateTimestamp: true, now: now) if let des = desMachineName, des.caseInsensitiveCompare(known.name) == .orderedSame { newDesMachineID = packet.src // MachineStuff.cs:731-735 setDesMachine(packet.src) } return [] // MachineStuff.cs:737 } guard pool.learn(name, keeping: matrix) else { return [] } // "The 5th machine" pool.updateID(name: name, id: packet.src, updateTimestamp: true, now: now) // Bidirectional control by default: the matrix becomes the pool, slot // for slot, with a machine that has no id leaving its slot empty // (MachineStuff.cs:758-772). var names = [String](repeating: "", count: Matrix.slotCount) for (slot, info) in pool.all.prefix(Matrix.slotCount).enumerated() where info.id != MachineID.none && info.id != MachineID.all { names[slot] = info.name } matrix = Matrix(names: names, oneRow: matrix.oneRow, wrap: matrix.wrap) return [.persistMachinePool, .persistMatrix, .reopenSockets] + MatrixPackets.encode(matrix).map { .send(stamped($0)) } } /// Applies one replicated `Matrix` packet (`UpdateMachineMatrix`, /// `MachineStuff.cs:978-1006`). The slot-4 packet commits the layout flags, /// so only it asks the caller to persist and reconnect. public func applyMatrix(_ packet: Packet) -> [SwitchAction] { MatrixPackets.apply(packet, to: &matrix) ? [.persistMatrix, .reopenSockets] : [] } /// Handles `ByeBye (4)`: if the machine leaving was the one being /// controlled, control comes home (`ProcessByeByeMessage`, `Common.cs:622-630`). public func handleByeBye(_ packet: Packet, now: TimeInterval) -> [SwitchAction] { var actions: [SwitchAction] = [] if packet.src == desMachineID { actions += switchToMachine(named: localName, now: now) } pool.setDisconnected(id: packet.src, now: now) return actions + [.persistMachinePool] } /// Handles `HideMouse (50)`: a peer took control, so park our cursor and let /// go of every modifier (`Receiver.cs:383-388`). public func handleHideMouse() -> [SwitchAction] { [.parkCursor(byHideMouseMessage: true), .releaseAllKeys] } /// A connection dropped: back-date the machine so it reads as dead, and take /// control back if it was the one driving (`MachineStuff.cs:675-694`, /// `SocketStuff.cs:1560-1563`). public func connectionLost(id: UInt32, now: TimeInterval) -> [SwitchAction] { pool.setDisconnected(id: id, now: now) connectedIDs.remove(id) var actions: [SwitchAction] = [.persistMachinePool] if id == desMachineID { actions += switchToMachine(named: localName, now: now) } return actions } /// Replaces the matrix after a local edit; the caller persists and /// replicates. public func setMatrix(_ new: Matrix) -> [SwitchAction] { matrix = new return [.persistMatrix] + MatrixPackets.encode(matrix).map { .send(stamped($0)) } } // MARK: - Helpers private func setDesMachine(_ id: UInt32) { desMachineID = id desMachineName = pool.name(for: id) // Common.cs:244-247 } /// A small addressed packet carrying our name, as `SendPackage` builds /// (`Common.cs:499-507`). private func packet(_ type: PackageType, to des: UInt32) -> Packet { var p = Packet(type: type) p.des = des try? p.setMachineName(localName) return stamped(p) } /// Stamps `Id` and `Src` the way `SkSend`/`TcpSend` do /// (`Common.cs:916`, `SocketStuff.cs:666-669`). private func stamped(_ packet: Packet) -> Packet { var p = packet p.id = sequencer.next() if p.src == MachineID.none { p.src = localID } return p } }