iOS: DModemKit, the app's modem apart from its views; terminal rows as runs

ios/DModemKit (Swift package): the engine (dmodem_engine.h) from Swift
(Engine: its config, its callbacks to a listener), its DTE (read on a
thread of its own, written), the settings (ModemSettings, as the Android
app's: the SIP account or the Wi-Fi peer line, user:password@host, kept in
UserDefaults, read leniently), ConnectInfo ("V.cvm · LAPM"), and
ModemSession (started from the settings: status, log, console, the DTE's
data, the speaker) for the views to watch. On Apple's systems the engine
is the XCFramework; on Linux the host build's libraries
(DMODEM_HOST_BUILD), so its tests run there: a session on a peer line
answering AT commands, a dial handed to the app and turned down busy.

shared: TerminalEmulator.runs(), a screen row as styled runs with their
colours resolved as TerminalView has them (the remote's palette, bold as
bright, iCE colours, inverse, faint), for a view that draws text (the iOS
app's); tested on the JVM and natively.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0172Hejd12i4aYikYW9vgpZs
This commit is contained in:
Claude committed 2026-10-18 02:09:13 +00:00
1 parent 34c89ee1e7
commit 7db2a88b79
10 files changed
+861

No files matched your search

+39
View File
@@ -0,0 +1,39 @@
// swift-tools-version:5.9
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
//
// DModemKit: the iOS app's modem, apart from its views: the engine
// (dmodem_engine.h) from Swift, its DTE, the settings, the session the
// views watch. On Apple's systems the engine is build-apple's XCFramework
// (ios/build-native.sh); on Linux the host build's libraries (cmake -S
// native-test -B build-host, or DMODEM_HOST_BUILD), so its tests run
// there too.
import Foundation
import PackageDescription
#if os(Linux)
let host = ProcessInfo.processInfo.environment["DMODEM_HOST_BUILD"] ?? "../../build-host"
let engine: Target = .systemLibrary(name: "DModemEngine", path: "Sources/DModemEngineHost")
let engineLinking: [LinkerSetting] = [
.unsafeFlags([
"-L\(host)/app", "-L\(host)/app/d-modem-re/dmodemd", "-L\(host)/_deps/libre-install/lib",
]),
.linkedLibrary("dmodem_engine"), .linkedLibrary("dmodem_sip"), .linkedLibrary("re"),
.linkedLibrary("ssl"), .linkedLibrary("crypto"), .linkedLibrary("stdc++"), .linkedLibrary("dl"),
.linkedLibrary("m"),
]
#else
let engine: Target = .binaryTarget(name: "DModemEngine", path: "../../build-apple/DModemEngine.xcframework")
let engineLinking: [LinkerSetting] = [.linkedLibrary("c++")]
#endif
let package = Package(
name: "DModemKit",
platforms: [.macOS(.v12), .iOS(.v15)],
products: [.library(name: "DModemKit", targets: ["DModemKit"])],
targets: [
engine,
.target(name: "DModemKit", dependencies: ["DModemEngine"], linkerSettings: engineLinking),
.testTarget(name: "DModemKitTests", dependencies: ["DModemKit"]),
]
)
@@ -0,0 +1,4 @@
module DModemEngine [system] {
header "../../../../app/src/main/cpp/dmodem_engine.h"
export *
}
@@ -0,0 +1,24 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
import Foundation
/// What a CONNECT result says beyond the rate ("CONNECT 1200/CVM/LAPM",
/// "CONNECT 56000/V92/LAPM/V44"), named as Home shows it ("V.cvm · LAPM").
/// The Android app's ConnectInfo.
public enum ConnectInfo {
static let names: [String: String] = [
"CVM": "V.cvm", "V92": "V.92", "V90": "V.90", "V91": "V.91", "V34": "V.34",
"V32B": "V.32bis", "V32": "V.32", "V22B": "V.22bis", "V22": "V.22", "V23": "V.23",
"V21": "V.21", "B103": "Bell 103", "B212": "Bell 212", "LAPM": "LAPM", "MNP": "MNP",
"V44": "V.44", "V42BIS": "V.42bis", "MNP5": "MNP 5",
]
/// the last CONNECT line in [console]: its parts after the rate, named; empty when there's none
public static func label(_ console: String) -> String {
guard let r = console.range(of: "CONNECT", options: .backwards) else { return "" }
let line = console[r.upperBound...].prefix { !$0.isNewline }
return line.trimmingCharacters(in: .whitespaces).split(separator: "/").dropFirst()
.compactMap { names[$0.trimmingCharacters(in: .whitespaces).uppercased()] }
.joined(separator: " · ")
}
}
+86
View File
@@ -0,0 +1,86 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
import Foundation
#if canImport(Glibc)
import Glibc
#endif
/// The modem's DTE: what it says (its results, the remote's data) read on
/// a thread of its own to [onData]; what we send it (AT commands, data)
/// written. Closing it stops the modem.
public final class DTE: @unchecked Sendable {
private let fd: Int32
private let lock = NSLock()
private var closed = false
private var reader: Thread?
private var handler: ((Data) -> Void)?
init(fd: Int32) {
self.fd = fd
}
/// the modem's octets as they come (on the reader's thread), until it ends ([onEnd])
public func read(onData: @escaping (Data) -> Void, onEnd: @escaping () -> Void = {}) {
lock.lock()
handler = onData
let start = reader == nil
lock.unlock()
guard start else { return }
let t = Thread { [weak self] in
var buf = [UInt8](repeating: 0, count: 4096)
while let self {
let n = buf.withUnsafeMutableBytes { Foundation.read(self.fd, $0.baseAddress, $0.count) }
if n < 0 && errno == EINTR { continue }
if n <= 0 { break }
let data = Data(buf[0..<n])
self.lock.lock(); let h = self.handler; self.lock.unlock()
h?(data)
}
onEnd()
}
t.name = "dte"
lock.lock(); reader = t; lock.unlock()
t.start()
}
/// [data] to the modem, all of it; false once it's gone
@discardableResult
public func write(_ data: Data) -> Bool {
lock.lock(); let gone = closed; lock.unlock()
if gone { return false }
return data.withUnsafeBytes { raw -> Bool in
var p = raw.baseAddress!
var left = raw.count
while left > 0 {
let w = Foundation.write(fd, p, left)
if w < 0 && errno == EINTR { continue }
if w <= 0 { return false }
p += w
left -= w
}
return true
}
}
@discardableResult
public func write(_ text: String) -> Bool { write(Data(text.utf8)) }
/// an AT command (its CR added)
@discardableResult
public func command(_ cmd: String) -> Bool { write(cmd + "\r") }
/// the DTE closed: the modem stops
public func close() {
lock.lock()
let was = closed
closed = true
lock.unlock()
if !was {
// (the reader's read ends: the other end gone)
shutdown(fd, Int32(SHUT_RDWR))
Foundation.close(fd)
}
}
deinit { close() }
}
@@ -0,0 +1,151 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
import DModemEngine
import Foundation
/// the call's state, as the engine reports it
public enum Link: Int, Sendable {
case idle = 0, connecting, online, hangingUp
}
public struct ModemStatus: Equatable, Sendable {
public var link: Link = .idle
public var offHook = false
public var txRate = 0
public var rxRate = 0
public init(link: Link = .idle, offHook: Bool = false, txRate: Int = 0, rxRate: Int = 0) {
self.link = link
self.offHook = offHook
self.txRate = txRate
self.rxRate = rxRate
}
}
/// what the modem starts with (dmodem_config)
public struct EngineConfig: Sendable {
public var user = "", password = "", domain = ""
public var sipPort = 5060
/// register and take calls (or, on a peer line, take the other phone's)
public var listen = false
public var t38 = true
/// DNS servers for SRV and NAPTR (iOS has no resolv.conf the engine can read)
public var dns: [String] = []
public var country = ""
/// where the modem keeps what it learns of the line
public var dataFile = ""
public var logLevel = 0, sipLogLevel = 1
/// the line another phone's through the app, not SIP; its lead silence (ms)
public var peer = false
public var peerLeadMs = 100
public init() {}
}
/// what the engine tells, from its threads
public protocol EngineListener: AnyObject {
func engineLog(_ line: String)
func engineStatus(_ status: ModemStatus)
/// the modem stopped: 0 asked for (or the DTE closed), -1 an error
func engineExited(_ result: Int)
/// a peer line's modem off hook: dialling [dial] (caller) or answering; [fd] its samples, ours to close
func engineLine(caller: Bool, dial: String, fd: Int32)
/// the speaker (ATM, ATL): 0 off, 1...3
func engineSpeaker(_ level: Int)
/// the line's sound while the speaker is on (16 bit, 8000 Hz)
func engineSound(_ pcm: UnsafeBufferPointer<Int16>)
}
public extension EngineListener {
func engineLine(caller: Bool, dial: String, fd: Int32) { close(fd) }
func engineSpeaker(_ level: Int) {}
func engineSound(_ pcm: UnsafeBufferPointer<Int16>) {}
}
public enum EngineError: Error, Equatable {
/// it runs already, or couldn't start (the log says why)
case notStarted
}
/// The modem (one in the process): dmodem_engine.h from Swift. Its
/// callbacks come on the engine's threads; [listener] gets them there.
public final class Engine: @unchecked Sendable {
public static let shared = Engine()
private let lock = NSLock()
private weak var _listener: EngineListener?
var listener: EngineListener? {
lock.lock(); defer { lock.unlock() }
return _listener
}
private init() {
var cb = dmodem_callbacks()
// (one engine, one Engine: the callbacks find it through this, not a context)
cb.ctx = nil
cb.log = { _, line in
guard let line else { return }
Engine.shared.listener?.engineLog(String(cString: line).trimmingCharacters(in: .newlines))
}
cb.status = { _, link, offhook, tx, rx in
Engine.shared.listener?.engineStatus(
ModemStatus(link: Link(rawValue: Int(link)) ?? .idle, offHook: offhook != 0, txRate: Int(tx), rxRate: Int(rx)))
}
cb.exited = { _, result in Engine.shared.listener?.engineExited(Int(result)) }
cb.line = { _, caller, dial, fd in
guard let l = Engine.shared.listener else { close(fd); return }
l.engineLine(caller: caller != 0, dial: dial.map { String(cString: $0) } ?? "", fd: fd)
}
cb.speaker = { _, level in Engine.shared.listener?.engineSpeaker(Int(level)) }
cb.sound = { _, pcm, n in
guard let pcm, n > 0 else { return }
Engine.shared.listener?.engineSound(UnsafeBufferPointer(start: pcm, count: Int(n)))
}
dmodem_set_callbacks(&cb)
}
/// the modem started with [config], its callbacks to [listener]: its DTE
public func start(_ config: EngineConfig, listener: EngineListener) throws -> DTE {
lock.lock(); _listener = listener; lock.unlock()
var c = dmodem_config()
dmodem_config_init(&c)
let dns = config.dns.joined(separator: ",")
let fd: Int32 = config.user.withCString { user in
config.password.withCString { password in
config.domain.withCString { domain in
dns.withCString { dnsC in
config.country.withCString { country in
config.dataFile.withCString { dataFile in
c.user = user
c.password = password
c.domain = domain
c.sip_port = Int32(config.sipPort)
c.listen = config.listen ? 1 : 0
c.t38 = config.t38 ? 1 : 0
c.dns = dns.isEmpty ? nil : dnsC
c.country = country
c.data_file = config.dataFile.isEmpty ? nil : dataFile
c.log_level = Int32(config.logLevel)
c.sip_log_level = Int32(config.sipLogLevel)
c.peer = config.peer ? 1 : 0
c.peer_lead_ms = Int32(config.peerLeadMs)
return dmodem_start(&c)
}
}
}
}
}
}
guard fd >= 0 else { throw EngineError.notStarted }
return DTE(fd: fd)
}
/// the modem stopped (its call hung up); waits for it
public func stop() { dmodem_stop() }
public var running: Bool { dmodem_running() != 0 }
/// a peer line's event: RING, CANCEL, ANSWERED, FAILED <SIP status>, DROPPED
public func peerEvent(_ line: String) { dmodem_peer_event(line) }
}
@@ -0,0 +1,151 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
import Foundation
/// The modem as the app has it: started with the settings, its status, its
/// log and its console (what it said, for Home's last lines and the
/// CONNECT's label), its DTE's data to whoever reads it (the terminal).
/// Changes go to [onChange] (on the engine's threads: the app's model
/// takes them to the main one).
public final class ModemSession: EngineListener, @unchecked Sendable {
public enum Run: Sendable { case stopped, running }
private let lock = NSLock()
private var _run = Run.stopped
private var _status = ModemStatus()
private var _log: [String] = []
private var _console = ""
private var _error: String?
private var dte: DTE?
/// the most of the log and the console kept
public var logMax = 2000
public var consoleMax = 16 * 1024
/// something changed (run, status, log, console, error)
public var onChange: (() -> Void)?
/// the DTE's data (the terminal's), as it comes
public var onData: ((Data) -> Void)?
/// the speaker's level and sound (the app's audio)
public var onSpeaker: ((Int) -> Void)?
public var onSound: ((UnsafeBufferPointer<Int16>) -> Void)?
private let engine: Engine
public init(engine: Engine = .shared) {
self.engine = engine
}
public var run: Run { lock.lock(); defer { lock.unlock() }; return _run }
public var status: ModemStatus { lock.lock(); defer { lock.unlock() }; return _status }
public var log: [String] { lock.lock(); defer { lock.unlock() }; return _log }
public var console: String { lock.lock(); defer { lock.unlock() }; return _console }
/// why it last stopped by itself, or didn't start
public var error: String? { lock.lock(); defer { lock.unlock() }; return _error }
/// "V.cvm · LAPM": the last CONNECT's, while online
public var connectLabel: String { status.link == .online ? ConnectInfo.label(console) : "" }
/// the modem started with [settings]; its start commands sent. False (and [error]) if it couldn't
@discardableResult
public func start(_ settings: ModemSettings, dns: [String] = [], dataFile: String = "") -> Bool {
if run == .running { return true }
guard settings.complete else {
setError("set up a SIP account first")
return false
}
do {
let d = try engine.start(settings.engineConfig(dns: dns, dataFile: dataFile), listener: self)
lock.lock()
dte = d
_run = .running
_status = ModemStatus()
_error = nil
lock.unlock()
d.read(onData: { [weak self] data in self?.received(data) })
let start = settings.startCommands()
if !start.isEmpty { d.command(start) }
changed()
return true
} catch {
setError("the modem didn't start (the log says why)")
return false
}
}
/// the modem stopped: its call hung up
public func stop() {
lock.lock()
let d = dte
dte = nil
lock.unlock()
engine.stop()
d?.close()
lock.lock(); _run = .stopped; _status = ModemStatus(); lock.unlock()
changed()
}
/// to the modem: data, or (with its CR) an AT command
@discardableResult
public func send(_ data: Data) -> Bool {
lock.lock(); let d = dte; lock.unlock()
return d?.write(data) ?? false
}
@discardableResult
public func command(_ cmd: String) -> Bool { send(Data((cmd + "\r").utf8)) }
/// hang up: +++ with its guard times, then ATH (blocking, about 2.5 s)
public func hangUp() {
Thread.sleep(forTimeInterval: 1.1)
send(Data("+++".utf8))
Thread.sleep(forTimeInterval: 1.3)
command("ATH")
}
private func received(_ data: Data) {
let text = String(decoding: data, as: UTF8.self)
lock.lock()
_console += text
if _console.count > consoleMax { _console = String(_console.suffix(consoleMax / 2)) }
lock.unlock()
onData?(data)
changed()
}
private func setError(_ e: String) {
lock.lock(); _error = e; lock.unlock()
changed()
}
private func changed() { onChange?() }
// EngineListener
public func engineLog(_ line: String) {
lock.lock()
_log.append(line)
if _log.count > logMax { _log.removeFirst(_log.count - logMax) }
lock.unlock()
changed()
}
public func engineStatus(_ status: ModemStatus) {
lock.lock(); _status = status; lock.unlock()
changed()
}
public func engineExited(_ result: Int) {
lock.lock()
let wasRunning = _run == .running && dte != nil
_run = .stopped
_status = ModemStatus()
if result != 0 && wasRunning { _error = "the modem stopped (the log says why)" }
lock.unlock()
changed()
}
public func engineSpeaker(_ level: Int) { onSpeaker?(level) }
public func engineSound(_ pcm: UnsafeBufferPointer<Int16>) { onSound?(pcm) }
}
@@ -0,0 +1,122 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
import Foundation
/// How the modem runs (the Android app's ModemSettings, the lines iOS has:
/// a SIP account, or another phone with the app on the same Wi-Fi).
public struct ModemSettings: Codable, Equatable, Sendable {
public enum Line: String, Codable, Sendable {
case sip, wifi
}
/// the SIP account
public var user = ""
public var password = ""
/// the registrar's or proxy's host[:port]
public var domain = ""
public var sipPort = 5060
/// register and take calls (on Wi-Fi: take the other phone's)
public var listen = false
public var t38 = true
/// the modem's country (empty: USA)
public var country = ""
/// AT commands sent each time it starts (SIP has no dial tone: ATX3)
public var initCommands = "ATX3"
public var logLevel = 0
public var sipLogLevel = 1
/// the modem's speaker on the phone's: the dialling and the handshake heard
public var speaker = true
public var line = Line.sip
/// the other phone to call (host[:port]), and the PIN between the two
public var peerAddress = ""
public var peerPort = 5070
public var peerPin = ""
public init() {}
/// the line another phone's, not SIP
public var peer: Bool { line != .sip }
/// enough to start: an account (or the line another phone's)
public var complete: Bool { peer || (!user.isEmpty && !domain.isEmpty) }
/// the commands sent as the modem starts (empty: none)
public func startCommands() -> String {
initCommands.trimmingCharacters(in: .whitespacesAndNewlines)
}
/// the engine's configuration for these, with the DNS servers the network has
public func engineConfig(dns: [String] = [], dataFile: String = "") -> EngineConfig {
var c = EngineConfig()
c.user = user
c.password = password
c.domain = domain
c.sipPort = sipPort
c.listen = listen
c.t38 = t38
c.dns = dns
c.country = country
c.dataFile = dataFile
c.logLevel = logLevel
c.sipLogLevel = sipLogLevel
c.peer = peer
return c
}
/// "user:password@host[:port]" (as dmodemd's SIP_LOGIN): its parts, nil if it isn't one
public static func parseLogin(_ s: String) -> (user: String, password: String, domain: String)? {
let t = s.trimmingCharacters(in: .whitespaces)
// (the password may have an @ in it: the last one ends it)
guard let at = t.range(of: "@", options: .backwards), let colon = t[..<at.lowerBound].firstIndex(of: ":") else { return nil }
let user = String(t[..<colon])
let password = String(t[t.index(after: colon)..<at.lowerBound])
let domain = String(t[at.upperBound...])
guard !user.isEmpty, !domain.isEmpty else { return nil }
return (user, password, domain)
}
// (decoded leniently: a setting a newer version added is its default when missing)
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
let d = ModemSettings()
user = try c.decodeIfPresent(String.self, forKey: .user) ?? d.user
password = try c.decodeIfPresent(String.self, forKey: .password) ?? d.password
domain = try c.decodeIfPresent(String.self, forKey: .domain) ?? d.domain
sipPort = try c.decodeIfPresent(Int.self, forKey: .sipPort) ?? d.sipPort
listen = try c.decodeIfPresent(Bool.self, forKey: .listen) ?? d.listen
t38 = try c.decodeIfPresent(Bool.self, forKey: .t38) ?? d.t38
country = try c.decodeIfPresent(String.self, forKey: .country) ?? d.country
initCommands = try c.decodeIfPresent(String.self, forKey: .initCommands) ?? d.initCommands
logLevel = try c.decodeIfPresent(Int.self, forKey: .logLevel) ?? d.logLevel
sipLogLevel = try c.decodeIfPresent(Int.self, forKey: .sipLogLevel) ?? d.sipLogLevel
speaker = try c.decodeIfPresent(Bool.self, forKey: .speaker) ?? d.speaker
line = try c.decodeIfPresent(Line.self, forKey: .line) ?? d.line
peerAddress = try c.decodeIfPresent(String.self, forKey: .peerAddress) ?? d.peerAddress
peerPort = try c.decodeIfPresent(Int.self, forKey: .peerPort) ?? d.peerPort
peerPin = try c.decodeIfPresent(String.self, forKey: .peerPin) ?? d.peerPin
}
}
/// The settings kept (UserDefaults, as JSON). The password stays there
/// for now; the Keychain is the app's next step.
public final class SettingsStore: @unchecked Sendable {
private let defaults: UserDefaults
private let key: String
public init(defaults: UserDefaults = .standard, key: String = "modemSettings") {
self.defaults = defaults
self.key = key
}
public var settings: ModemSettings {
get {
guard let d = defaults.data(forKey: key), let s = try? JSONDecoder().decode(ModemSettings.self, from: d) else {
return ModemSettings()
}
return s
}
set {
if let d = try? JSONEncoder().encode(newValue) { defaults.set(d, forKey: key) }
}
}
}
@@ -0,0 +1,129 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
import DModemKit
import Foundation
import XCTest
/// DModemKit on the engine itself (Linux's host build, or Apple's
/// XCFramework): a session started on a peer line (no SIP needed) answering
/// AT commands, its console and status; a dial handed to the app and
/// turned down busy; stopped. The settings as the Android app has them.
final class DModemKitTests: XCTestCase {
/// [cond] within [secs]
func waitFor(_ secs: Double = 10, _ cond: () -> Bool) -> Bool {
let end = Date().addingTimeInterval(secs)
while Date() < end {
if cond() { return true }
Thread.sleep(forTimeInterval: 0.05)
}
return cond()
}
final class Lines: EngineListener, @unchecked Sendable {
let session: ModemSession
var dial = ""
var fd: Int32 = -1
let lock = NSLock()
init(_ s: ModemSession) { session = s }
func engineLog(_ line: String) { session.engineLog(line) }
func engineStatus(_ status: ModemStatus) { session.engineStatus(status) }
func engineExited(_ result: Int) { session.engineExited(result) }
func engineLine(caller: Bool, dial: String, fd: Int32) {
lock.lock(); self.dial = dial; self.fd = fd; lock.unlock()
}
}
func testASessionOnAPeerLine() {
signal(SIGPIPE, SIG_IGN)
let session = ModemSession()
var changes = 0
session.onChange = { changes += 1 }
var settings = ModemSettings()
settings.line = .wifi
settings.initCommands = "ATE0"
// (the modem's log at level 1: its commands, its states)
settings.logLevel = 1
XCTAssertTrue(session.start(settings))
XCTAssertEqual(session.run, .running)
XCTAssertTrue(waitFor { session.console.contains("OK") }, session.console)
session.command("ATI3")
XCTAssertTrue(waitFor { session.console.contains("peer") }, session.console)
// the log came through
XCTAssertTrue(waitFor { !session.log.isEmpty })
XCTAssertGreaterThan(changes, 0)
// a second start while it runs: nothing new
XCTAssertTrue(session.start(settings))
session.stop()
XCTAssertEqual(session.run, .stopped)
XCTAssertFalse(Engine.shared.running)
}
func testADialHandedToTheApp() throws {
signal(SIGPIPE, SIG_IGN)
let session = ModemSession()
let lines = Lines(session)
var config = EngineConfig()
config.peer = true
let dte = try Engine.shared.start(config, listener: lines)
var text = ""
let tl = NSLock()
dte.read(onData: { d in tl.lock(); text += String(decoding: d, as: UTF8.self); tl.unlock() })
dte.command("ATE0X3D5551234")
XCTAssertTrue(waitFor { lines.lock.lock(); defer { lines.lock.unlock() }; return lines.fd >= 0 })
XCTAssertEqual(lines.dial, "5551234")
// the far end busy: BUSY to the DTE
Engine.shared.peerEvent("FAILED 486")
// (and its line closed, as the app's PeerLine ends a failed call)
close(lines.fd)
XCTAssertTrue(waitFor { tl.lock(); defer { tl.unlock() }; return text.contains("BUSY") }, text)
// the DTE closed: the modem stops by itself
dte.close()
XCTAssertTrue(waitFor { !Engine.shared.running })
// (its thread joined)
Engine.shared.stop()
}
func testIncompleteSettingsDontStart() {
let session = ModemSession()
XCTAssertFalse(session.start(ModemSettings()))
XCTAssertEqual(session.error, "set up a SIP account first")
XCTAssertEqual(session.run, .stopped)
}
func testLogins() {
let a = ModemSettings.parseLogin("alice:secret@sip.example.com")
XCTAssertEqual(a?.user, "alice"); XCTAssertEqual(a?.password, "secret"); XCTAssertEqual(a?.domain, "sip.example.com")
let b = ModemSettings.parseLogin("bob:p@ss@pbx.local:5070")
XCTAssertEqual(b?.password, "p@ss"); XCTAssertEqual(b?.domain, "pbx.local:5070")
XCTAssertEqual(ModemSettings.parseLogin("u:@h")?.password, "")
XCTAssertNil(ModemSettings.parseLogin("alice@sip.example.com"))
XCTAssertNil(ModemSettings.parseLogin("alice:secret"))
XCTAssertNil(ModemSettings.parseLogin(":x@h"))
XCTAssertNil(ModemSettings.parseLogin("u:x@"))
}
func testSettingsKeptAndOldOnesRead() throws {
let defaults = UserDefaults(suiteName: "dmodemkit-test-\(UUID())")!
let store = SettingsStore(defaults: defaults)
XCTAssertEqual(store.settings, ModemSettings())
var s = ModemSettings()
s.user = "alice"; s.domain = "sip.example.com"; s.line = .wifi; s.peerPin = "1234"
store.settings = s
XCTAssertEqual(store.settings, s)
XCTAssertTrue(s.complete)
// settings from before a field was added: its default
defaults.set(Data(#"{"user":"u","domain":"d"}"#.utf8), forKey: "modemSettings")
XCTAssertEqual(store.settings.user, "u")
XCTAssertEqual(store.settings.initCommands, "ATX3")
XCTAssertTrue(store.settings.t38)
XCTAssertEqual(ModemSettings().engineConfig(dns: ["1.1.1.1"]).dns, ["1.1.1.1"])
}
func testWhatTheConnectSaid() {
XCTAssertEqual(ConnectInfo.label("ATD5550002\r\nCONNECT 1200/CVM/LAPM\r\n"), "V.cvm · LAPM")
XCTAssertEqual(ConnectInfo.label("CONNECT 48000/V92/LAPM/V44\r\nhello"), "V.92 · LAPM · V.44")
XCTAssertEqual(ConnectInfo.label("CONNECT 300\r\n"), "")
XCTAssertEqual(ConnectInfo.label("OK\r\n"), "")
XCTAssertEqual(ConnectInfo.label("CONNECT 9600/V32\r\nNO CARRIER\r\nCONNECT 1200/CVM\r\n"), "V.cvm")
}
}
@@ -0,0 +1,97 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.terminal
/**
* A row of the screen as runs of text with one look each, its colours
* resolved (ARGB): what a view that draws text, not cells, needs (the iOS
* app's, in SwiftUI). As Android's TerminalView resolves them: the
* remote's palette changes, bold as bright, iCE colours (blink as a bright
* background), inverse (the cell's and the screen's), faint.
*/
class StyledRun(
/** its first column, and the columns it covers (a wide character two) */
val col: Int,
val cells: Int,
/** its text: never-written cells as spaces, a wide character once, combining marks after their base */
val text: String,
val fg: Int,
val bg: Int,
val bold: Boolean,
val italic: Boolean,
val underline: Boolean,
val strike: Boolean,
)
/** how the runs' colours are taken (the terminal's settings) */
class RunLook(
val theme: TermTheme = TermTheme.VGA,
/** bold in colours 0-7 as their bright ones (8-15), the BBS way */
val boldBright: Boolean = true,
/** blink as a bright background, not blinking (iCE colours) */
val iceColors: Boolean = false,
)
/** [row] of the screen (0: its top; negative: the scrollback's, -1 the newest) as runs */
fun TerminalEmulator.runs(row: Int, look: RunLook = RunLook()): List<StyledRun> {
val line = line(row)
val out = ArrayList<StyledRun>()
val text = StringBuilder()
fun color(c: Int, isFg: Boolean): Int {
val i = when {
c == Style.DEFAULT_FG -> 256
c == Style.DEFAULT_BG -> 257
c and Style.RGB == 0 && c in 0..255 -> c
else -> -1
}
if (i >= 0) {
val o = colorOverride(i)
if (o != -1) return o
}
return look.theme.argb(c, isFg)
}
var x = 0
while (x < line.cols) {
val st = line.styles[x]
var end = x + 1
while (end < line.cols && line.styles[end] == st) end++
val a = Style.attrs(st)
var fg = Style.fg(st)
var bg = Style.bg(st)
if (a and Style.BOLD != 0 && look.boldBright && fg in 0..7) fg += 8
if (look.iceColors && a and Style.BLINK != 0 && bg in 0..7) bg += 8
var f = color(fg, true)
var b = color(bg, false)
if ((a and Style.INVERSE != 0) != reverseVideo) {
val t = f; f = b; b = t
}
if (a and Style.FAINT != 0) f = (f and 0x00ffffff) or (0x99 shl 24)
val hidden = a and Style.INVISIBLE != 0
text.setLength(0)
for (i in x until end) {
val cp = line.chars[i]
when {
cp == Line.WIDE_TAIL -> {}
hidden || cp == 0 -> text.append(' ')
else -> {
text.appendCp(cp)
line.extra(i)?.combining?.forEach { text.appendCp(it) }
}
}
}
out.add(
StyledRun(
col = x, cells = end - x, text = text.toString(), fg = f, bg = b,
// (heavy glyphs only when bold isn't shown as a bright colour instead)
bold = a and Style.BOLD != 0 && !(look.boldBright && Style.fg(st) in 0..7),
italic = a and Style.ITALIC != 0,
underline = a and Style.ANY_UNDERLINE != 0,
strike = a and Style.STRIKE != 0,
),
)
x = end
}
return out
}
@@ -0,0 +1,58 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.terminal
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
/** A screen's rows as styled runs (what the iOS app draws): the text, its cells, its colours resolved. */
class TerminalRunsTest {
private val vga = TermTheme.VGA
private fun argb(rgb: Int) = 0xff000000.toInt() or rgb
@Test
fun plainColouredBoldInverse() {
val t = TerminalEmulator(20, 3)
// red, then bold red (bright, as BBSes have it), inverse, default
t.appendText("\u001b[31mab\u001b[1mcd\u001b[0;7mef\u001b[0mgh")
val r = t.runs(0)
assertEquals(listOf("ab", "cd", "ef", "gh" + " ".repeat(12)), r.map { it.text })
assertEquals(listOf(0, 2, 4, 6), r.map { it.col })
assertEquals(argb(0xaa0000), r[0].fg)
assertEquals(argb(0xff5555), r[1].fg)
assertFalse(r[1].bold)
// inverse: the default colours swapped
assertEquals(vga.bgArgb, r[2].fg)
assertEquals(vga.fgArgb, r[2].bg)
assertEquals(20, r.sumOf { it.cells })
// bold shown heavy when it isn't bright instead
val heavy = t.runs(0, RunLook(boldBright = false))
assertTrue(heavy[1].bold)
assertEquals(argb(0xaa0000), heavy[1].fg)
}
@Test
fun wideCharactersAndTrueColour() {
val t = TerminalEmulator(10, 2)
t.appendText("\u001b[38;2;1;2;3m漢x")
val r = t.runs(0)
// the wide character once, over two cells
assertEquals("漢x", r[0].text)
assertEquals(3, r[0].cells)
assertEquals(argb(0x010203), r[0].fg)
// a row never written: spaces, the theme's colours
val blank = t.runs(1).single()
assertEquals(" ".repeat(10), blank.text)
assertEquals(vga.bgArgb, blank.bg)
}
@Test
fun theRemotesPalette() {
val t = TerminalEmulator(10, 1)
// OSC 4: colour 1 is now green
t.appendText("\u001b]4;1;rgb:00/ff/00\u001b\\\u001b[31mx")
assertEquals(argb(0x00ff00), t.runs(0)[0].fg)
}
}