iOS app: SwiftUI on DModemKit and the shared terminal

ios/DModem (XcodeGen's project.yml, iOS 16): Home (the modem's state, the
rates and what the CONNECT was, the call's time, start, hang up, stop, an
AT command line and its last words), the terminal (the shared Kotlin
emulator through TerminalBridge, drawn run by run in a Canvas; CP437 and
the VGA colours; the keyboard and a hardware one's arrows and Esc; Esc,
a sticky Ctrl, Tab and the arrows on a bar; pinch for the font), the log
(shared as text) and the settings (the SIP account or user:password@host,
incoming calls, T.38, the speaker, the AT commands at start, the log
levels). The modem's speaker on AVAudioEngine; the audio session (its
sound, or quiet) keeps a call going in the background. The DNS servers
from the resolver's state (SystemDNS.c: iOS has no resolv.conf for the
engine).

shared: TerminalBridge, the terminal for Swift (octets as Latin-1 strings
both ways, rows as runs, keys, replies, the title, the look and the
character set), tested on the JVM and natively; the framework also as an
XCFramework (assembleDModemSharedXCFramework).

CI: the macOS job builds the shared XCFramework, runs DModemKit's tests
and builds the app for the simulator; the Linux job runs DModemKit's
tests on the host engine. Not built here: no Xcode on Linux (DModemKit,
TerminalBridge and SystemDNS.c are).

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:15:16 +00:00
1 parent 7db2a88b79
commit 133d5acb61
20 files changed
+1002 -4

No files matched your search

+10
View File
@@ -78,6 +78,16 @@ jobs:
- name: Engine test
run: ctest --test-dir build-host --output-on-failure
# the iOS app's DModemKit (its Swift) on this engine: Swift runs on Linux too
- uses: swift-actions/setup-swift@v2
with:
swift-version: "6.1"
- name: DModemKit (Swift) on the engine
run: swift test --package-path ios/DModemKit
env:
DMODEM_HOST_BUILD: ${{ github.workspace }}/build-host
# (Apple's ways on Linux: the portable fallbacks the iOS build has)
- name: Engine test, Apple's fallbacks
run: |
+17 -1
View File
@@ -1,7 +1,8 @@
# The modem for Apple's systems, and the Kotlin the apps share on iOS: the engine with D-Modem-RE, libre and
# Mbed TLS built for iOS (devices and simulator) and macOS as an
# XCFramework (ios/build-native.sh), and its Swift tests run on macOS
# (ios/DModemSmoke): the modem through its C API, as the iOS app has it.
# (ios/DModemSmoke): the modem through its C API, as the iOS app has it;
# DModemKit's tests, and the iOS app (ios/DModem) built for the simulator.
#
# D-Modem-RE is a private submodule: the DMODEM_RE_TOKEN secret (as
# android.yml's).
@@ -41,6 +42,21 @@ jobs:
- name: Swift tests (macOS)
run: swift test --package-path ios/DModemSmoke
- name: DModemKit's tests (macOS)
run: swift test --package-path ios/DModemKit
# the iOS app: its project from ios/DModem/project.yml, built for the simulator
- name: The shared Kotlin as an XCFramework
run: ./gradlew :shared:assembleDModemSharedReleaseXCFramework
- name: The iOS app (simulator)
run: |
brew install xcodegen
cd ios/DModem && xcodegen generate
xcodebuild -project DModem.xcodeproj -scheme DModem \
-destination 'generic/platform=iOS Simulator' \
CODE_SIGNING_ALLOWED=NO build
- uses: actions/upload-artifact@v4
with:
name: DModemEngine.xcframework
+3
View File
@@ -12,3 +12,6 @@ captures/
.kotlin/
/build-apple/
/build-fallback/
# the iOS app's generated project
ios/DModem/DModem.xcodeproj/
+23 -3
View File
@@ -156,7 +156,7 @@ each way.
CI (`.github/workflows/android.yml`) runs all three; it needs a
`DMODEM_RE_TOKEN` secret that can read the private D-Modem-RE submodule.
## Apple's systems (the iOS app to come)
## Apple's systems: the iOS app
The native modem builds for iOS and macOS too: the engine's C API,
`app/src/main/cpp/dmodem_engine.h` (what Swift calls in place of
@@ -174,11 +174,31 @@ layer (`shared/.../io`). What stays each app's own: the UI, the modem
service, sockets and Bluetooth, Android's VPN and files. Its tests run on
the JVM and natively: `./gradlew :shared:allTests`.
The iOS app (`ios/DModem`, SwiftUI, iOS 16) is the modem on a SIP
account: Home (its state, the rates and what the CONNECT was, start, hang
up, stop, an AT command line), the terminal (the shared emulator drawn in
SwiftUI, CP437 and the VGA colours, Esc/Ctrl/Tab/arrows), the log and the
settings. Its modem keeps going in the background on the audio session
(its speaker, or quiet). The modem apart from the views is the
`ios/DModemKit` Swift package (the engine from Swift, its DTE, the
settings, the session), whose tests run on Linux too, against the host
build:
./gradlew :shared:assembleDModemSharedReleaseXCFramework
ios/build-native.sh
cd ios/DModem && xcodegen generate && open DModem.xcodeproj
DMODEM_HOST_BUILD=$PWD/build-host swift test --package-path ios/DModemKit # Linux or macOS
Still to come on iOS: the line to another phone (Bonjour), CallKit, the
Keychain for the password, fax, transfers and PPP's screens.
D-Modem-RE's `portable.h` has Apple's ways where Linux has its own
(close-on-exec sockets, SIGPIPE, a monotonic sleep, a peer's hang-up);
the Linux build tests them too with `-DDMODEM_PORTABLE_FALLBACKS`. CI
(`.github/workflows/apple.yml`) builds the XCFramework and runs the Swift
tests on macOS.
(`.github/workflows/apple.yml`) builds the XCFramework, runs the Swift
tests on macOS and builds the app for the simulator; the Linux job runs
DModemKit's tests on the host engine.
## License
+86
View File
@@ -0,0 +1,86 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
import DModemKit
import Foundation
import SwiftUI
/// The app's state for its views: the modem session (DModemKit) brought to
/// the main thread, the settings kept, the speaker and the background
/// audio that keeps a call going when the app isn't in front.
@MainActor
final class AppModel: ObservableObject {
@Published private(set) var run = ModemSession.Run.stopped
@Published private(set) var status = ModemStatus()
@Published private(set) var log: [String] = []
@Published private(set) var console = ""
@Published private(set) var error: String?
/// when the call came online (for its time on Home)
@Published private(set) var onlineSince: Date?
@Published var settings: ModemSettings {
didSet { store.settings = settings }
}
let session = ModemSession()
let terminal = TerminalModel()
private let store = SettingsStore()
private let audio = ModemAudio()
private var pending = false
init() {
settings = store.settings
session.onChange = { [weak self] in
// (many changes at once, one update)
Task { @MainActor [weak self] in self?.refresh() }
}
session.onData = { [weak self] data in
Task { @MainActor [weak self] in self?.terminal.feed(data) }
}
session.onSpeaker = { [audio] level in audio.speaker(level) }
session.onSound = { [audio] pcm in audio.play(pcm) }
terminal.send = { [weak self] data in self?.session.send(data) }
}
var connectLabel: String { status.link == .online ? ConnectInfo.label(console) : "" }
func start() {
error = nil
audio.enabled = settings.speaker
let dataFile = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
.map { url -> String in
try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
return url.appendingPathComponent("modem-data").path
} ?? ""
let s = settings
Task.detached { [session, audio] in
// (the background audio first: the call keeps the app running)
audio.begin()
if !session.start(s, dns: SystemDNS.servers(), dataFile: dataFile) { audio.end() }
}
}
func stop() {
Task.detached { [session, audio] in
session.stop()
audio.end()
}
}
func hangUp() {
Task.detached { [session] in session.hangUp() }
}
/// an AT command (Home's line)
func command(_ cmd: String) { session.command(cmd) }
private func refresh() {
let wasOnline = status.link == .online
run = session.run
status = session.status
log = session.log
console = session.console
error = session.error
if status.link == .online && !wasOnline { onlineSince = Date() }
if status.link != .online { onlineSince = nil }
if run == .stopped { audio.end() }
}
}
@@ -0,0 +1,4 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
// (the app's C, for its Swift)
#include "SystemDNS.h"
+24
View File
@@ -0,0 +1,24 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
import SwiftUI
/// D-Modem for iOS: the modem on a SIP account, its terminal, its log.
@main
struct DModemApp: App {
@StateObject private var model = AppModel()
var body: some Scene {
WindowGroup {
TabView {
NavigationStack { HomeView(model: model) }
.tabItem { Label("Home", systemImage: "house") }
NavigationStack { TerminalScreen(model: model.terminal) }
.tabItem { Label("Terminal", systemImage: "terminal") }
NavigationStack { LogView(model: model) }
.tabItem { Label("Log", systemImage: "list.bullet.rectangle") }
NavigationStack { SettingsView(model: model) }
.tabItem { Label("Settings", systemImage: "gear") }
}
}
}
}
+132
View File
@@ -0,0 +1,132 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
import DModemKit
import SwiftUI
/// What the modem is doing and the one thing to do about it (start, hang
/// up, stop); its rates online and what the CONNECT was; an AT command line
/// and the modem's last words.
struct HomeView: View {
@ObservedObject var model: AppModel
@State private var at = ""
var body: some View {
List {
Section {
VStack(alignment: .leading, spacing: 10) {
HStack {
Circle().fill(dotColor).frame(width: 12, height: 12)
Text(title).font(.title2.weight(.semibold))
Spacer()
if let since = model.onlineSince {
TimelineView(.periodic(from: since, by: 1)) { ctx in
Text(elapsed(since, ctx.date)).font(.title3.monospacedDigit())
}
}
}
if model.status.link == .online {
HStack(spacing: 28) {
rate("↓ down", model.status.rxRate)
rate("↑ up", model.status.txRate)
}
if !model.connectLabel.isEmpty {
Text(model.connectLabel).font(.body).foregroundStyle(.secondary)
}
} else {
Text(subtitle).foregroundStyle(.secondary)
}
if let e = model.error {
Text(e).foregroundStyle(.red).font(.callout)
}
actions
}
.padding(.vertical, 6)
}
Section("Line") {
LabeledContent("SIP account", value: model.settings.complete ? "\(model.settings.user)@\(model.settings.domain)" : "not set up")
LabeledContent("Incoming calls", value: model.settings.listen ? "taken" : "off")
LabeledContent("Fax", value: model.settings.t38 ? "audio or T.38" : "audio")
}
if model.run == .running {
Section("AT command") {
HStack {
TextField("ATI3", text: $at)
.textInputAutocapitalization(.characters)
.autocorrectionDisabled()
.font(.body.monospaced())
.onSubmit(sendAt)
Button("Send", action: sendAt).disabled(at.isEmpty)
}
Text(lastLines).font(.caption.monospaced()).foregroundStyle(.secondary)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
}
.navigationTitle("D-Modem")
}
@ViewBuilder private var actions: some View {
HStack {
switch model.run {
case .stopped:
Button("Start the modem") { model.start() }
.buttonStyle(.borderedProminent)
.disabled(!model.settings.complete)
case .running:
if model.status.offHook {
Button("Hang up") { model.hangUp() }.buttonStyle(.borderedProminent)
}
Button("Stop") { model.stop() }.buttonStyle(.bordered)
}
}
}
private var title: String {
switch (model.run, model.status.link) {
case (.stopped, _): return "Modem off"
case (_, .online): return "Online"
case (_, .connecting): return "Connecting…"
case (_, .hangingUp): return "Hanging up…"
default: return model.status.offHook ? "Off hook" : "Ready"
}
}
private var subtitle: String {
switch (model.run, model.status.link) {
case (.stopped, _): return model.settings.complete ? "Ready to start" : "Set up a SIP account to start"
case (_, .connecting): return "Training the line"
default: return model.status.offHook ? "Dialling" : "On hook, waiting for a dial (the Terminal: ATD)"
}
}
private var dotColor: Color {
if model.run == .stopped { return .gray }
// (online, or ready on hook: green; anything on its way: orange)
if model.status.link == .online || (model.status.link == .idle && !model.status.offHook) { return .green }
return .orange
}
private var lastLines: String {
model.console.split(whereSeparator: \.isNewline).suffix(6).joined(separator: "\n")
}
private func rate(_ label: String, _ bps: Int) -> some View {
VStack(alignment: .leading) {
Text(label).font(.caption)
Text(bps >= 1000 ? String(format: "%.1f kbit/s", Double(bps) / 1000) : "\(bps) bit/s")
.font(.title.weight(.bold))
}
}
private func elapsed(_ since: Date, _ now: Date) -> String {
let s = max(0, Int(now.timeIntervalSince(since)))
return String(format: "%d:%02d", s / 60, s % 60)
}
private func sendAt() {
let c = at.trimmingCharacters(in: .whitespaces)
guard !c.isEmpty else { return }
model.command(c.uppercased().hasPrefix("AT") ? c : "AT" + c)
at = ""
}
}
+24
View File
@@ -0,0 +1,24 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
import SwiftUI
/// The modem's and SIP's log, the newest at the bottom; shared as text.
struct LogView: View {
@ObservedObject var model: AppModel
var body: some View {
ScrollViewReader { proxy in
List(Array(model.log.enumerated()), id: \.offset) { item in
Text(item.element).font(.caption.monospaced()).textSelection(.enabled).id(item.offset)
}
.listStyle(.plain)
.onChange(of: model.log.count) { n in
if n > 0 { proxy.scrollTo(n - 1, anchor: .bottom) }
}
}
.navigationTitle("Log")
.toolbar {
ShareLink(item: model.log.joined(separator: "\n"))
}
}
}
+89
View File
@@ -0,0 +1,89 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
import AVFoundation
import Foundation
/// The modem's sound on the phone: its speaker (ATM, ATL: the dialling and
/// the handshake), and while the modem runs, the audio session that keeps
/// the app running in the background (UIBackgroundModes audio), quiet
/// between the speaker's sounds.
final class ModemAudio: @unchecked Sendable {
/// the speaker's sound played (the settings' "speaker")
var enabled = true
private let lock = NSLock()
private let engine = AVAudioEngine()
/// the speaker's sound, and (on its own, so the sound never waits behind it) the quiet
private let player = AVAudioPlayerNode()
private let quiet = AVAudioPlayerNode()
/// the modem's samples: 16 bit at 8000 Hz, as floats for the player
private let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 8000, channels: 1, interleaved: false)!
private var running = false
private var gain: Float = 0
init() {
engine.attach(player)
engine.attach(quiet)
engine.connect(player, to: engine.mainMixerNode, format: format)
engine.connect(quiet, to: engine.mainMixerNode, format: format)
}
/// the session active, the engine playing (quiet): the app keeps running behind others
func begin() {
lock.lock(); defer { lock.unlock() }
if running { return }
let s = AVAudioSession.sharedInstance()
do {
try s.setCategory(.playback, mode: .default, options: [.mixWithOthers])
try s.setActive(true)
try engine.start()
player.play()
quiet.play()
running = true
scheduleQuiet()
} catch {
NSLog("modem audio: \(error)")
}
}
func end() {
lock.lock(); defer { lock.unlock() }
if !running { return }
running = false
player.stop()
quiet.stop()
engine.stop()
try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
}
/// the speaker's level (0 off, 1...3: ATL's quiet, medium, loud)
func speaker(_ level: Int) {
lock.lock(); defer { lock.unlock() }
gain = !enabled || level <= 0 ? 0 : [0.3, 0.6, 1.0][min(level, 3) - 1]
}
/// the line's sound while the speaker is on
func play(_ pcm: UnsafeBufferPointer<Int16>) {
lock.lock()
let g = gain
let on = running
lock.unlock()
guard on, g > 0, pcm.count > 0,
let buf = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(pcm.count)) else { return }
buf.frameLength = AVAudioFrameCount(pcm.count)
let out = buf.floatChannelData![0]
for i in 0..<pcm.count { out[i] = Float(pcm[i]) / 32768 * g }
player.scheduleBuffer(buf)
}
/// a second of quiet, again and again: the session stays active with nothing to play
private func scheduleQuiet() {
guard let buf = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 8000) else { return }
buf.frameLength = 8000
quiet.scheduleBuffer(buf) { [weak self] in
guard let self else { return }
self.lock.lock(); let on = self.running; self.lock.unlock()
if on { self.scheduleQuiet() }
}
}
}
+62
View File
@@ -0,0 +1,62 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
import DModemKit
import SwiftUI
/// The SIP account (or pasted as user:password@host), incoming calls, T.38,
/// the AT commands at start, the speaker, the log levels. Kept as they're
/// changed; they apply the next time the modem starts.
struct SettingsView: View {
@ObservedObject var model: AppModel
@State private var login = ""
var body: some View {
Form {
Section {
TextField("User", text: $model.settings.user)
.textInputAutocapitalization(.never).autocorrectionDisabled()
SecureField("Password", text: $model.settings.password)
TextField("Server (host[:port])", text: $model.settings.domain)
.textInputAutocapitalization(.never).autocorrectionDisabled().keyboardType(.URL)
TextField("Or paste user:password@host", text: $login)
.textInputAutocapitalization(.never).autocorrectionDisabled()
.onSubmit {
if let l = ModemSettings.parseLogin(login) {
model.settings.user = l.user
model.settings.password = l.password
model.settings.domain = l.domain
login = ""
}
}
} header: {
Text("SIP account")
} footer: {
Text("The provider must carry G.711 (PCMU/PCMA) to the phone network.")
}
Section("Calls") {
Toggle("Take incoming calls", isOn: $model.settings.listen)
Toggle("Fax over T.38", isOn: $model.settings.t38)
Toggle("Speaker (the dialling and the handshake)", isOn: $model.settings.speaker)
Stepper("Local SIP port: \(model.settings.sipPort)", value: $model.settings.sipPort, in: 1024...65535)
}
Section {
TextField("AT commands at start", text: $model.settings.initCommands)
.textInputAutocapitalization(.characters).autocorrectionDisabled().font(.body.monospaced())
} header: {
Text("Modem")
} footer: {
Text("ATX3 by default: a SIP line has no dial tone.")
}
Section("Log") {
Stepper("Modem's level: \(model.settings.logLevel)", value: $model.settings.logLevel, in: 0...5)
Stepper("SIP's level: \(model.settings.sipLogLevel)", value: $model.settings.sipLogLevel, in: 0...4)
}
if model.run == .running {
Section {
Text("Changes apply when the modem starts again.").foregroundStyle(.secondary)
}
}
}
.navigationTitle("Settings")
}
}
+43
View File
@@ -0,0 +1,43 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (C) 2026 Neo-Desktop
*
* SystemDNS.c - see SystemDNS.h (res_ninit: libresolv)
*/
#include <arpa/inet.h>
#include <netinet/in.h>
#include <resolv.h>
#include <stdio.h>
#include <string.h>
#include "SystemDNS.h"
int dmodem_dns_servers(char *buf, int len)
{
struct __res_state st;
int i, n = 0, at = 0;
if (len <= 0)
return 0;
buf[0] = 0;
memset(&st, 0, sizeof(st));
if (res_ninit(&st) != 0)
return 0;
for (i = 0; i < st.nscount && i < MAXNS; i++) {
char a[INET_ADDRSTRLEN];
if (st.nsaddr_list[i].sin_family != AF_INET ||
!inet_ntop(AF_INET, &st.nsaddr_list[i].sin_addr, a, sizeof(a)))
continue;
int w = snprintf(buf + at, (size_t)(len - at), "%s%s", n ? "," : "", a);
if (w < 0 || w >= len - at)
break;
at += w;
n++;
}
#ifdef __APPLE__
res_ndestroy(&st); /* (Apple's: frees what res_ninit allocated) */
#else
res_nclose(&st);
#endif
return n;
}
+15
View File
@@ -0,0 +1,15 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (C) 2026 Neo-Desktop
*
* SystemDNS.h - the DNS servers the phone's network has (the engine's
* SIP needs them for SRV and NAPTR: iOS has no
* resolv.conf it can read), from the resolver's state
*/
#ifndef DMODEM_SYSTEM_DNS_H
#define DMODEM_SYSTEM_DNS_H
/* the IPv4 servers into buf, apart by commas ("" for none): how many */
int dmodem_dns_servers(char *buf, int len);
#endif
+12
View File
@@ -0,0 +1,12 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
import Foundation
/// The phone's network's DNS servers (SystemDNS.c), for the engine's SIP.
enum SystemDNS {
static func servers() -> [String] {
var buf = [CChar](repeating: 0, count: 512)
guard dmodem_dns_servers(&buf, Int32(buf.count)) > 0 else { return [] }
return String(cString: buf).split(separator: ",").map(String.init)
}
}
+78
View File
@@ -0,0 +1,78 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
import DModemShared
import Foundation
import SwiftUI
/// The terminal on the modem: the shared Kotlin's emulator
/// (TerminalBridge) fed what the modem says, its keys and replies to the
/// modem ([send]). Octets cross to Kotlin as Latin-1 strings, one
/// character each.
@MainActor
final class TerminalModel: ObservableObject {
let bridge = TerminalBridge(cols: 80, rows: 24)
/// the screen changed: redraw
@Published private(set) var revision: Int64 = 0
/// the next key with Ctrl (the extra keys' sticky Ctrl)
@Published var ctrl = false
/// to the modem
var send: ((Data) -> Void)?
init() {
// (BBSes: CP437, bold as bright; the VGA colours)
bridge.setLook(themeId: "vga", boldBright: true, iceColors: false, charset: "CP437")
}
var cols: Int { Int(bridge.cols) }
var rows: Int { Int(bridge.rows) }
/// what the modem said, onto the screen; the terminal's answers back
func feed(_ data: Data) {
guard let s = String(data: data, encoding: .isoLatin1) else { return }
bridge.feed(latin1: s)
let replies = bridge.takeReplies()
if !replies.isEmpty { out(replies) }
revision = bridge.revision
}
/// text typed (the keyboard's), Ctrl if the sticky one is down
func typed(_ text: String) {
out(bridge.typed(text: text, ctrl: ctrl, alt: false))
ctrl = false
}
/// a key that isn't a character: UP, DOWN, LEFT, RIGHT, ESCAPE, TAB, BACKSPACE, ENTER, F1 ...
func key(_ name: String) {
out(bridge.key(name: name, shift: false, alt: false, ctrl: ctrl))
ctrl = false
}
/// the screen to [cols] by [rows] (the view's size)
func resize(cols: Int, rows: Int) {
guard cols > 0, rows > 0, cols != self.cols || rows != self.rows else { return }
bridge.resize(cols: Int32(cols), rows: Int32(rows))
revision = bridge.revision
}
/// a row's runs
func runs(_ row: Int) -> [StyledRun] { bridge.runs(row: Int32(row)) }
private func out(_ latin1: String) {
guard !latin1.isEmpty, let d = latin1.data(using: .isoLatin1) else { return }
send?(d)
}
}
extension Color {
/// an ARGB colour as Kotlin has it
init(argb: Int32) {
let u = UInt32(bitPattern: argb)
self.init(
.sRGB,
red: Double((u >> 16) & 0xff) / 255,
green: Double((u >> 8) & 0xff) / 255,
blue: Double(u & 0xff) / 255,
opacity: Double((u >> 24) & 0xff) / 255)
}
}
+177
View File
@@ -0,0 +1,177 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
import DModemShared
import SwiftUI
import UIKit
/// The terminal: the screen drawn run by run in its cells, the keyboard
/// on a tap (KeyInput), the keys a phone's keyboard lacks below it.
struct TerminalScreen: View {
@ObservedObject var model: TerminalModel
@State private var focused = true
@AppStorage("terminalFontSize") private var fontSize: Double = 12
var body: some View {
VStack(spacing: 0) {
GeometryReader { geo in
let cell = CellMetrics(fontSize: fontSize)
ScreenCanvas(model: model, revision: model.revision, cell: cell)
.background(Color(argb: model.bridge.background))
.onAppear { fit(geo.size, cell) }
.onChange(of: geo.size) { fit($0, cell) }
.onChange(of: fontSize) { _ in fit(geo.size, CellMetrics(fontSize: fontSize)) }
.overlay(KeyInput(model: model, focused: $focused).frame(width: 1, height: 1).opacity(0.01), alignment: .topLeading)
.contentShape(Rectangle())
.onTapGesture { focused = true }
.gesture(MagnificationGesture().onEnded { s in fontSize = min(24, max(7, fontSize * Double(s))) })
}
ExtraKeys(model: model)
}
.navigationTitle(model.bridge.title.isEmpty ? "Terminal" : model.bridge.title)
.navigationBarTitleDisplayMode(.inline)
}
/// as many cells as fit
private func fit(_ size: CGSize, _ cell: CellMetrics) {
model.resize(cols: max(20, Int(size.width / cell.width)), rows: max(5, Int(size.height / cell.height)))
}
}
/// a cell's size in the terminal's font
struct CellMetrics {
let font: UIFont
let width: CGFloat
let height: CGFloat
init(fontSize: Double) {
font = UIFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
width = ceil(("M" as NSString).size(withAttributes: [.font: font]).width)
height = ceil(font.lineHeight)
}
}
/// the screen: each row's runs, their backgrounds, their text, the cursor
private struct ScreenCanvas: View {
@ObservedObject var model: TerminalModel
/// (read here so the canvas redraws with each change)
let revision: Int64
let cell: CellMetrics
var body: some View {
Canvas { ctx, _ in
let regular = Font(cell.font as CTFont)
let bold = Font(UIFont.monospacedSystemFont(ofSize: cell.font.pointSize, weight: .bold) as CTFont)
for row in 0..<model.rows {
let y = CGFloat(row) * cell.height
for run in model.runs(row) {
let x = CGFloat(run.col) * cell.width
let w = CGFloat(run.cells) * cell.width
ctx.fill(Path(CGRect(x: x, y: y, width: w, height: cell.height)), with: .color(Color(argb: run.bg)))
if run.text.trimmingCharacters(in: .whitespaces).isEmpty { continue }
var t = Text(run.text).font(run.bold ? bold : regular).foregroundColor(Color(argb: run.fg))
if run.italic { t = t.italic() }
if run.underline { t = t.underline() }
if run.strike { t = t.strikethrough() }
ctx.draw(t, at: CGPoint(x: x, y: y), anchor: .topLeading)
}
}
if model.bridge.cursorVisible {
let r = CGRect(x: CGFloat(model.bridge.cursorX) * cell.width, y: CGFloat(model.bridge.cursorY) * cell.height,
width: cell.width, height: cell.height)
ctx.fill(Path(r), with: .color(Color(argb: model.bridge.cursorColor).opacity(0.6)))
}
}
}
}
/// the keys a phone's keyboard lacks: Esc, a sticky Ctrl, Tab, the arrows
private struct ExtraKeys: View {
@ObservedObject var model: TerminalModel
var body: some View {
HStack(spacing: 6) {
key("Esc") { model.key("ESCAPE") }
Button(action: { model.ctrl.toggle() }) {
Text("Ctrl").frame(minWidth: 40, minHeight: 32)
}
.buttonStyle(.bordered)
.tint(model.ctrl ? .accentColor : .secondary)
key("Tab") { model.key("TAB") }
key("←") { model.key("LEFT") }
key("↓") { model.key("DOWN") }
key("↑") { model.key("UP") }
key("→") { model.key("RIGHT") }
}
.padding(.horizontal, 8)
.padding(.vertical, 6)
.background(.bar)
}
private func key(_ label: String, _ action: @escaping () -> Void) -> some View {
Button(action: action) { Text(label).frame(minWidth: 32, minHeight: 32) }
.buttonStyle(.bordered)
}
}
/// a view the keyboard types into: its text and keys to the terminal
/// (UIKeyInput), the hardware keyboard's arrows and Esc too
struct KeyInput: UIViewRepresentable {
let model: TerminalModel
@Binding var focused: Bool
func makeUIView(context: Context) -> KeyInputView {
let v = KeyInputView()
v.model = model
return v
}
func updateUIView(_ v: KeyInputView, context: Context) {
v.model = model
if focused && !v.isFirstResponder {
DispatchQueue.main.async { v.becomeFirstResponder() }
}
}
}
/// (a UIView: on the main actor, as the terminal's model is)
final class KeyInputView: UIView, UIKeyInput {
weak var model: TerminalModel?
override var canBecomeFirstResponder: Bool { true }
var hasText: Bool { true }
// (a terminal's keyboard: nothing corrected, capitalised or made smart)
var autocorrectionType: UITextAutocorrectionType = .no
var autocapitalizationType: UITextAutocapitalizationType = .none
var spellCheckingType: UITextSpellCheckingType = .no
var smartQuotesType: UITextSmartQuotesType = .no
var smartDashesType: UITextSmartDashesType = .no
var smartInsertDeleteType: UITextSmartInsertDeleteType = .no
var keyboardType: UIKeyboardType = .asciiCapable
func insertText(_ text: String) {
model?.typed(text)
}
func deleteBackward() {
model?.key("BACKSPACE")
}
override var keyCommands: [UIKeyCommand]? {
[
(UIKeyCommand.inputUpArrow, "UP"), (UIKeyCommand.inputDownArrow, "DOWN"),
(UIKeyCommand.inputLeftArrow, "LEFT"), (UIKeyCommand.inputRightArrow, "RIGHT"),
(UIKeyCommand.inputEscape, "ESCAPE"), ("\t", "TAB"),
].map { input, name in
let c = UIKeyCommand(input: input, modifierFlags: [], action: #selector(keyCommand(_:)))
c.wantsPriorityOverSystemBehavior = true
c.title = name
return c
}
}
@objc private func keyCommand(_ c: UIKeyCommand) {
guard let name = c.title.isEmpty ? nil : c.title else { return }
model?.key(name)
}
}
+44
View File
@@ -0,0 +1,44 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright (C) 2026 Neo-Desktop
#
# The iOS app's Xcode project, as text: xcodegen generate (in ios/DModem)
# makes DModem.xcodeproj. It needs build-apple/DModemEngine.xcframework
# (ios/build-native.sh) and the shared Kotlin's XCFramework
# (./gradlew :shared:assembleDModemSharedXCFramework).
name: DModem
options:
bundleIdPrefix: com.neodesktop
deploymentTarget:
iOS: "16.0"
packages:
DModemKit:
path: ../DModemKit
targets:
DModem:
type: application
platform: iOS
sources: [Sources]
dependencies:
- package: DModemKit
- framework: ../../shared/build/XCFrameworks/release/DModemShared.xcframework
embed: false
info:
path: Sources/Info.plist
properties:
CFBundleDisplayName: D-Modem
CFBundleShortVersionString: "0.1"
UILaunchScreen: {}
UISupportedInterfaceOrientations: [UIInterfaceOrientationPortrait, UIInterfaceOrientationLandscapeLeft, UIInterfaceOrientationLandscapeRight]
# the modem's call goes on in the background: its speaker (or quiet) keeps the app's audio running
UIBackgroundModes: [audio]
NSLocalNetworkUsageDescription: "D-Modem calls another phone with the app on this network, and SIP servers on it."
NSBonjourServices: [_dmodem._tcp]
settings:
base:
PRODUCT_BUNDLE_IDENTIFIER: com.neodesktop.dmodem
PRODUCT_NAME: DModem
SWIFT_VERSION: "5.9"
TARGETED_DEVICE_FAMILY: "1,2"
# (the engine is C++; SystemDNS.c's res_ninit is libresolv's)
OTHER_LDFLAGS: ["-lc++", "-lresolv"]
SWIFT_OBJC_BRIDGING_HEADER: Sources/DModem-Bridging-Header.h
+5
View File
@@ -7,6 +7,8 @@
// transfers (X/Y/ZMODEM, Kermit), PPP, fax, the line to another phone,
// and the I/O they're on (io/). The Android app
// has its JVM side; the iOS app its framework (iOS devices, simulator).
import org.jetbrains.kotlin.gradle.plugin.mpp.apple.XCFramework
plugins {
alias(libs.plugins.kotlin.multiplatform)
}
@@ -19,10 +21,13 @@ kotlin {
}
// (Kotlin/Native on Linux: the common tests run native here and in CI, as on iOS)
linuxX64()
// (the two as one XCFramework for the iOS app: ./gradlew :shared:assembleDModemSharedXCFramework)
val xcf = XCFramework("DModemShared")
listOf(iosArm64(), iosSimulatorArm64()).forEach {
it.binaries.framework {
baseName = "DModemShared"
isStatic = true
xcf.add(this)
}
}
@@ -0,0 +1,101 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.terminal
/**
* The terminal as the iOS app's Swift has it: a [TerminalEmulator] and its
* keys behind a few calls that pass plain values. Octets go both ways as
* Latin-1 strings (one character for each octet: Swift's Data to and from
* them is exact and cheap), the screen as [StyledRun]s.
*/
class TerminalBridge(cols: Int, rows: Int) {
private val replies = StringBuilder()
private val lock = kotlinx.atomicfu.locks.SynchronizedObject()
val emulator = TerminalEmulator(cols, rows, output = { b ->
kotlinx.atomicfu.locks.synchronized(lock) { for (x in b) replies.append((x.toInt() and 0xff).toChar()) }
})
private val keys = KeyEncoder()
private var look = RunLook()
/** the window's title (OSC 0/2), as the remote last set it */
var title = ""
private set
init {
emulator.listener = object : TerminalEmulator.Listener {
override fun onTitle(title: String) { this@TerminalBridge.title = title }
}
}
val cols: Int get() = emulator.cols
val rows: Int get() = emulator.rows
val cursorX: Int get() = emulator.cursorX
val cursorY: Int get() = emulator.cursorY
val cursorVisible: Boolean get() = emulator.cursorVisible
/** changes with each change to the screen: redraw when it does */
val revision: Long get() = emulator.revision
/** the remote's octets (Latin-1, one character each) onto the screen */
fun feed(latin1: String) {
val b = ByteArray(latin1.length) { latin1[it].code.toByte() }
emulator.append(b, b.size)
}
/** what the terminal answers the remote (cursor reports, its identity …), as octets in Latin-1; taken */
fun takeReplies(): String = kotlinx.atomicfu.locks.synchronized(lock) {
replies.toString().also { replies.setLength(0) }
}
/** a row (0: the screen's top) as runs */
fun runs(row: Int): List<StyledRun> = emulator.runs(row, look)
/** the screen's background, the theme's (ARGB) */
val background: Int get() = look.theme.bgArgb
val cursorColor: Int get() = look.theme.cursorArgb
fun resize(cols: Int, rows: Int) = emulator.resize(cols, rows)
/** the theme ([TermTheme.ALL]'s ids), bold as bright, and the character set (UTF8, CP437, LATIN1) */
fun setLook(themeId: String, boldBright: Boolean, iceColors: Boolean, charset: String) {
look = RunLook(TermTheme.byId(themeId), boldBright, iceColors)
emulator.decoder.charset = TermCharset.entries.firstOrNull { it.name == charset } ?: TermCharset.UTF8
}
/** text typed: its octets in the character set (Latin-1, one character each); a newline as Enter */
fun typed(text: String, ctrl: Boolean = false, alt: Boolean = false): String {
val out = StringBuilder()
var i = 0
while (i < text.length) {
val c = text[i]
val cp = if (c.isHighSurrogate() && i + 1 < text.length) {
i++
0x10000 + ((c.code - 0xd800) shl 10) + (text[i].code - 0xdc00)
} else {
c.code
}
i++
if (cp == '\n'.code || cp == '\r'.code) {
out.append(keys.key(Key.ENTER, emulator.appCursorKeys, alt = alt))
continue
}
out.append(keys.char(cp, alt, ctrl))
}
return octets(out.toString())
}
/** a key that isn't a character ([Key]'s names: UP, ESCAPE, F1 …) as octets in Latin-1; "" for no such key */
fun key(name: String, shift: Boolean = false, alt: Boolean = false, ctrl: Boolean = false): String {
val k = Key.entries.firstOrNull { it.name == name } ?: return ""
if (k == Key.BACKSPACE) return keys.backspace.code.toChar().toString()
return octets(keys.key(k, emulator.appCursorKeys, shift, alt, ctrl))
}
/** the screen's text from (row, col) to (row2, col2), for copying */
fun text(row: Int, col: Int, row2: Int, col2: Int): String = emulator.text(row, col, row2, col2)
private fun octets(s: String): String {
val b = emulator.decoder.charset.encode(s)
return CharArray(b.size) { (b[it].toInt() and 0xff).toChar() }.concatToString()
}
}
@@ -0,0 +1,53 @@
// 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.assertTrue
/** The terminal as Swift has it: octets as Latin-1 strings each way, rows as runs, keys, replies. */
class TerminalBridgeTest {
@Test
fun octetsInScreenOutRepliesBack() {
val t = TerminalBridge(20, 4)
val r0 = t.revision
t.feed("hello\r\nworld")
assertTrue(t.revision != r0)
assertEquals("hello", t.runs(0).joinToString("") { it.text }.trimEnd())
assertEquals(1, t.cursorY)
assertEquals(5, t.cursorX)
// a cursor position report asked for: the answer to send back
t.feed("\u001b[6n")
assertEquals("\u001b[2;6R", t.takeReplies())
assertEquals("", t.takeReplies())
// the title
t.feed("\u001b]2;BBS\u0007")
assertEquals("BBS", t.title)
}
@Test
fun typedAndKeys() {
val t = TerminalBridge(20, 4)
assertEquals("a\r", t.typed("a\n"))
assertEquals("\u0003", t.typed("c", ctrl = true))
// UTF-8's octets, one character each
assertEquals("é", t.typed("é"))
assertEquals("\u001b[A", t.key("UP"))
assertEquals("\u007f", t.key("BACKSPACE"))
assertEquals("", t.key("NOPE"))
// application cursor keys, as the remote asks
t.feed("\u001b[?1h")
assertEquals("\u001bOA", t.key("UP"))
}
@Test
fun cp437ForTheBbs() {
val t = TerminalBridge(10, 2)
t.setLook("vga", boldBright = true, iceColors = false, charset = "CP437")
// 0xdb: CP437's full block
t.feed("Û")
assertEquals("█", t.runs(0)[0].text.take(1))
assertEquals("Û", t.typed("█"))
}
}