Files

243 lines
11 KiB
Swift

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