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

@@ -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) }
}
}
}