diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml index 30e5dde..9c24854 100644 --- a/.github/workflows/android.yml +++ b/.github/workflows/android.yml @@ -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: | diff --git a/.github/workflows/apple.yml b/.github/workflows/apple.yml index d519630..e79e6a4 100644 --- a/.github/workflows/apple.yml +++ b/.github/workflows/apple.yml @@ -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 diff --git a/.gitignore b/.gitignore index 7a5c7e5..15bf8fe 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,6 @@ captures/ .kotlin/ /build-apple/ /build-fallback/ + +# the iOS app's generated project +ios/DModem/DModem.xcodeproj/ diff --git a/README.md b/README.md index 9b33a1b..acbef41 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/ios/DModem/Sources/AppModel.swift b/ios/DModem/Sources/AppModel.swift new file mode 100644 index 0000000..d3fdf8c --- /dev/null +++ b/ios/DModem/Sources/AppModel.swift @@ -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() } + } +} diff --git a/ios/DModem/Sources/DModem-Bridging-Header.h b/ios/DModem/Sources/DModem-Bridging-Header.h new file mode 100644 index 0000000..ffc7009 --- /dev/null +++ b/ios/DModem/Sources/DModem-Bridging-Header.h @@ -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" diff --git a/ios/DModem/Sources/DModemApp.swift b/ios/DModem/Sources/DModemApp.swift new file mode 100644 index 0000000..7aae823 --- /dev/null +++ b/ios/DModem/Sources/DModemApp.swift @@ -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") } + } + } + } +} diff --git a/ios/DModem/Sources/HomeView.swift b/ios/DModem/Sources/HomeView.swift new file mode 100644 index 0000000..f0c8499 --- /dev/null +++ b/ios/DModem/Sources/HomeView.swift @@ -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 = "" + } +} diff --git a/ios/DModem/Sources/LogView.swift b/ios/DModem/Sources/LogView.swift new file mode 100644 index 0000000..7f4c8ee --- /dev/null +++ b/ios/DModem/Sources/LogView.swift @@ -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")) + } + } +} diff --git a/ios/DModem/Sources/ModemAudio.swift b/ios/DModem/Sources/ModemAudio.swift new file mode 100644 index 0000000..fbd1862 --- /dev/null +++ b/ios/DModem/Sources/ModemAudio.swift @@ -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) { + 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.. +#include +#include +#include +#include + +#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; +} diff --git a/ios/DModem/Sources/SystemDNS.h b/ios/DModem/Sources/SystemDNS.h new file mode 100644 index 0000000..660e792 --- /dev/null +++ b/ios/DModem/Sources/SystemDNS.h @@ -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 diff --git a/ios/DModem/Sources/SystemDNS.swift b/ios/DModem/Sources/SystemDNS.swift new file mode 100644 index 0000000..3e8de3f --- /dev/null +++ b/ios/DModem/Sources/SystemDNS.swift @@ -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) + } +} diff --git a/ios/DModem/Sources/TerminalModel.swift b/ios/DModem/Sources/TerminalModel.swift new file mode 100644 index 0000000..ec5b6ee --- /dev/null +++ b/ios/DModem/Sources/TerminalModel.swift @@ -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) + } +} diff --git a/ios/DModem/Sources/TerminalScreen.swift b/ios/DModem/Sources/TerminalScreen.swift new file mode 100644 index 0000000..c58f687 --- /dev/null +++ b/ios/DModem/Sources/TerminalScreen.swift @@ -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.. 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) + } +} diff --git a/ios/DModem/project.yml b/ios/DModem/project.yml new file mode 100644 index 0000000..db06e2a --- /dev/null +++ b/ios/DModem/project.yml @@ -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 diff --git a/shared/build.gradle.kts b/shared/build.gradle.kts index a47ed73..f26b783 100644 --- a/shared/build.gradle.kts +++ b/shared/build.gradle.kts @@ -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) } } diff --git a/shared/src/commonMain/kotlin/com/neodesktop/dmodem/terminal/TerminalBridge.kt b/shared/src/commonMain/kotlin/com/neodesktop/dmodem/terminal/TerminalBridge.kt new file mode 100644 index 0000000..0bbf376 --- /dev/null +++ b/shared/src/commonMain/kotlin/com/neodesktop/dmodem/terminal/TerminalBridge.kt @@ -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 = 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() + } +} diff --git a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/terminal/TerminalBridgeTest.kt b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/terminal/TerminalBridgeTest.kt new file mode 100644 index 0000000..da04fa6 --- /dev/null +++ b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/terminal/TerminalBridgeTest.kt @@ -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("█")) + } +}