session-matrix: MachinePool, Matrix + Matrix packets, Coordinates, Edge, Switcher, Session

This commit is contained in:
lucio committed 2026-09-16 00:37:29 -07:00
1 parent 73de465986
commit 8d61347218
6 files changed
+1519

No files matched your search

+201
View File
@@ -0,0 +1,201 @@
// Turning pixels into the 0..65535 "universal" values the protocol carries, and
// back, plus the two magic biases that mark a relative move and a pixel move.
// See docs/protocol.md §4.4.
//
// Ported from App/Core/MachineStuff.cs ConvertToUniversalValue (181-190),
// App/Core/Event.cs (32-33, 105-113), App/Class/InputSimulation.cs SendMouse
// (160-173), App/Class/InputHook.cs (271-312), App/Core/Receiver.cs (147-153),
// App/Core/Common.cs SendNextMachine (516-539).
import Foundation
/// A point in protocol coordinates: 0..65535 across some rectangle both
/// machines have agreed on (docs/protocol.md §4.4).
public struct UniversalPoint: Sendable, Equatable {
/// Horizontal position, 0..65535.
public var x: Int32
/// Vertical position, 0..65535.
public var y: Int32
/// A universal point.
public init(x: Int32, y: Int32) {
self.x = x
self.y = y
}
}
/// Coordinate conversions and the biases that tag a packet's `Md.X`/`Md.Y`.
///
/// Every conversion is integer arithmetic, done in 64 bits and truncated, so it
/// matches C#'s `int` division exactly for any screen geometry while never
/// trapping the way 32-bit Swift arithmetic would.
public enum Coordinates {
/// The top of the universal range (`MachineStuff.cs:185-186`).
public static let universalMax: Int32 = 65535
/// Added to a delta to mark a packet as a *relative* move
/// (`MOVE_MOUSE_RELATIVE`, `Event.cs:32`).
public static let relativeBias: Int32 = 100_000
/// Added to a coordinate to mark it as *pixels, not universal*, on the
/// local switch path (`XY_BY_PIXEL`, `Event.cs:33`).
public static let pixelBias: Int32 = 300_000
// MARK: - Universal values
/// `p` expressed as 0..65535 across `rect`
/// (`ConvertToUniversalValue`, `MachineStuff.cs:181-190`).
///
/// Windows skips the conversion when the point is `Point.Empty`, i.e.
/// exactly (0, 0), because it uses that value as its "no switch" sentinel;
/// reproduced here so a jump landing on the origin carries the same bytes
/// (docs/protocol.md §10.2).
public static func toUniversal(_ p: CGPoint, in rect: CGRect) -> UniversalPoint {
let x = Int(p.x)
let y = Int(p.y)
if x == 0 && y == 0 { return UniversalPoint(x: 0, y: 0) }
let r = bounds(rect)
return UniversalPoint(
x: scale(x - r.left, span: r.right - r.left),
y: scale(y - r.top, span: r.bottom - r.top))
}
/// The inverse: a universal value placed back into `rect` in pixels
/// (`InputHook.cs:279-280`).
public static func fromUniversal(_ u: UniversalPoint, in rect: CGRect) -> CGPoint {
let r = bounds(rect)
return point(
unscale(Int(u.x), span: r.right - r.left) + r.left,
unscale(Int(u.y), span: r.bottom - r.top) + r.top)
}
/// What a `Mouse` packet carries for a plain move: the cursor scaled from
/// the sender's **primary** monitor (`Event.cs:112-113`).
///
/// The Windows divisor is `Common.screenWidth`/`screenHeight`, which are set
/// from the monitor whose origin is (0, 0) — the primary one
/// (`WinAPI.cs:70-80`), so `primary` is the same rectangle the offset comes
/// from.
public static func mouseMove(_ p: CGPoint, primary: CGRect) -> UniversalPoint {
let r = bounds(primary)
return UniversalPoint(
x: scale(Int(p.x) - r.left, span: r.right - r.left),
y: scale(Int(p.y) - r.top, span: r.bottom - r.top))
}
/// What the Windows receiver feeds to `SendInput` for an absolute move:
/// the universal value stretched from the sender's primary monitor onto the
/// receiver's whole desktop (`InputSimulation.cs:160-173`).
///
/// The result is still a universal value — `MOUSEEVENTF_ABSOLUTE` is 0..65535
/// over the primary monitor — so a macOS injector converts it to pixels with
/// `fromUniversal(_:in:)` over its own primary bounds.
public static func absoluteMove(_ u: UniversalPoint, desktop: CGRect, primary: CGRect)
-> UniversalPoint
{
let d = bounds(desktop)
let p = bounds(primary)
let w = scale(d.right - d.left, span: p.right - p.left)
let h = scale(d.bottom - d.top, span: p.bottom - p.top)
let l = scale(d.left, span: p.right - p.left)
let t = scale(d.top, span: p.bottom - p.top)
return UniversalPoint(
x: Int32(truncatingIfNeeded: (Int(u.x) * Int(w) / Int(universalMax)) + Int(l)),
y: Int32(truncatingIfNeeded: (Int(u.y) * Int(h) / Int(universalMax)) + Int(t)))
}
// MARK: - The two biases
/// A relative delta tagged for the wire: the bias is added away from zero so
/// the sign survives (`InputHook.cs:311-312`).
public static func tagRelative(dx: Int32, dy: Int32) -> UniversalPoint {
UniversalPoint(
x: dx &+ (dx < 0 ? -relativeBias : relativeBias),
y: dy &+ (dy < 0 ? -relativeBias : relativeBias))
}
/// Whether a `Mouse` packet carries a relative delta rather than a position
/// (`Receiver.cs:147`): **both** axes must be past the bias.
public static func isRelative(_ u: UniversalPoint) -> Bool {
abs(Int(u.x)) >= Int(relativeBias) && abs(Int(u.y)) >= Int(relativeBias)
}
/// The delta inside a relative packet (`Receiver.cs:151-153`).
public static func untagRelative(_ u: UniversalPoint) -> UniversalPoint {
UniversalPoint(
x: u.x < 0 ? u.x &+ relativeBias : u.x &- relativeBias,
y: u.y < 0 ? u.y &+ relativeBias : u.y &- relativeBias)
}
/// A pixel coordinate tagged for the *local* switch path
/// (`MachineStuff.cs:1021-1022`); never goes on the wire.
public static func tagPixels(_ p: CGPoint) -> UniversalPoint {
UniversalPoint(
x: pixelBias &+ Int32(truncatingIfNeeded: Int(p.x)),
y: pixelBias &+ Int32(truncatingIfNeeded: Int(p.y)))
}
/// Whether a switch location is tagged as pixels. Windows tests
/// `> XY_BY_PIXEL - 100000` rather than `>= XY_BY_PIXEL` so that a slightly
/// negative pixel coordinate still reads as tagged; 65535 is the largest
/// untagged value, so the two ranges cannot meet
/// (`Helper.cs:107`, `InputHook.cs:271`).
public static func isPixels(_ u: UniversalPoint) -> Bool {
u.x > pixelBias - relativeBias || u.y > pixelBias - relativeBias
}
/// The pixels inside a tagged switch location (`Helper.cs:109-110`).
public static func untagPixels(_ u: UniversalPoint) -> CGPoint {
point(Int(u.x &- pixelBias), Int(u.y &- pixelBias))
}
// MARK: - CGRect/CGPoint without CoreGraphics
// `MWBCore` may import Foundation only (README D2), which supplies the
// `CGRect`/`CGPoint` types but none of CoreGraphics' geometry members — no
// `minX`, no `zero`, no `Equatable`. These four are everything this target
// needs; nothing here extends a CG type, so `MWBMac` still sees the real
// CoreGraphics API unshadowed.
/// A point from whole pixels.
public static func point(_ x: Int, _ y: Int) -> CGPoint {
CGPoint(x: CGFloat(x), y: CGFloat(y))
}
/// A rectangle from the Windows `MyRectangle` edges (`right`/`bottom`
/// exclusive, as `Rectangle.Right` is).
public static func rect(left: Int, top: Int, right: Int, bottom: Int) -> CGRect {
CGRect(
origin: CGPoint(x: CGFloat(left), y: CGFloat(top)),
size: CGSize(width: CGFloat(right - left), height: CGFloat(bottom - top)))
}
/// The empty rectangle, for a machine that has not read its displays yet.
public static let emptyRect = rect(left: 0, top: 0, right: 0, bottom: 0)
/// The centre of a rectangle, rounded down as Windows' integer halving does
/// (`Common.cs:1476-1479`).
public static func centre(of rect: CGRect) -> CGPoint {
let r = bounds(rect)
return point(r.left + ((r.right - r.left) / 2), r.top + ((r.bottom - r.top) / 2))
}
// MARK: - Integer helpers
/// The four edges of a rectangle as whole pixels, in the Windows
/// convention: top-left origin, `right`/`bottom` exclusive.
public static func bounds(_ rect: CGRect) -> (left: Int, top: Int, right: Int, bottom: Int) {
let left = Int(rect.origin.x)
let top = Int(rect.origin.y)
return (left, top, left + Int(rect.size.width), top + Int(rect.size.height))
}
private static func scale(_ value: Int, span: Int) -> Int32 {
guard span != 0 else { return 0 }
return Int32(truncatingIfNeeded: value * Int(universalMax) / span)
}
private static func unscale(_ value: Int, span: Int) -> Int {
value * span / Int(universalMax)
}
}
+144
View File
@@ -0,0 +1,144 @@
// Whether the cursor just left the screen, which way, and where it should land
// on the machine it is going to. See docs/protocol.md §4.3-§4.4.
//
// Ported from App/Core/MachineStuff.cs MoveToMyNeighbourIfNeeded (203-283) and
// the landing-point arms of MoveRight/Left/Up/Down (385-421, 524-530, 593-599,
// 663-669), plus the monitor corners collected in App/Core/WinAPI.cs (104-109).
import Foundation
/// The rectangles and options edge detection needs, in Windows screen
/// coordinates: top-left origin, y down, whole pixels.
public struct EdgeConfig: Sendable {
/// The union of every monitor (`MachineStuff.desktopBounds`).
public var desktop: CGRect
/// The monitor whose origin is (0, 0) (`MachineStuff.primaryScreenBounds`).
public var primary: CGRect
/// Every monitor's four corners (`WinAPI.SensitivePoints`, `WinAPI.cs:104-109`).
public var corners: [CGPoint]
/// `BlockMouseAtScreenCorners`: suppress switching near a corner.
public var blockCorners: Bool
/// `MoveMouseRelatively`: the controlled machine reports its own deltas, so
/// landing points are computed against desktop bounds on both sides.
public var moveRelatively: Bool
/// An edge configuration.
public init(
desktop: CGRect = Coordinates.emptyRect, primary: CGRect = Coordinates.emptyRect,
corners: [CGPoint] = [], blockCorners: Bool = false, moveRelatively: Bool = false
) {
self.desktop = desktop
self.primary = primary
self.corners = corners
self.blockCorners = blockCorners
self.moveRelatively = moveRelatively
}
}
/// Edge detection: pure geometry, no matrix and no machines.
///
/// `crossing(...)` answers "did this cursor position leave the screen, and which
/// way"; `landing(...)` answers "where does the cursor appear on the machine we
/// are switching to". Which machine that is belongs to `Matrix`; putting the two
/// together is `Switcher`'s job.
public struct Edge: Sendable {
/// How close to an edge counts as leaving it (`SKIP_PIXELS`,
/// `MachineStuff.cs:33`).
public static let skipPixels = 1
/// How far inside the far edge the cursor reappears (`JUMP_PIXELS`,
/// `MachineStuff.cs:34`).
public static let jumpPixels = 2
/// How near a monitor corner blocks a switch when `blockCorners` is on
/// (`MachineStuff.cs:228`).
public static let cornerRadius = 100
/// The quiet period after a switch, 100 ms (`MachineStuff.cs:217`).
public static let jumpDebounce: TimeInterval = 0.1
/// The rectangles and options.
public var config: EdgeConfig
/// The last cursor position worth remembering, persisted by the app as the
/// `LastX`/`LastY` settings (`MachineStuff.cs:207-215`).
public private(set) var lastX: Int32 = 0
/// See `lastX`.
public private(set) var lastY: Int32 = 0
/// Edge detection over these rectangles.
public init(config: EdgeConfig) {
self.config = config
}
/// Which way the cursor left the screen, or `nil` for "stay put"
/// (`MoveToMyNeighbourIfNeeded`, `MachineStuff.cs:203-283`).
///
/// - `cursorIsLocal` is `desMachineID == MachineID`: the cursor is on this
/// machine, so it roams the whole desktop. Otherwise it is being scaled
/// from the controller's primary monitor and that is the rectangle to test.
/// - `broadcasting` is ALL mode, in which switching is off.
/// - `lastJump` is when the last switch happened, in the caller's time base.
public mutating func crossing(
at point: CGPoint, cursorIsLocal: Bool, broadcasting: Bool, lastJump: TimeInterval,
now: TimeInterval
) -> Direction? {
let x = Int(point.x)
let y = Int(point.y)
if abs(x) > 10 { lastX = Int32(truncatingIfNeeded: x) } // MachineStuff.cs:207-210
if abs(y) > 10 { lastY = Int32(truncatingIfNeeded: y) } // MachineStuff.cs:212-215
guard now - lastJump >= Edge.jumpDebounce, !broadcasting else { return nil }
if config.blockCorners && isNearCorner(x: x, y: y) { return nil }
let r = Coordinates.bounds(cursorIsLocal ? config.desktop : config.primary)
if x < r.left + Edge.skipPixels { return .left }
if x >= r.right - Edge.skipPixels { return .right }
if y < r.top + Edge.skipPixels { return .up }
if y >= r.bottom - Edge.skipPixels { return .down }
return nil
}
/// Where the cursor lands on the machine being switched to, as a universal
/// value (`MachineStuff.cs:385-421` and the identical arms in the other
/// three `Move*` methods).
///
/// The rectangle is chosen by `landingRect`; the cursor arrives
/// `jumpPixels` inside the **opposite** edge, keeping the other axis where
/// it was.
public func landing(
direction: Direction, from point: CGPoint, targetIsLocal: Bool, cursorIsLocal: Bool
) -> UniversalPoint {
let rect = landingRect(targetIsLocal: targetIsLocal, cursorIsLocal: cursorIsLocal)
let r = Coordinates.bounds(rect)
let jump = Edge.jumpPixels
let landed: CGPoint
switch direction {
case .right: landed = Coordinates.point(r.left + jump, Int(point.y))
case .left: landed = Coordinates.point(r.right - jump, Int(point.y))
case .up: landed = Coordinates.point(Int(point.x), r.bottom - jump)
case .down: landed = Coordinates.point(Int(point.x), r.top + jump)
}
return Coordinates.toUniversal(landed, in: rect)
}
/// The four-case rule of docs/protocol.md §4.4 (`MachineStuff.cs:385-421`).
///
/// In relative mode both machines work in desktop bounds. Otherwise the
/// cursor is bounded by the controller's primary monitor whenever the
/// controller is not the one holding it, so only the "switching away from
/// the controller" case gets to use desktop bounds.
func landingRect(targetIsLocal: Bool, cursorIsLocal: Bool) -> CGRect {
if config.moveRelatively { return config.desktop } // MachineStuff.cs:417-420
if targetIsLocal { return config.primary } // MachineStuff.cs:387-392
return cursorIsLocal ? config.desktop : config.primary // MachineStuff.cs:396-411
}
/// `BlockMouseAtCorners`: within 100 px of any monitor corner, on both axes
/// (`MachineStuff.cs:222-234`).
private func isNearCorner(x: Int, y: Int) -> Bool {
config.corners.contains { corner in
abs(Int(corner.x) - x) < Edge.cornerRadius && abs(Int(corner.y) - y) < Edge.cornerRadius
}
}
}
+208
View File
@@ -0,0 +1,208 @@
// The set of machines this one knows about: name, id and when each was last
// heard from, in the persisted `Name:Id,…` form. See docs/protocol.md §4.1.
//
// Ported from App/Class/MachinePool.cs, App/Class/MachinePoolHelpers.cs and
// App/Core/MachineStuff.cs AddToMachinePool (712-777).
import Foundation
/// One machine in the pool (`MachineInf`, `MachineInf.cs`).
public struct MachineInfo: Sendable, Equatable {
/// The machine's name, as it appears in a packet's `MachineName` field.
public var name: String
/// Its id, or `MachineID.none` while unknown.
public var id: UInt32
/// When it was last heard from, in the caller's time base (seconds).
public var lastSeen: TimeInterval
/// A pool entry.
public init(name: String, id: UInt32 = MachineID.none, lastSeen: TimeInterval = 0) {
self.name = name
self.id = id
self.lastSeen = lastSeen
}
}
/// Up to four machines, keyed by name, with best-effort updates.
///
/// A value type: the Windows class is a locked list because every thread
/// touches one global (`MachinePool.cs:40-49`); here the app owns one copy on
/// the queue that owns the sessions. Every mutation is "try to", as on Windows:
/// a full pool simply refuses to learn a fifth machine.
public struct MachinePool: Sendable, Equatable {
/// The most machines a matrix can hold (`MAX_MACHINE`, `MachineStuff.cs:30`).
public static let maxMachines = 4
/// How long a machine stays alive without a heartbeat: 1 500 000 ms
/// (`HEARTBEAT_TIMEOUT`, `MachineStuff.cs:32` — 25 minutes, despite the
/// comment there saying 30).
public static let heartbeatTimeout: TimeInterval = 1500
private var machines: [MachineInfo]
/// An empty pool.
public init() {
machines = []
}
/// The pool as persisted in the `MachinePool` setting.
///
/// `MachinePoolHelpers.cs:16-43`: comma-separated `Name:Id` fields, at least
/// four of them. A field that is not exactly `Name:Id` is skipped; an
/// unparsable id reads as `ID.NONE` and back-dates the entry past the
/// heartbeat timeout so it starts out dead. A string with fewer than four
/// fields throws on Windows and is caught into an empty pool
/// (`InitAndCleanup.cs:47-64`), which is what an empty pool here means.
public init(string: String, now: TimeInterval) {
machines = []
let fields = string.components(separatedBy: ",")
guard fields.count >= MachinePool.maxMachines else { return }
for field in fields.prefix(MachinePool.maxMachines) {
let parts = field.components(separatedBy: ":")
guard parts.count == 2 else { continue }
let name = parts[0].trimmingCharacters(in: .whitespaces) // InitAndCleanup.cs:53
guard !name.isEmpty else { continue } // MachinePool.cs:178-181
let id = UInt32(parts[1]) ?? MachineID.none
let seen = id == MachineID.none ? now - MachinePool.heartbeatTimeout : now
machines.append(MachineInfo(name: name, id: id, lastSeen: seen))
}
}
/// The `Name:Id,…` string for the `MachinePool` setting
/// (`MachinePool.cs:287-301`), padded with empty `:` fields to four.
public var string: String {
var text = machines.map { "\($0.name):\($0.id)" }.joined(separator: ",")
for _ in machines.count..<MachinePool.maxMachines {
text += ",:"
}
return text
}
/// Every machine, in insertion order (`ListAllMachines`, `MachinePool.cs:130`).
public var all: [MachineInfo] { machines }
/// The machine with this name, compared case-insensitively as Windows does
/// (`NamesAreEqual`, `MachinePool.cs:309-312`).
public func machine(named name: String) -> MachineInfo? {
machines.first { MachinePool.namesAreEqual($0.name, name) }
}
/// This machine's id, or `nil` when it is unknown (`ID.NONE` on Windows,
/// `ResolveID`, `MachinePool.cs:264-267`).
public func resolveID(name: String) -> UInt32? {
guard let found = machine(named: name), found.id != MachineID.none else { return nil }
return found.id
}
/// The first machine holding this id, as `NameFromID` does
/// (`MachineStuff.cs:1085-1096`); `nil` for `MachineID.none`.
public func name(for id: UInt32) -> String? {
guard id != MachineID.none else { return nil }
return machines.first { $0.id == id }?.name
}
/// Adds a machine, initially disconnected (`LearnMachine`,
/// `MachinePool.cs:195-243`). `false` if it is already known, if the name is
/// blank, or if the pool is full of machines the matrix still wants.
///
/// When the pool is full, the first machine that is *not* in `matrix` is
/// evicted to make room — that is the only thing the matrix is consulted
/// for here (`MachinePool.cs:217-238`, `MachineStuff.InMachineMatrix`).
public mutating func learn(_ name: String, keeping matrix: Matrix) -> Bool {
let trimmed = name.trimmingCharacters(in: .whitespaces)
guard !trimmed.isEmpty else { return false }
guard machine(named: name) == nil else { return false }
if machines.count >= MachinePool.maxMachines {
guard let slot = machines.firstIndex(where: { !matrix.contains($0.name) }) else {
return false
}
machines.remove(at: slot)
}
machines.append(MachineInfo(name: name))
return true
}
/// Points a known name at an id, and clears that id from any other machine
/// that was holding it (`TryUpdateMachineID`, `MachinePool.cs:52-89`).
///
/// `false` when no machine has that name. `updateTimestamp` marks the
/// machine alive; the duplicate-id reset uses the same flag, as Windows does.
@discardableResult
public mutating func updateID(
name: String, id: UInt32, updateTimestamp: Bool, now: TimeInterval
) -> Bool {
var updated = false
for i in machines.indices {
if MachinePool.namesAreEqual(name, machines[i].name) {
machines[i].id = id
if updateTimestamp { machines[i].lastSeen = now }
updated = true
} else if machines[i].id == id {
// Duplicate id? Reset the old machine's (MachinePool.cs:75-84).
machines[i].id = MachineID.none
if updateTimestamp { machines[i].lastSeen = now }
}
}
return updated
}
/// Back-dates a machine's timestamp so it reads as dead after a socket
/// error (`SetMachineDisconnected`, `MachinePool.cs:101-127`).
///
/// Returns whether it was already past the timeout, which is the Windows
/// signal that control should come back to the local machine.
@discardableResult
public mutating func setDisconnected(name: String, now: TimeInterval) -> Bool {
let floor = now - MachinePool.heartbeatTimeout + 10 // 10 000 ms, MachinePool.cs:118
var foundAndTimedOut = false
for i in machines.indices where MachinePool.namesAreEqual(name, machines[i].name) {
machines[i].lastSeen = min(machines[i].lastSeen, floor)
foundAndTimedOut = machines[i].lastSeen < floor - 5 // 5 000 ms, MachinePool.cs:121
}
return foundAndTimedOut
}
/// Back-dates every machine holding this id, used when a connection drops
/// (`RemoveDeadMachines(ID)`, `MachineStuff.cs:675-694`).
@discardableResult
public mutating func setDisconnected(id: UInt32, now: TimeInterval) -> Bool {
var changed = false
for info in machines where info.id == id {
if setDisconnected(name: info.name, now: now) { changed = true }
}
return changed
}
/// Whether a machine counts as alive: it has an id, and either its last
/// heartbeat is inside the timeout or a socket to it is up
/// (`IsAlive`, `MachinePool.cs:304-307`).
public func isAlive(_ info: MachineInfo, now: TimeInterval, connectedIDs: Set<UInt32>) -> Bool {
guard info.id != MachineID.none else { return false }
return now - info.lastSeen <= MachinePool.heartbeatTimeout || connectedIDs.contains(info.id)
}
/// Clears the id of every machine that the matrix no longer lists or that
/// has gone quiet, leaving the local machine alone
/// (`ResetIPAddressesForDeadMachines`, `MachinePool.cs:320-343`).
public mutating func resetDeadMachineIDs(
localName: String, matrix: Matrix, now: TimeInterval, connectedIDs: Set<UInt32>,
firstLoaded: Bool
) {
for i in machines.indices {
let info = machines[i]
if !info.name.isEmpty && info.name == localName { continue } // MachinePool.cs:326
let inMatrix = matrix.contains(info.name)
let drop =
firstLoaded
? !inMatrix
: !inMatrix || !isAlive(info, now: now, connectedIDs: connectedIDs)
if drop { machines[i].id = MachineID.none }
}
}
private static func namesAreEqual(_ a: String, _ b: String) -> Bool {
a.caseInsensitiveCompare(b) == .orderedSame
}
}
+242
View File
@@ -0,0 +1,242 @@
// The four-slot machine matrix: its persisted string form, the live view that
// blanks disconnected machines, the neighbour search that decides which machine
// is to the left/right/up/down, and the four `Matrix` packets that replicate it.
// See docs/protocol.md §4.1-§4.2.
//
// Ported from App/Core/MachineStuff.cs: MachineMatrix (883-933),
// LiveMachineMatrix (935-945), MoveRight/Left/Up/Down (288-673),
// SendMachineMatrix (952-976), UpdateMachineMatrix (978-1006).
import Foundation
/// Which way the cursor left the screen.
public enum Direction: Sendable, Equatable {
/// Towards the previous slot in the row.
case left
/// Towards the next slot in the row.
case right
/// Towards the row above; two-row layouts only.
case up
/// Towards the row below; two-row layouts only.
case down
}
/// Four machine names in layout order, plus the two flags that say how they are
/// arranged.
///
/// One row is `[0][1][2][3]` (`MatrixOneRow`, the default); two rows are
/// `[0][1]` over `[2][3]`. `wrap` is the Windows `MatrixCircle` setting (the
/// `WrapMouse` property), which lets the last slot lead back to the first.
public struct Matrix: Sendable, Equatable {
/// Slots in the matrix (`MAX_MACHINE`, `MachineStuff.cs:30`).
public static let slotCount = MachinePool.maxMachines
/// The four slot names; empty means an unused slot.
public private(set) var names: [String]
/// `MatrixOneRow`: all four machines side by side.
public var oneRow: Bool
/// `MatrixCircle` (the `WrapMouse` setting): the edges wrap around.
public var wrap: Bool
/// A matrix from four names; short or long arrays are padded or truncated
/// to exactly four slots, as `MachineMatrix` insists on
/// (`MachineStuff.cs:897-905`).
public init(names: [String] = [], oneRow: Bool = true, wrap: Bool = true) {
var slots = Array(names.prefix(Matrix.slotCount))
slots.append(contentsOf: [String](repeating: "", count: Matrix.slotCount - slots.count))
self.names = slots
self.oneRow = oneRow
self.wrap = wrap
}
/// A matrix from the persisted `MachineMatrixString` setting: names joined
/// by commas (`MachineStuff.cs:891-905, 923`). Anything that does not split
/// into exactly four fields becomes four empty slots, as on Windows.
public init(string: String, oneRow: Bool = true, wrap: Bool = true) {
let fields = string.components(separatedBy: ",")
let slots = fields.count == Matrix.slotCount ? fields : []
self.init(names: slots, oneRow: oneRow, wrap: wrap)
}
/// The `MachineMatrixString` setting value (`MachineStuff.cs:923`).
public var string: String { names.joined(separator: ",") }
/// Replaces one slot, ignoring an index outside 0..3
/// (`MachineStuff.cs:983-987`).
public mutating func setName(_ name: String, at slot: Int) {
guard names.indices.contains(slot) else { return }
names[slot] = name
}
/// The slot holding this name, compared case-insensitively on trimmed names
/// as every `Move*` does (`MachineStuff.cs:310`).
public func slot(of name: String) -> Int? {
names.firstIndex { Matrix.namesMatch($0, name) }
}
/// Whether the matrix lists this name (`InMachineMatrix`,
/// `MachineStuff.cs:1098-1114`).
public func contains(_ name: String) -> Bool {
let wanted = name.trimmingCharacters(in: .whitespaces)
guard !wanted.isEmpty else { return false }
return names.contains {
!$0.trimmingCharacters(in: .whitespaces).isEmpty && Matrix.namesMatch($0, wanted)
}
}
/// The matrix as the neighbour search sees it: in one-row mode a slot whose
/// machine has no live connection is blanked, in two-row mode nothing is
/// (`LiveMachineMatrix`, `MachineStuff.cs:935-945`).
///
/// `connectedNames` must include the local machine: the Windows test is
/// `IsConnectedTo`, which answers yes for this machine's own id without
/// looking at any socket (`Common.cs:852-855`). `Switcher` adds it.
public func live(connectedNames: Set<String>) -> [String] {
guard oneRow else { return names }
return names.map { name in
connectedNames.contains(where: { Matrix.namesMatch($0, name) }) ? name : ""
}
}
/// The machine one step `direction` from `current`, or `nil` when there is
/// none — which is the Windows "stay put" answer.
///
/// `live` is the array from `live(connectedNames:)`; `isReachable` is the
/// `IdFromName(name) != ID.NONE` test the Windows code applies to every
/// candidate slot (`MachineStuff.cs:316, 456`), so a named but unresolved
/// machine is stepped over.
public func neighbour(
of current: String, direction: Direction, live: [String],
isReachable: (String) -> Bool
) -> String? {
guard live.count == Matrix.slotCount else { return nil }
switch direction {
case .right:
return oneRow
? rowStep(current, live, isReachable, forward: true)
: chain(current, live, isReachable, [(0, 1), (2, 3)], wrapArms: [(1, 0), (3, 2)])
case .left:
return oneRow
? rowStep(current, live, isReachable, forward: false)
: chain(current, live, isReachable, [(1, 0), (3, 2)], wrapArms: [(0, 1), (2, 3)])
case .up:
// MoveUp (MachineStuff.cs:536-603); one-row matrices return early (:538-541).
return oneRow
? nil : chain(current, live, isReachable, [(2, 0), (3, 1)], wrapArms: [(0, 2), (1, 3)])
case .down:
return oneRow ? nil : moveDown(current, live, isReachable)
}
}
// MARK: - One row
/// `MoveRight`/`MoveLeft` in one-row mode (`MachineStuff.cs:306-343, 445-483`):
/// scan outwards from the current slot, then wrap around the other side.
/// `MoveRight` scans slots ascending for the current machine and `MoveLeft`
/// descending, which only differs when a name appears twice.
private func rowStep(
_ current: String, _ live: [String], _ isReachable: (String) -> Bool, forward: Bool
) -> String? {
let order = forward ? Array(live.indices) : Array(live.indices.reversed())
guard let i = order.first(where: { Matrix.namesMatch(live[$0], current) }) else { return nil }
let onwards = forward ? Array((i + 1)..<live.count) : Array((0..<i).reversed())
if let hit = onwards.first(where: { pick(live[$0], isReachable) }) { return live[hit] }
guard wrap else { return nil }
let around = forward ? Array(0..<i) : Array(((i + 1)..<live.count).reversed())
return around.first(where: { pick(live[$0], isReachable) }).map { live[$0] }
}
// MARK: - Two rows
/// The two-row `Move*` if-chains (`MachineStuff.cs:346-378, 486-517, 556-587`).
///
/// Each arm is `(from, to)`: "if the current machine is in slot `from` and
/// slot `to` is not empty, go there". Windows writes them as one `else if`
/// chain, so the **first** arm whose slot and non-empty target match wins
/// and the rest are never examined — even if that target turns out to have
/// no id, which is why `isReachable` is applied after the arm is chosen and
/// not as part of choosing it. The wrap arms are appended only when
/// `MatrixCircle` is on.
private func chain(
_ current: String, _ live: [String], _ isReachable: (String) -> Bool,
_ arms: [(Int, Int)], wrapArms: [(Int, Int)]
) -> String? {
let all = wrap ? arms + wrapArms : arms
guard
let arm = all.first(where: {
Matrix.namesMatch(live[$0.0], current) && !live[$0.1].isEmpty
})
else { return nil }
return isReachable(live[arm.1]) ? live[arm.1] : nil
}
/// `MoveDown` (`MachineStuff.cs:605-673`). Windows writes this one as *two*
/// separate if-chains rather than one, so a wrap arm can overwrite the
/// answer a straight arm already gave. That only differs when one name
/// occupies two slots; it is reproduced here — see docs/protocol.md §10.2.
private func moveDown(
_ current: String, _ live: [String], _ isReachable: (String) -> Bool
) -> String? {
let straight = chain(current, live, isReachable, [(0, 2), (1, 3)], wrapArms: [])
guard wrap else { return straight }
let wrapped = chain(current, live, isReachable, [(2, 0), (3, 1)], wrapArms: [])
return wrapped ?? straight
}
private func pick(_ name: String, _ isReachable: (String) -> Bool) -> Bool {
!name.isEmpty && isReachable(name)
}
private static func namesMatch(_ a: String, _ b: String) -> Bool {
a.trimmingCharacters(in: .whitespaces)
.caseInsensitiveCompare(b.trimmingCharacters(in: .whitespaces)) == .orderedSame
}
}
/// The four `Matrix` packets that replicate a matrix to every peer.
///
/// One packet per slot, `Src` a 1-based slot index and `Des` broadcast; the
/// layout flags ride in the type byte and are only committed by the receiver
/// when slot 4 arrives (docs/protocol.md §4.2).
public enum MatrixPackets {
/// The four packets for `matrix`, in slot order
/// (`SendMachineMatrix`, `MachineStuff.cs:952-976`).
///
/// A name longer than 32 bytes or outside ASCII is dropped from its slot
/// rather than failing the whole send: such a machine could never be
/// resolved by a peer anyway (README D7).
public static func encode(_ matrix: Matrix) -> [Packet] {
var typeByte = PackageType.matrixBit
if matrix.wrap { typeByte |= PackageType.matrixSwapFlag } // MachineStuff.cs:966
if !matrix.oneRow { typeByte |= PackageType.matrixTwoRowFlag } // MachineStuff.cs:967
return matrix.names.enumerated().map { slot, name in
var packet = Packet(type: PackageType(rawValue: typeByte))
try? packet.setMachineName(name)
packet.src = UInt32(slot + 1) // MachineStuff.cs:969
packet.des = MachineID.all
return packet
}
}
/// Applies one received `Matrix` packet to `matrix`
/// (`UpdateMachineMatrix`, `MachineStuff.cs:978-1006`).
///
/// Returns `true` on the slot-4 packet, which is where Windows commits the
/// layout flags and reopens its client sockets — the caller's cue to
/// persist the matrix and reconnect. A `Src` outside 1...4 is ignored.
@discardableResult
public static func apply(_ packet: Packet, to matrix: inout Matrix) -> Bool {
let slot = packet.src
guard slot > 0, slot <= UInt32(Matrix.slotCount) else { return false }
matrix.setName(packet.machineName ?? "", at: Int(slot) - 1)
guard slot == UInt32(Matrix.slotCount) else { return false }
let raw = packet.type.rawValue
matrix.wrap = (raw & PackageType.matrixSwapFlag) != 0 // MachineStuff.cs:991
matrix.oneRow = (raw & PackageType.matrixTwoRowFlag) == 0 // MachineStuff.cs:992
return true
}
}
+377
View File
@@ -0,0 +1,377 @@
// One TCP control connection's protocol state: the handshake that decides
// whether the peer knows the security key, the trust gate that keeps everything
// else out until it does, packet reassembly, replay rejection and heartbeats.
// See docs/protocol.md §1.4, §3.2-§3.3.
//
// Ported from App/Class/SocketStuff.cs MainTCPRoutine (1261-1565) and
// TcpReceiveData (557-610), App/Core/Receiver.cs PreProcess (40-82),
// App/Core/Common.cs SendPackage/SendHeartBeat (499-513), SendAwakeBeat
// (545-558), SendByeBye (612-616) and TestSend (822-847),
// App/Form/frmScreen.cs the 100 ms timer (285-288, 555-575).
import Foundation
/// How a connection is doing, in the Windows numbering so the menu-bar colours
/// can stay the same (`SocketStatus`, `SocketStuff.cs:54-66`).
public enum SocketStatus: Int, Sendable {
/// Not in use.
case na = 0
/// Looking the peer's name up.
case resolving
/// TCP connect in progress.
case connecting
/// Connected, exchanging handshakes.
case handshaking
/// Read or write failed.
case error
/// Closed by us.
case forceClosed
/// The peer does not share our security key.
case invalidKey
/// The peer stopped answering.
case timeout
/// A write failed.
case sendError
/// Trusted and carrying traffic.
case connected
}
/// Why a session gave up on a peer's key.
public enum InvalidKeyReason: Sendable, Equatable {
/// More than ten packets arrived before the handshake completed
/// (`SocketStuff.cs:1387-1406`).
case tooManyUntrustedPackets
/// The `HandshakeAck` nonce was not the complement we sent
/// (`SocketStuff.cs:1409-1410`).
case handshakeAckMismatch
}
/// What a session tells its owner.
public enum SessionEvent: Sendable, Equatable {
/// The connection's status changed; drive the UI from this.
case status(SocketStatus)
/// The handshake completed and the peer is trusted.
case connected(peerName: String, peerID: UInt32)
/// A trusted, non-duplicate application packet. Nothing is delivered here
/// before the handshake (CLAUDE.md invariant 2).
case packet(Packet)
/// The peer failed the key check.
case invalidKey(InvalidKeyReason)
/// The peer is us — Windows closes such a socket (`SocketStuff.cs:1430-1437`).
case selfConnection
/// Close the socket now. Always the last event of a session.
case close
}
/// Everything a session needs to know about the machine it runs on.
public struct SessionConfig: Sendable {
/// This machine's name, sent in every handshake.
public var localName: String
/// This machine's id (`MachineID` setting).
public var localID: UInt32
/// The magic number derived from the security key (`MagicHash`).
public var magic: UInt32
/// `BlockScreenSaverOnOtherMachines`, which sets the heartbeat cadence.
public var blockScreenSaver: Bool
/// The peer's name from DNS, if the caller resolved one; the `HandshakeAck`
/// name overrides it (`SocketStuff.cs:1412-1419`).
public var peerNameHint: String?
/// A session configuration.
public init(
localName: String, localID: UInt32, magic: UInt32, blockScreenSaver: Bool = true,
peerNameHint: String? = nil
) {
self.localName = localName
self.localID = localID
self.magic = magic
self.blockScreenSaver = blockScreenSaver
self.peerNameHint = peerNameHint
}
}
/// One connection's protocol logic, with no socket, timer or thread of its own.
///
/// The owner feeds it decrypted bytes, drains framed bytes to write back,
/// collects events and calls `tick` from its own timer. Not `Sendable`: one
/// connection owns one session, on one queue, alongside its `CipherWriter` and
/// `CipherReader`.
public final class Session {
/// Heartbeat every 60 s when the screen saver is being blocked
/// (`frmScreen.cs:565-570`: `count % 600` at 100 ms per tick).
public static let fastHeartbeat: TimeInterval = 60
/// Heartbeat every 300 s otherwise (`count % 3000`, `frmScreen.cs:568`).
public static let slowHeartbeat: TimeInterval = 300
/// Untrusted packets tolerated before the key is declared wrong
/// (`SocketStuff.cs:1390`).
public static let untrustedPacketLimit = 10
private let config: SessionConfig
private let sequencer: PacketSequencer
private let replay: ReplayFilter
private let isClient: Bool
private var inbox = Data()
private var outbox: [Data] = []
private var pending: [SessionEvent] = []
/// -1 once the peer is trusted, as `packageCount` is on Windows
/// (`SocketStuff.cs:1441`).
private var untrustedCount = 0
private var expectedNonce: (UInt32, UInt32, UInt32, UInt32) = (0, 0, 0, 0)
private var receiveErrors = 0
private var nextHeartbeat: TimeInterval = .greatestFiniteMagnitude
private var finished = false
/// The connection's status.
public private(set) var status: SocketStatus = .na
/// The peer's name, known once the handshake completes.
public private(set) var peerName: String?
/// The peer's machine id, taken from the `HandshakeAck`'s `Src`.
public private(set) var peerID: UInt32?
/// A session for one connection. `isClient` is whether we dialled out; it
/// changes nothing here but is what the network layer needs to decide which
/// of a pair's two connections to keep (`SocketStuff.cs:1980-2004`).
public init(
config: SessionConfig, sequencer: PacketSequencer, replay: ReplayFilter, isClient: Bool
) {
self.config = config
self.sequencer = sequencer
self.replay = replay
self.isClient = isClient
peerName = config.peerNameHint
}
/// Whether we dialled this connection out.
public var isOutbound: Bool { isClient }
// MARK: - Driving the session
/// Queues the opening handshake: ten identical `Handshake` packets, then
/// remembers the complement of their nonce as the ack we expect
/// (`SocketStuff.cs:1269-1299`).
///
/// The whole 64-byte packet starts as cryptographic randomness, so `Id`,
/// `Src` and `Des` are random too — only the type and the machine name are
/// set (`:1269-1289`).
public func start(now: TimeInterval) {
var handshake = Session.randomPacket()
try? handshake.setMachineName(config.localName)
handshake.type = .handshake
for _ in 0..<10 { sendDirect(handshake) }
let n = handshake.nonce
expectedNonce = (~n.0, ~n.1, ~n.2, ~n.3) // SocketStuff.cs:1296-1299
nextHeartbeat = now + heartbeatInterval
report(.handshaking)
}
/// Feeds decrypted socket bytes in. Handles the 32-then-32 rule itself: a
/// packet whose framing failed still occupies 64 bytes when its type byte
/// has the `Matrix` bit, which `.invalid` does (docs/protocol.md §10.1).
public func feed(_ plaintext: Data) {
inbox.append(plaintext)
while !finished {
guard inbox.count >= packageSize else { return }
let head = Framing.open(inbox.prefix(packageSize), magic: config.magic)
let size = head.type.packetSize
guard inbox.count >= size else { return }
// Re-open the whole 64 bytes for a big packet: the checksum covers
// bytes 2..31 either way, so this is what Windows does when it sets
// `package.Bytes = buf` (SocketStuff.cs:585-598).
let packet = size == packageSize ? head : Framing.open(inbox.prefix(size), magic: config.magic)
inbox.removeFirst(size)
receiveErrors = 0 // SocketStuff.cs:1364
handle(packet)
}
}
/// A read that returned nothing or a short packet — `PackageType.Error` on
/// Windows. Six in a row close the connection (`SocketStuff.cs:1326-1361`).
public func noteReceiveError() {
receiveErrors += 1
guard receiveErrors > 5 else { return }
report(.error)
close()
}
/// Reports a status the network layer knows and the session cannot see, such
/// as `.resolving` or `.sendError`.
public func report(_ new: SocketStatus) {
guard status != new else { return }
status = new
pending.append(.status(new))
}
/// Heartbeats. `userActive` is whether real input happened since the last
/// tick, which is what turns a `Heartbeat` into an `Awake`
/// (`Common.cs:545-552`).
public func tick(now: TimeInterval, userActive: Bool) {
guard status == .connected, !finished, now >= nextHeartbeat else { return }
nextHeartbeat = now + heartbeatInterval
let type: PackageType = config.blockScreenSaver && userActive ? .awake : .heartbeat
send(broadcast(type))
}
/// Queues a packet, stamping `Id` and `Src` as `SkSend` does
/// (`Common.cs:916`, `SocketStuff.cs:666-669`). Use this for anything the
/// app originates.
public func send(_ packet: Packet) {
var p = packet
p.id = sequencer.next()
sendDirect(p)
}
/// The liveness probe Windows writes before trusting a socket's "connected"
/// state (`Hi`, `TestSend`, `Common.cs:822-847`). Not sequenced, like every
/// `TcpSend`-only packet.
public func probe() {
guard let id = peerID else { return }
var p = Packet(type: .hi)
p.des = id
try? p.setMachineName(config.localName)
sendDirect(p)
}
/// Queues `ByeBye (4)` on the way out (`Common.cs:612-616`).
public func sayGoodbye() {
send(broadcast(.byeBye))
}
/// Framed bytes to write through `CipherWriter`, in order. Drains the queue.
public func drain() -> [Data] {
defer { outbox.removeAll() }
return outbox
}
/// Everything that happened since the last call. Drains the queue.
public func events() -> [SessionEvent] {
defer { pending.removeAll() }
return pending
}
// MARK: - Receiving
private func handle(_ packet: Packet) {
// A Handshake is answered whatever the trust state, and never counts
// against the untrusted budget (SocketStuff.cs:1367-1384).
if packet.type == .handshake {
var ack = packet
ack.type = .handshakeAck
ack.src = MachineID.none // refilled with our id by sendDirect
try? ack.setMachineName(config.localName)
let n = packet.nonce
ack.nonce = (~n.0, ~n.1, ~n.2, ~n.3)
sendDirect(ack)
return
}
guard untrustedCount >= 0 else {
// Trusted. Duplicate acks from the peer's ten handshakes are
// ignored rather than processed (SocketStuff.cs:1524-1527).
if packet.type != .handshakeAck { deliver(packet) }
return
}
countUntrusted(packet)
}
/// The untrusted branch of `MainTCPRoutine` (`SocketStuff.cs:1386-1500`).
private func countUntrusted(_ packet: Packet) {
untrustedCount += 1
if untrustedCount >= Session.untrustedPacketLimit {
var reject = packet
reject.type = .invalid
for _ in 0..<10 { sendDirect(reject) } // SocketStuff.cs:1394-1397
report(.invalidKey)
pending.append(.invalidKey(.tooManyUntrustedPackets))
close()
return
}
switch packet.type {
case .handshakeAck:
acceptAck(packet)
case .mouse, .heartbeat, .heartbeatEx:
// Traffic from a peer mid-handshake is expected; give the budget
// back rather than spending it (SocketStuff.cs:1502-1515).
if untrustedCount > 5 { untrustedCount -= 1 }
default:
if untrustedCount > 5 { report(.invalidKey) } // SocketStuff.cs:1519-1521
}
}
/// The nonce check that makes a peer trusted (`SocketStuff.cs:1407-1480`).
private func acceptAck(_ packet: Packet) {
guard packet.nonce == expectedNonce else {
report(.invalidKey)
pending.append(.invalidKey(.handshakeAckMismatch))
close()
return
}
let claimed = packet.machineName ?? ""
let name = claimed.isEmpty ? (peerName ?? "") : claimed
if name.caseInsensitiveCompare(config.localName) == .orderedSame {
report(.na) // SocketStuff.cs:1433
pending.append(.selfConnection)
close()
return
}
untrustedCount = -1 // Trusted (SocketStuff.cs:1441)
peerName = name
peerID = packet.src
report(.connected)
pending.append(.connected(peerName: name, peerID: packet.src))
send(broadcast(.heartbeat)) // SendHeartBeat(initial: true), SocketStuff.cs:1451
}
/// `Receiver.PreProcess` (`Receiver.cs:40-82`): drop what framing rejected,
/// drop the type byte Windows treats as unknown, drop replays.
private func deliver(_ packet: Packet) {
if packet.type == .invalid { return }
if packet.type.rawValue == 0 { return }
if replay.isDuplicate(packet) { return }
pending.append(.packet(packet))
}
// MARK: - Sending
/// Writes a packet without touching `Id`, which is what `TcpSend` does:
/// only `SkSend` sequences (`SocketStuff.cs:663-678`).
private func sendDirect(_ packet: Packet) {
guard !finished else { return }
var p = packet
if p.src == MachineID.none { p.src = config.localID } // SocketStuff.cs:666-669
outbox.append(Framing.seal(p, magic: config.magic))
}
/// A broadcast packet carrying our machine name (`SendPackage`,
/// `Common.cs:499-507`).
private func broadcast(_ type: PackageType) -> Packet {
var p = Packet(type: type)
p.des = MachineID.all
try? p.setMachineName(config.localName)
return p
}
private var heartbeatInterval: TimeInterval {
config.blockScreenSaver ? Session.fastHeartbeat : Session.slowHeartbeat
}
private func close() {
guard !finished else { return }
finished = true
pending.append(.close)
}
/// 64 cryptographically random bytes as a packet (`SocketStuff.cs:1269-1270`).
private static func randomPacket() -> Packet {
var rng = SystemRandomNumberGenerator()
let bytes = (0..<packageSizeEx).map { _ in UInt8.random(in: .min ... .max, using: &rng) }
return Packet(bytes: Data(bytes)) ?? Packet(type: .handshake)
}
}
+347
View File
@@ -0,0 +1,347 @@
// 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<UInt32> = []
/// Names with a live connection, for `LiveMachineMatrix`
/// (`MachineStuff.cs:940`).
public var connectedNames: Set<String> = []
/// 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))
p.id = sequencer.next()
p.src = localID
return p
}
/// Learns the sender of a `Heartbeat`, `Awake` or `Hello`
/// (`AddToMachinePool`, `MachineStuff.cs:712-777`).
///
/// A known name just has its id and timestamp refreshed. A new name is
/// learned, the matrix is rebuilt from the pool so control is bidirectional
/// straight away (`:758-772`), and the caller is 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 [.persistMachinePool]
}
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
}
}