Comments for every function: the last batch; CI checks it

The UI tests, Gradle's script, the iOS app and the native test hosts
(batch 6 of 8, comment lines only) and the checker's own. Every
function in the app is now documented; android.yml's docs job runs
tools/doc_check.py first.

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-27 08:23:54 +00:00
1 parent ebbb5eb4a4
commit 9915decc6d
51 files changed
+240

No files matched your search

+12
View File
@@ -1,3 +1,4 @@
# docs: every function documented (tools/doc_check.py).
# build: the APK (all four ABIs), the unit tests and lint.
# native: the native engine on the runner against a dmodemd over loopback
# SIP (native-test).
@@ -18,6 +19,17 @@ env:
CMAKE_VERSION: "3.31.6"
jobs:
docs:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
token: ${{ secrets.DMODEM_RE_TOKEN || github.token }}
- name: Every function documented
run: python3 tools/doc_check.py
build:
runs-on: ubuntu-24.04
steps:
@@ -41,6 +41,7 @@ class PromptHostTest {
@get:Rule
val compose = createAndroidComposeRule<MainActivity>()
/** [p] asked of the terminal's prompts on another thread; its answer, once there is one */
private fun asked(p: Prompt): AtomicReference<Answer> {
val got = AtomicReference<Answer>()
Thread { got.set(Terminal.prompts.ask(p, this)) }.start()
@@ -51,10 +52,12 @@ class PromptHostTest {
@After
fun tearDown() = Terminal.prompts.cancel(this)
/** (up to 15 s) until some node shows [text] */
private fun waitFor(text: String) {
compose.waitUntil(15_000) { compose.onAllNodesWithText(text, substring = true).fetchSemanticsNodes().isNotEmpty() }
}
/** the dialog on screen drawn into build/screens/[name].png */
private fun shotDialog(name: String) {
compose.waitForIdle()
val bmp = compose.onNode(isDialog()).captureToImage().asAndroidBitmap()
@@ -69,6 +72,7 @@ class PromptHostTest {
return r.get()
}
/** an unknown host's key is shown, and "Accept and keep" accepts and remembers it */
@Test
fun anUnknownHostsKey() {
val got = asked(Prompt.HostKey("Unknown host", "bbs.example.org", 2222, "ssh-ed25519", "SHA256:Ng3jZbE6x1yJr9q0sJ4Ylm5o2p8Qe7Rk0vT1uW2xY3z", null))
@@ -79,6 +83,7 @@ class PromptHostTest {
assertTrue(a.accepted && a.remember)
}
/** a changed host key accepted "Once" connects but isn't kept */
@Test
fun aChangedHostKeyOnlyOnce() {
val got = asked(
@@ -95,6 +100,7 @@ class PromptHostTest {
assertFalse("not kept", a.remember)
}
/** the broker ignores an answer to a question other than the one being asked */
@Test
fun anAnswerToAnotherQuestionIsIgnored() {
val b = PromptBroker()
@@ -29,6 +29,7 @@ class ScreenshotsTest {
@get:Rule
val compose = createAndroidComposeRule<MainActivity>()
/** the whole screen drawn into build/screens/[name].png */
private fun shot(name: String) {
compose.waitForIdle()
val bmp = compose.onRoot().captureToImage().asAndroidBitmap()
@@ -36,6 +37,7 @@ class ScreenshotsTest {
File(dir, "$name.png").outputStream().use { bmp.compress(Bitmap.CompressFormat.PNG, 100, it) }
}
/** home, terminal, dial, settings and log drawn, with some modem text in them */
@Test
fun screens() {
// some text from a "modem" for the console and the terminal
@@ -53,6 +53,7 @@ import org.robolectric.annotation.GraphicsMode
import java.io.File
import java.net.ServerSocket
/** [bmp] saved as build/screens/[name].png */
private fun saveShot(bmp: Bitmap, name: String) {
File("build/screens").mkdirs()
File("build/screens/$name.png").outputStream().use { bmp.compress(Bitmap.CompressFormat.PNG, 100, it) }
@@ -71,6 +72,7 @@ class SshSessionPanelTest {
private lateinit var server: SshServer
/** a local SSH server that allows any key, forwards and the agent; the terminal with no SSH files */
@Before
fun setUp() {
SshSecurity.ensure()
@@ -87,12 +89,14 @@ class SshSessionPanelTest {
Terminal.init(ctx, PlainBox())
}
/** the SSH sessions closed and the server stopped */
@After
fun tearDown() {
Terminal.sessions.value.filter { it.kind != TerminalSession.Kind.MODEM }.forEach { Terminal.close(it) }
server.stop(true)
}
/** an entry's local, SOCKS and remote forwards and its agent come up, and the session's panel shows them */
@Test
fun forwardsAndTheAgent() {
val ctx = ApplicationProvider.getApplicationContext<Context>()
@@ -144,6 +148,7 @@ class SshToolsDialogsTest {
@get:Rule
val compose = createComposeRule()
/** the terminal with no SSH files */
@Before
fun setUp() {
SshSecurity.ensure()
@@ -152,11 +157,13 @@ class SshToolsDialogsTest {
Terminal.init(ctx, PlainBox())
}
/** the dialog on screen saved as [name] */
private fun shot(name: String) {
compose.waitForIdle()
saveShot(compose.onNode(isDialog()).captureToImage().asAndroidBitmap(), name)
}
/** an entry's forward removed in its dialog is gone from the saved entry, and agent forwarding asks to confirm */
@Test
fun anEntrysForwardsAndAgent() {
var saved: DialEntry? = null
@@ -173,6 +180,7 @@ class SshToolsDialogsTest {
assertTrue(saved!!.agentForwarding && saved!!.agentConfirm)
}
/** a remote forward from the forward dialog's fields, to localhost by default */
@Test
fun aForwardMade() {
var made: ForwardSpec? = null
@@ -186,6 +194,7 @@ class SshToolsDialogsTest {
assertEquals(ForwardSpec(ForwardSpec.Type.REMOTE, null, 2222, "localhost", 22), made)
}
/** a key's details show its kind and size */
@Test
fun aKeysDetails() {
val k = Terminal.keys.generate(KeyKind.ED25519, "pixel", comment = "alice@pixel")
@@ -194,6 +203,7 @@ class SshToolsDialogsTest {
shot("ssh-tools-key")
}
/** the export dialog's format can be switched to PuTTY .ppk */
@Test
fun anExportAsPutty() {
val k = Terminal.keys.generate(KeyKind.ED25519, "pixel", comment = "alice@pixel")
@@ -71,12 +71,18 @@ class SshUiTest {
private lateinit var inp: InputStream
private lateinit var out: OutputStream
private var exit: ExitCallback? = null
/** the client's keystrokes, read by the shell's thread */
override fun setInputStream(i: InputStream) { inp = i }
/** where the shell's output goes */
override fun setOutputStream(o: OutputStream) { out = o }
/** (nothing goes to stderr) */
override fun setErrorStream(e: OutputStream) {}
/** told when the input ends */
override fun setExitCallback(cb: ExitCallback) { exit = cb }
/** [s] written to the client and flushed */
private fun say(s: String) = synchronized(out) { out.write(s.toByteArray()); out.flush() }
private val prompt = "\u001b[1;32malice@raspberrypi\u001b[0m:\u001b[1;34m~ \u001b[0m$ "
/** a login banner, the client's TERM and size, the prompt; then a thread that echoes, edits and runs each line */
override fun start(channel: ChannelSession, env: Environment) {
val cols = env.env[Environment.ENV_COLUMNS]
say("Linux raspberrypi 6.12.25-v8+ #1 SMP PREEMPT aarch64\r\n\r\nLast login: Fri Oct 16 09:12:44 2026 from 192.168.1.20\r\n")
@@ -113,9 +119,11 @@ class SshUiTest {
exit?.onExit(0)
}.start()
}
/** (nothing to free: the thread ends with the input) */
override fun destroy(channel: ChannelSession) {}
}
/** a local SSH server taking alice's password, with [Shell]; the terminal with no SSH files */
@Before
fun setUp() {
SshSecurity.ensure()
@@ -131,12 +139,14 @@ class SshUiTest {
Terminal.init(ctx, PlainBox())
}
/** the SSH sessions closed and the server stopped */
@After
fun tearDown() {
Terminal.sessions.value.filter { it.kind != TerminalSession.Kind.MODEM }.forEach { Terminal.close(it) }
server.stop(true)
}
/** the whole screen drawn into build/screens/[name].png */
private fun shot(name: String) {
compose.waitForIdle()
val bmp = compose.onRoot().captureToImage().asAndroidBitmap()
@@ -147,6 +157,7 @@ class SshUiTest {
/** the bottom bar's item (not a heading of the same name) */
private fun tab(name: String) = compose.onNode(hasText(name) and isSelectable()).performClick()
/** (up to [ms]) until some node shows [t] */
private fun waitForText(t: String, ms: Long = 20_000) {
compose.waitUntil(ms) { compose.onAllNodesWithText(t, substring = true).fetchSemanticsNodes().isNotEmpty() }
}
@@ -165,9 +176,11 @@ class SshUiTest {
}
}.apply { isDaemon = true; start() }
/** the text on [s]'s screen, row by row */
private fun shell(s: TerminalSession) =
synchronized(s.emulator) { (0 until s.emulator.rows).joinToString("\n") { s.emulator.line(it).text() } }
/** (up to 20 s) until [s]'s screen shows [text], or an error with what it shows */
private fun waitShell(s: TerminalSession, text: String) {
val end = System.currentTimeMillis() + 20_000
while (!shell(s).contains(text)) {
@@ -176,6 +189,7 @@ class SshUiTest {
}
}
/** an SSH entry logs in with the host key and password kept, gets its own tab, and offers to reconnect when the server goes */
@Test
fun sshFromTheDirectory() {
val ctx = ApplicationProvider.getApplicationContext<Context>()
@@ -22,6 +22,7 @@ class UsbPluggedTest {
@get:Rule
val compose = createComposeRule()
/** "Plugged in" names the modem once it's attached and says none again once it's detached */
@Test
fun followsPlugAndUnplug() {
val context = ApplicationProvider.getApplicationContext<android.content.Context>()
+7
View File
@@ -19,7 +19,9 @@ subprojects {
val dir = File(testRunDir, "${project.name}-$name")
if (this is Test) systemProperty("dmodem.testRunDir", dir.path)
val writers = java.util.concurrent.ConcurrentHashMap<String, java.io.Writer>()
/** [s] safe as a file name: other characters as _, at most 150 */
fun fileName(s: String) = s.replace(Regex("[^A-Za-z0-9._-]+"), "_").take(150)
/** the log [d]'s output goes to (its class's _class.log if it's no test), opened once */
fun writer(d: TestDescriptor): java.io.Writer {
val cls = d.className ?: d.parent?.className ?: "_run"
val key = if (d.className != null && d.name != d.className) "${fileName(cls.substringAfterLast('.'))}/${fileName(d.name)}.log"
@@ -30,6 +32,7 @@ subprojects {
}
doFirst { dir.deleteRecursively() }
addTestOutputListener(object : TestOutputListener {
/** what a test printed, into its log as it comes */
override fun onOutput(d: TestDescriptor, e: TestOutputEvent) {
val w = writer(d)
synchronized(w) {
@@ -39,8 +42,11 @@ subprojects {
}
})
addTestListener(object : TestListener {
/** (nothing before a suite) */
override fun beforeSuite(suite: TestDescriptor) {}
/** (nothing before a test) */
override fun beforeTest(d: TestDescriptor) {}
/** a failed test's stack traces at the end of its log */
override fun afterTest(d: TestDescriptor, r: TestResult) {
// (a failure's stack trace at the end of its log)
if (r.resultType == TestResult.ResultType.FAILURE) {
@@ -52,6 +58,7 @@ subprojects {
}
}
}
/** at the run's end the logs closed, and the task's folder removed if nothing failed (else where it is said) */
override fun afterSuite(suite: TestDescriptor, r: TestResult) {
if (suite.parent != null) return
writers.values.forEach { runCatching { it.close() } }
+6
View File
@@ -39,6 +39,7 @@ final class AppModel: ObservableObject {
private var typedLine = ""
private var lastDial = ""
/// the settings kept, and the session's changes, data, speaker and sound and the phone's call screen wired to it
init() {
settings = store.settings
jobs = JobsModel(session: session) { [store] in store.settings }
@@ -76,6 +77,7 @@ final class AppModel: ObservableObject {
}
}
/// a RING: the phone's call screen rings (with the caller's number), and a fax is answered if it's set to (not while a job runs)
private func ring() {
if jobs.running { return }
calls.ringing(from: callerId)
@@ -123,6 +125,7 @@ final class AppModel: ObservableObject {
var connectLabel: String { status.link == .online ? ConnectInfo.label(console) : "" }
/// the modem started with the settings: the background audio, the peer line if there's one, then the session
func start() {
error = nil
audio.enabled = settings.speaker
@@ -145,6 +148,7 @@ final class AppModel: ObservableObject {
watchPeer(s.peer && !s.noLine)
}
/// the modem, the peer line and the background audio stopped
func stop() {
Task.detached { [session, audio, peer] in
session.stop()
@@ -172,6 +176,7 @@ final class AppModel: ObservableObject {
}
}
/// the modem's call hung up (off the main thread)
func hangUp() {
Task.detached { [session] in session.hangUp() }
}
@@ -179,6 +184,7 @@ final class AppModel: ObservableObject {
/// an AT command (Home's line)
func command(_ cmd: String) { session.command(cmd) }
/// the session's state copied in, and the call screen, the jobs and the audio told what changed
private func refresh() {
let wasOnline = status.link == .online
let wasRunning = run == .running
+9
View File
@@ -31,6 +31,7 @@ final class CallController: NSObject {
/// the ringing call turned down: its RINGs passed over until they stop
private var declined = false
/// a CallKit provider for one voice call at a time, by number or not, kept in Recents
override init() {
let c = CXProviderConfiguration()
c.supportsVideo = false
@@ -112,6 +113,7 @@ final class CallController: NSObject {
}
}
/// no RING for a while: a turned-down call's RINGs heeded again, and an unanswered ringing call reported missed
private func ringStopped() {
declined = false
guard let id = current, incoming, !answered else { return }
@@ -119,6 +121,7 @@ final class CallController: NSObject {
forget(id)
}
/// call [id] no longer the current one (if it still was)
private func forget(_ id: UUID) {
if current == id {
current = nil
@@ -128,15 +131,18 @@ final class CallController: NSObject {
}
extension CallController: CXProviderDelegate {
/// CallKit dropped its calls: none current
nonisolated func providerDidReset(_ provider: CXProvider) {
Task { @MainActor in self.current = nil }
}
/// a call the modem dials: reported connecting
nonisolated func provider(_ provider: CXProvider, perform action: CXStartCallAction) {
provider.reportOutgoingCall(with: action.callUUID, startedConnectingAt: nil)
action.fulfill()
}
/// the ringing call answered: the modem told to answer, unless the app answered it already
nonisolated func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) {
Task { @MainActor in
// (answered here already, a fax: nothing to tell the modem)
@@ -148,6 +154,7 @@ extension CallController: CXProviderDelegate {
action.fulfill()
}
/// the call ended: if by the user, the modem told (and a ringing call's RINGs passed over)
nonisolated func provider(_ provider: CXProvider, perform action: CXEndCallAction) {
Task { @MainActor in
let byUser = !self.endingOurselves
@@ -158,10 +165,12 @@ extension CallController: CXProviderDelegate {
action.fulfill()
}
/// the call's audio session active: [onAudio] told
nonisolated func provider(_ provider: CXProvider, didActivate audioSession: AVAudioSession) {
Task { @MainActor in self.onAudio?(true) }
}
/// the call's audio session gone: [onAudio] told
nonisolated func provider(_ provider: CXProvider, didDeactivate audioSession: AVAudioSession) {
Task { @MainActor in self.onAudio?(false) }
}
+1
View File
@@ -39,6 +39,7 @@ enum FaxDocuments {
throw Failure.unreadable("not a PDF, an image or text: \(url.lastPathComponent)")
}
/// each page of the PDF at [url] drawn to fill a fax page (no dithering)
private static func pdf(_ url: URL, fine: Bool) throws -> [FaxPage] {
guard let doc = CGPDFDocument(url as CFURL) else { throw Failure.unreadable("can't open the PDF") }
guard doc.numberOfPages > 0 else { return [] }
+1
View File
@@ -117,6 +117,7 @@ struct FaxView: View {
}
}
/// the received faxes listed again from the faxes folder
private func reload() { received = AppFolders.files(AppFolders.faxes) }
/// a picked file copied where the app may read it later (a picked one may only be read while open to us)
+3
View File
@@ -137,6 +137,7 @@ struct HomeView: View {
model.console.split(whereSeparator: \.isNewline).suffix(6).joined(separator: "\n")
}
/// a speed under its [label], in kbit/s from 1000 up
private func rate(_ label: String, _ bps: Int) -> some View {
VStack(alignment: .leading) {
Text(label).font(.caption)
@@ -145,11 +146,13 @@ struct HomeView: View {
}
}
/// the time from [since] to [now] as m:ss
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)
}
/// the typed AT command sent (AT put in front if it's missing), and the field cleared
private func sendAt() {
let c = at.trimmingCharacters(in: .whitespaces)
guard !c.isEmpty else { return }
+2
View File
@@ -56,6 +56,7 @@ struct InternetView: View {
.navigationTitle("Internet")
}
/// the dial-up's state: connected or its phase, and once connected its address, DNS, time up and bytes
@ViewBuilder private func status(_ s: DialUpJob.State) -> some View {
Text(s.running ? (s.connected ? "Connected" : s.phase) : "Disconnected").font(.headline)
if !s.connect.isEmpty { Text(s.connect).font(.callout.monospaced()).foregroundStyle(.secondary) }
@@ -71,6 +72,7 @@ struct InternetView: View {
if let e = s.ended, e != "disconnected" { Text(e).foregroundStyle(.red) }
}
/// [s] seconds as m:ss, or h:mm:ss from an hour
private func elapsed(_ s: Int) -> String {
s >= 3600 ? String(format: "%d:%02d:%02d", s / 3600, s / 60 % 60, s % 60) : String(format: "%d:%02d", s / 60, s % 60)
}
+9
View File
@@ -11,18 +11,22 @@ final class JobLink: NSObject, DteOut, LogOut, Changed, @unchecked Sendable {
private let session: ModemSession
private let onChange: @MainActor () -> Void
/// a job's link to [session], its changes to [onChange]
init(session: ModemSession, onChange: @escaping @MainActor () -> Void) {
self.session = session
self.onChange = onChange
}
/// the job's octets (Latin-1) to the modem's DTE: whether they went
func write(latin1: String) -> Bool {
guard let d = latin1.data(using: .isoLatin1) else { return false }
return session.send(d)
}
/// a line of the job's into the modem's log
func log(line: String) { session.engineLog(line) }
/// the job changed: [onChange] on the main thread
func changed() {
let f = onChange
Task { @MainActor in f() }
@@ -32,13 +36,17 @@ final class JobLink: NSObject, DteOut, LogOut, Changed, @unchecked Sendable {
/// a line for the log, from Kotlin
final class LogLink: NSObject, LogOut, @unchecked Sendable {
private let f: (String) -> Void
/// a link whose lines go to [f]
init(_ f: @escaping (String) -> Void) { self.f = f }
/// [line] to the function given
func log(line: String) { f(line) }
}
/// octets between Swift and Kotlin: Latin-1 text, a character an octet
enum Octets {
/// [d]'s octets as Latin-1 characters
static func latin1(_ d: Data) -> String { String(data: d, encoding: .isoLatin1) ?? "" }
/// [s]'s Latin-1 characters as octets (empty if any isn't Latin-1)
static func data(_ s: String) -> Data { s.data(using: .isoLatin1) ?? Data() }
}
@@ -53,6 +61,7 @@ enum AppFolders {
/// faxes received, as PDFs
static var faxes: URL { folder("Faxes") }
/// Documents/[name], made if it isn't there
private static func folder(_ name: String) -> URL {
let u = documents.appendingPathComponent(name, isDirectory: true)
try? FileManager.default.createDirectory(at: u, withIntermediateDirectories: true)
+14
View File
@@ -32,6 +32,7 @@ final class JobsModel: ObservableObject {
private var tunnel: UdpPacketTunnel?
private var sawOnline = false
/// jobs on [session], with the settings as [settings] gives them at each start
init(session: ModemSession, settings: @escaping () -> ModemSettings) {
self.session = session
self.settings = settings
@@ -52,6 +53,7 @@ final class JobsModel: ObservableObject {
session.claim { d in feed(Octets.latin1(d)) }
}
/// a link for a job, whose changes run [refresh] on this model
private func link(_ refresh: @escaping @MainActor (JobsModel) -> Void) -> JobLink {
JobLink(session: session) { [weak self] in
guard let self else { return }
@@ -77,6 +79,7 @@ final class JobsModel: ObservableObject {
return nil
}
/// the fax's pages drawn: the DTE lent and the fax sent, or why not in [faxError]
private func faxPagesReady(_ pages: Result<[FaxPage], Error>, number: String, settings s: ModemSettings) {
preparing = false
let l = link { $0.refreshFax() }
@@ -111,10 +114,13 @@ final class JobsModel: ObservableObject {
return nil
}
/// the fax call hung up
func cancelFax() { faxJob?.cancel() }
/// the last fax's outcome cleared (not while one's going)
func dismissFax() { if faxJob == nil { fax = nil; faxError = nil } }
/// the fax job's state copied in; once it's over, the DTE back with what it didn't read
private func refreshFax() {
guard let job = faxJob else { return }
fax = job.state
@@ -128,7 +134,9 @@ final class JobsModel: ObservableObject {
/// the protocols' names (ZMODEM …), and what each is called
static var protocols: [String] { TransferJob.companion.protocols }
/// what protocol [p] is called
static func label(_ p: String) -> String { TransferJob.companion.label(protocolName: p) }
/// whether protocol [p] takes a batch of files (else one at a time)
static func batch(_ p: String) -> Bool { TransferJob.companion.batch(protocolName: p) }
/// files received by [proto] into Documents/Received ([first]: what came that started it)
@@ -174,10 +182,13 @@ final class JobsModel: ObservableObject {
return nil
}
/// the transfer cancelled
func cancelTransfer() { transferJob?.cancel() }
/// the last transfer's outcome cleared (not while one's going)
func dismissTransfer() { if transferJob == nil { transfer = nil } }
/// the transfer's state copied in; once it's over, the DTE back with what it didn't read
private func refreshTransfer() {
guard let job = transferJob else { return }
transfer = job.state
@@ -220,11 +231,13 @@ final class JobsModel: ObservableObject {
return nil
}
/// the dial-up link hung up
func disconnectInternet() { dialUp?.disconnect() }
/// how long the link has been up (ms)
var upMs: Int64 { dialUp?.upMs ?? 0 }
/// the last dial-up's outcome cleared (not while one's going)
func dismissInternet() { if dialUp == nil { internet = nil } }
/// the modem's status changed: the link down when the call is
@@ -236,6 +249,7 @@ final class JobsModel: ObservableObject {
if sawOnline && !online && d.state.connected { d.lineDropped() }
}
/// the dial-up's state copied in; once it's over, the tunnel dropped and the DTE back with what it didn't read
private func refreshInternet() {
guard let job = dialUp else { return }
internet = job.state
+2
View File
@@ -21,6 +21,7 @@ final class ModemAudio: @unchecked Sendable {
private var running = false
private var gain: Float = 0
/// the speaker's player and the quiet's into the mixer, at the modem's 8000 Hz
init() {
engine.attach(player)
engine.attach(quiet)
@@ -60,6 +61,7 @@ final class ModemAudio: @unchecked Sendable {
}
}
/// the players and engine stopped and the session given up (others' audio told it may resume)
func end() {
lock.lock(); defer { lock.unlock() }
if !running { return }
+8
View File
@@ -38,6 +38,7 @@ final class PeerLineController: NSObject, NetServiceDelegate, @unchecked Sendabl
}
}
/// the line stopped, and no longer offered on the network
func stop() {
lock.lock()
let h = host
@@ -62,6 +63,7 @@ final class PeerLineController: NSObject, NetServiceDelegate, @unchecked Sendabl
return host?.lastError ?? error
}
/// this phone offered with Bonjour as taking calls on [port]
private func advertise(port: Int) {
let s = NetService(domain: "local.", type: PeerFinder.type, name: "D-Modem on \(UIDevice.current.name)", port: Int32(port))
s.delegate = self
@@ -79,26 +81,31 @@ final class PeerFinder: NSObject, NetServiceBrowserDelegate, NetServiceDelegate
private var resolving: [NetService] = []
private let found: (String, String) -> Void
/// a finder whose phones go to [found]
init(found: @escaping (String, String) -> Void) {
self.found = found
super.init()
browser.delegate = self
}
/// the network searched for phones taking calls
func start() { browser.searchForServices(ofType: Self.type, inDomain: "local.") }
/// the search stopped, and the ones still resolving
func stop() {
browser.stop()
resolving.forEach { $0.stop() }
resolving.removeAll()
}
/// a phone seen: its address looked up (for 5 s at most)
func netServiceBrowser(_ browser: NetServiceBrowser, didFind service: NetService, moreComing: Bool) {
service.delegate = self
resolving.append(service)
service.resolve(withTimeout: 5)
}
/// a phone's address found: to [found] as its name and host:port
func netServiceDidResolveAddress(_ sender: NetService) {
// (an IPv4 address of it, else its host name; its port)
let host = sender.addresses?.compactMap(Self.ipv4).first ?? sender.hostName
@@ -106,6 +113,7 @@ final class PeerFinder: NSObject, NetServiceBrowserDelegate, NetServiceDelegate
resolving.removeAll { $0 === sender }
}
/// a phone whose address couldn't be found: dropped
func netService(_ sender: NetService, didNotResolve errorDict: [String: NSNumber]) {
resolving.removeAll { $0 === sender }
}
+2
View File
@@ -141,6 +141,7 @@ private struct PeerSection: View {
.onDisappear(perform: stop)
}
/// phones taking calls on this network looked for, each address listed once
private func find() {
found = []
let f = PeerFinder { name, address in
@@ -151,6 +152,7 @@ private struct PeerSection: View {
f.start()
}
/// the looking stopped
private func stop() {
finder?.stop()
finder = nil
+1
View File
@@ -12,6 +12,7 @@
#include "SystemDNS.h"
/* see SystemDNS.h */
int dmodem_dns_servers(char *buf, int len)
{
struct __res_state st;
+1
View File
@@ -4,6 +4,7 @@ import Foundation
/// The phone's network's DNS servers (SystemDNS.c), for the engine's SIP.
enum SystemDNS {
/// the network's IPv4 DNS servers, as addresses ([] for none)
static func servers() -> [String] {
var buf = [CChar](repeating: 0, count: 512)
guard dmodem_dns_servers(&buf, Int32(buf.count)) > 0 else { return [] }
+2
View File
@@ -19,6 +19,7 @@ final class TerminalModel: ObservableObject {
/// to the modem
var send: ((Data) -> Void)?
/// the emulator set up for BBSes: CP437, bold as bright, the VGA colours
init() {
// (BBSes: CP437, bold as bright; the VGA colours)
bridge.setLook(themeId: "vga", boldBright: true, iceColors: false, charset: "CP437")
@@ -58,6 +59,7 @@ final class TerminalModel: ObservableObject {
/// a row's runs
func runs(_ row: Int) -> [StyledRun] { bridge.runs(row: Int32(row)) }
/// the emulator's Latin-1 output as octets to the modem (nothing if there's none)
private func out(_ latin1: String) {
guard !latin1.isEmpty, let d = latin1.data(using: .isoLatin1) else { return }
send?(d)
+7
View File
@@ -43,6 +43,7 @@ struct CellMetrics {
let width: CGFloat
let height: CGFloat
/// the monospaced system font at [fontSize], and its "M"'s width and line height rounded up
init(fontSize: Double) {
font = UIFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
width = ceil(("M" as NSString).size(withAttributes: [.font: font]).width)
@@ -107,6 +108,7 @@ private struct ExtraKeys: View {
.background(.bar)
}
/// a bordered key showing [label] that runs [action]
private func key(_ label: String, _ action: @escaping () -> Void) -> some View {
Button(action: action) { Text(label).frame(minWidth: 32, minHeight: 32) }
.buttonStyle(.bordered)
@@ -119,12 +121,14 @@ struct KeyInput: UIViewRepresentable {
let model: TerminalModel
@Binding var focused: Bool
/// the view, typing into [model]
func makeUIView(context: Context) -> KeyInputView {
let v = KeyInputView()
v.model = model
return v
}
/// the view's model kept, and the keyboard brought up once it's [focused]
func updateUIView(_ v: KeyInputView, context: Context) {
v.model = model
if focused && !v.isFirstResponder {
@@ -149,10 +153,12 @@ final class KeyInputView: UIView, UIKeyInput {
var smartInsertDeleteType: UITextSmartInsertDeleteType = .no
var keyboardType: UIKeyboardType = .asciiCapable
/// the keyboard's text to the terminal
func insertText(_ text: String) {
model?.typed(text)
}
/// the keyboard's delete as the terminal's BACKSPACE
func deleteBackward() {
model?.key("BACKSPACE")
}
@@ -170,6 +176,7 @@ final class KeyInputView: UIView, UIKeyInput {
}
}
/// a hardware key (named in its command's title) to the terminal
@objc private func keyCommand(_ c: UIKeyCommand) {
guard let name = c.title.isEmpty ? nil : c.title else { return }
model?.key(name)
+3
View File
@@ -76,6 +76,7 @@ struct TransferView: View {
}
}
/// the transfer: which way or how it ended, the file and how far, files done, blocks resent, and Cancel or Dismiss
@ViewBuilder private func progress(_ t: TransferState) -> some View {
Section {
let p = t.progress
@@ -101,7 +102,9 @@ struct TransferView: View {
}
}
/// [n] bytes as a file size (KB, MB …)
private func bytes(_ n: Int64) -> String { ByteCountFormatter.string(fromByteCount: n, countStyle: .file) }
/// the received files listed again from Documents/Received
private func reload() { received = AppFolders.files(AppFolders.received) }
}
+1
View File
@@ -37,6 +37,7 @@ final class VpnTunnel: NSObject, TunnelStarter, @unchecked Sendable {
/// (whether it started, set by the task the start waits for)
private final class Started: @unchecked Sendable { var ok = false }
/// the packet tunnel stopped (if it was started)
func stop() {
manager?.connection.stopVPNTunnel()
manager = nil
@@ -14,6 +14,7 @@ final class PacketTunnelProvider: NEPacketTunnelProvider {
private let lock = NSLock()
private var running = false
/// the tunnel up with the app's address, DNS and MTU, all IPv4 routed to it, and the packets passed to and from the app's port
override func startTunnel(options: [String: NSObject]?, completionHandler: @escaping (Error?) -> Void) {
guard let o = options, let address = o["address"] as? String, let port = (o["port"] as? NSNumber)?.uint16Value else {
completionHandler(NSError(domain: "DModemTunnel", code: 1, userInfo: [NSLocalizedDescriptionKey: "start it from D-Modem's Internet screen"]))
@@ -49,6 +50,7 @@ final class PacketTunnelProvider: NEPacketTunnelProvider {
}
}
/// the passing stopped and the socket to the app closed
override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
lock.lock()
running = false
@@ -61,6 +63,7 @@ final class PacketTunnelProvider: NEPacketTunnelProvider {
private var isRunning: Bool { lock.lock(); defer { lock.unlock() }; return running }
/// [d] as one datagram to the app's port on the loopback
private func sendToApp(_ d: Data) {
var to = app
d.withUnsafeBytes { p in
@@ -15,6 +15,7 @@ public final class DTE: @unchecked Sendable {
private var reader: Thread?
private var handler: ((Data) -> Void)?
/// the DTE on the modem's end [fd] (closed with it)
init(fd: Int32) {
self.fd = fd
}
@@ -62,6 +63,7 @@ public final class DTE: @unchecked Sendable {
}
}
/// [text] to the modem as UTF-8; false once it's gone
@discardableResult
public func write(_ text: String) -> Bool { write(Data(text.utf8)) }
@@ -82,5 +84,6 @@ public final class DTE: @unchecked Sendable {
}
}
/// closed with the last reference (the modem stops)
deinit { close() }
}
@@ -14,6 +14,7 @@ public struct ModemStatus: Equatable, Sendable {
public var txRate = 0
public var rxRate = 0
/// a status as given (on hook and idle by default)
public init(link: Link = .idle, offHook: Bool = false, txRate: Int = 0, rxRate: Int = 0) {
self.link = link
self.offHook = offHook
@@ -39,12 +40,15 @@ public struct EngineConfig: Sendable {
public var peer = false
public var peerLeadMs = 100
/// the defaults: SIP on 5060, not listening, T.38 on
public init() {}
}
/// what the engine tells, from its threads
public protocol EngineListener: AnyObject {
/// a line of the engine's log (its newline gone)
func engineLog(_ line: String)
/// the call's state changed: link, hook, rates
func engineStatus(_ status: ModemStatus)
/// the modem stopped: 0 asked for (or the DTE closed), -1 an error
func engineExited(_ result: Int)
@@ -57,8 +61,11 @@ public protocol EngineListener: AnyObject {
}
public extension EngineListener {
/// (no peer line taken: its samples closed)
func engineLine(caller: Bool, dial: String, fd: Int32) { close(fd) }
/// (the speaker ignored)
func engineSpeaker(_ level: Int) {}
/// (the sound ignored)
func engineSound(_ pcm: UnsafeBufferPointer<Int16>) {}
}
@@ -80,6 +87,7 @@ public final class Engine: @unchecked Sendable {
return _listener
}
/// the engine's callbacks set once, each to the listener of the moment
private init() {
var cb = dmodem_callbacks()
// (one engine, one Engine: the callbacks find it through this, not a context)
@@ -39,6 +39,7 @@ public final class ModemSession: EngineListener, @unchecked Sendable {
private let engine: Engine
/// a session on [engine] (the process's one by default), stopped
public init(engine: Engine = .shared) {
self.engine = engine
}
@@ -101,6 +102,7 @@ public final class ModemSession: EngineListener, @unchecked Sendable {
return d?.write(data) ?? false
}
/// an AT command, its CR added, to the modem; false if it's off
@discardableResult
public func command(_ cmd: String) -> Bool { send(Data((cmd + "\r").utf8)) }
@@ -134,6 +136,7 @@ public final class ModemSession: EngineListener, @unchecked Sendable {
/// whether a job has the DTE
public var claimed: Bool { lock.lock(); defer { lock.unlock() }; return claimant != nil }
/// what the modem said: to the job that has the DTE, else onto the console and to [onData]
private func received(_ data: Data) {
lock.lock()
if let c = claimant {
@@ -151,15 +154,18 @@ public final class ModemSession: EngineListener, @unchecked Sendable {
changed()
}
/// [error] set, and [onChange] told
private func setError(_ e: String) {
lock.lock(); _error = e; lock.unlock()
changed()
}
/// [onChange] told
private func changed() { onChange?() }
// EngineListener
/// the engine's line kept in the log (the last [logMax] of them)
public func engineLog(_ line: String) {
lock.lock()
_log.append(line)
@@ -168,11 +174,13 @@ public final class ModemSession: EngineListener, @unchecked Sendable {
changed()
}
/// the engine's status kept
public func engineStatus(_ status: ModemStatus) {
lock.lock(); _status = status; lock.unlock()
changed()
}
/// the modem stopped by itself: stopped, and an error if it failed while it ran
public func engineExited(_ result: Int) {
lock.lock()
let wasRunning = _run == .running && dte != nil
@@ -183,6 +191,7 @@ public final class ModemSession: EngineListener, @unchecked Sendable {
changed()
}
/// a peer line's call: to [onLine]; with no line, failed as nothing plugged in (closed either way without a handler)
public func engineLine(caller: Bool, dial: String, fd: Int32) {
lock.lock(); let none = noLine; lock.unlock()
if none {
@@ -194,7 +203,9 @@ public final class ModemSession: EngineListener, @unchecked Sendable {
if let h = onLine { h(caller, dial, fd) } else { close(fd) }
}
/// the speaker's level to [onSpeaker]
public func engineSpeaker(_ level: Int) { onSpeaker?(level) }
/// the line's sound to [onSound]
public func engineSound(_ pcm: UnsafeBufferPointer<Int16>) { onSound?(pcm) }
}
@@ -48,6 +48,7 @@ public struct ModemSettings: Codable, Equatable, Sendable {
public var ispScript = ""
public var ispInit = ""
/// the defaults
public init() {}
/// the settings' secrets, kept apart from the rest (the Keychain), by name
@@ -140,6 +141,7 @@ public final class SettingsStore: @unchecked Sendable {
private let key: String
private let secrets: SecretStore
/// settings kept under [key] in [defaults], their secrets in [secrets]
public init(defaults: UserDefaults = .standard, key: String = "modemSettings", secrets: SecretStore = defaultSecrets()) {
self.defaults = defaults
self.key = key
@@ -20,13 +20,16 @@ public final class MemorySecrets: SecretStore, @unchecked Sendable {
private let lock = NSLock()
private var values: [String: String] = [:]
/// none yet
public init() {}
/// the secret named [key], nil when there's none
public func get(_ key: String) -> String? {
lock.lock(); defer { lock.unlock() }
return values[key]
}
/// [value] kept under [key] (empty: removed)
public func set(_ key: String, _ value: String) {
lock.lock(); defer { lock.unlock() }
values[key] = value.isEmpty ? nil : value
@@ -40,16 +43,19 @@ public final class MemorySecrets: SecretStore, @unchecked Sendable {
public final class KeychainSecrets: SecretStore, @unchecked Sendable {
private let service: String
/// the Keychain's items under [service]
public init(service: String = "com.neodesktop.dmodem") {
self.service = service
}
/// the Keychain query for [key]'s generic password under [service]
private func query(_ key: String) -> [String: Any] {
[kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: key]
}
/// the secret named [key] from the Keychain, nil when there's none (or it can't be read)
public func get(_ key: String) -> String? {
var q = query(key)
q[kSecReturnData as String] = true
@@ -59,6 +65,7 @@ public final class KeychainSecrets: SecretStore, @unchecked Sendable {
return String(data: d, encoding: .utf8)
}
/// [value] kept under [key], updated or added, this device only (empty: removed)
public func set(_ key: String, _ value: String) {
let q = query(key)
if value.isEmpty {
@@ -24,15 +24,21 @@ final class DModemKitTests: XCTestCase {
var dial = ""
var fd: Int32 = -1
let lock = NSLock()
/// a listener passing the engine's news on to [s], but for its peer lines
init(_ s: ModemSession) { session = s }
/// the log line to the session
func engineLog(_ line: String) { session.engineLog(line) }
/// the status to the session
func engineStatus(_ status: ModemStatus) { session.engineStatus(status) }
/// the exit to the session
func engineExited(_ result: Int) { session.engineExited(result) }
/// the peer line's dial and samples kept for the test (not closed)
func engineLine(caller: Bool, dial: String, fd: Int32) {
lock.lock(); self.dial = dial; self.fd = fd; lock.unlock()
}
}
/// a session on a peer line starts, answers AT commands, logs and changes, ignores a second start, and stops
func testASessionOnAPeerLine() {
signal(SIGPIPE, SIG_IGN)
let session = ModemSession()
@@ -58,6 +64,7 @@ final class DModemKitTests: XCTestCase {
XCTAssertFalse(Engine.shared.running)
}
/// a dial is handed to the listener with its number, BUSY comes back for a busy far end, and closing the DTE stops the modem
func testADialHandedToTheApp() throws {
signal(SIGPIPE, SIG_IGN)
let session = ModemSession()
@@ -83,6 +90,7 @@ final class DModemKitTests: XCTestCase {
Engine.shared.stop()
}
/// a session's dial on a peer line goes to [ModemSession.onLine], and the line gone ends it
func testThePeerLineGoesToTheApp() {
signal(SIGPIPE, SIG_IGN)
let session = ModemSession()
@@ -105,6 +113,7 @@ final class DModemKitTests: XCTestCase {
session.stop()
}
/// the DTE lent to a job gets all the modem says (one job at a time, none while it's off), and its leftover goes back to the terminal
func testTheDteLentToAJob() {
signal(SIGPIPE, SIG_IGN)
let session = ModemSession()
@@ -134,6 +143,7 @@ final class DModemKitTests: XCTestCase {
session.stop()
}
/// with no line, the modem starts without a SIP account, dials get NO DIALTONE, and the setting is kept
func testNoLine() {
signal(SIGPIPE, SIG_IGN)
let session = ModemSession()
@@ -155,6 +165,7 @@ final class DModemKitTests: XCTestCase {
XCTAssertEqual(try JSONDecoder().decode(ModemSettings.self, from: JSONEncoder().encode(settings)).line, .none)
}
/// without a SIP account (on a SIP line) the session doesn't start, and says why
func testIncompleteSettingsDontStart() {
let session = ModemSession()
XCTAssertFalse(session.start(ModemSettings()))
@@ -162,6 +173,7 @@ final class DModemKitTests: XCTestCase {
XCTAssertEqual(session.run, .stopped)
}
/// user:password@domain parsed (an @ in the password, a port in the domain); one without a user, password or domain isn't
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")
@@ -174,6 +186,7 @@ final class DModemKitTests: XCTestCase {
XCTAssertNil(ModemSettings.parseLogin("u:x@"))
}
/// settings kept with their secrets apart, a cleared secret removed, an old version's moved out of the JSON, missing fields defaulted
func testSettingsKeptAndOldOnesRead() throws {
let defaults = UserDefaults(suiteName: "dmodemkit-test-\(UUID())")!
let secrets = MemorySecrets()
@@ -210,6 +223,7 @@ final class DModemKitTests: XCTestCase {
XCTAssertEqual(ModemSettings().engineConfig(dns: ["1.1.1.1"]).dns, ["1.1.1.1"])
}
/// the label of the last CONNECT's protocols, empty for one with none
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")
@@ -35,10 +35,12 @@ final class EngineTests: XCTestCase {
return false
}
/// [s] written to [fd]
func put(_ fd: Int32, _ s: String) {
_ = s.withCString { write(fd, $0, strlen($0)) }
}
/// on a peer line the modem answers AT commands, hands a dial's line to the callback with the speaker on, says BUSY when told, and ends once its DTE is closed
func testThePeerLine() throws {
signal(SIGPIPE, SIG_IGN)
let seen = Seen()
+7
View File
@@ -33,12 +33,15 @@ static int line_fd = -1, line_caller = -1, exits = 0, exit_result = 99;
static int statuses, speaker_on, logs;
static char line_dial[64];
/* a log line counted */
static void on_log(void *ctx, const char *l) { (void)ctx; (void)l; __sync_fetch_and_add(&logs, 1); }
/* a status report counted */
static void on_status(void *ctx, int link, int offhook, unsigned tx, unsigned rx)
{
(void)ctx; (void)link; (void)offhook; (void)tx; (void)rx;
__sync_fetch_and_add(&statuses, 1);
}
/* the modem's exit counted, its result kept */
static void on_exit_(void *ctx, int r)
{
(void)ctx;
@@ -47,6 +50,7 @@ static void on_exit_(void *ctx, int r)
exit_result = r;
pthread_mutex_unlock(&mu);
}
/* a peer line's fd, which end and the number dialled kept */
static void on_line(void *ctx, int caller, const char *dial, int fd)
{
(void)ctx;
@@ -56,6 +60,7 @@ static void on_line(void *ctx, int caller, const char *dial, int fd)
snprintf(line_dial, sizeof(line_dial), "%s", dial);
pthread_mutex_unlock(&mu);
}
/* the speaker seen on */
static void on_speaker(void *ctx, int level) { (void)ctx; if (level > 0) speaker_on = 1; }
/* text from fd until want (or secs) */
@@ -80,12 +85,14 @@ static int expect(int fd, const char *want, int secs)
return 0;
}
/* s written to fd */
static void put(int fd, const char *s)
{
if (write(fd, s, strlen(s)) < 0)
perror("write");
}
/* the engine on a peer line through its C API, each step checked: 1 if any failed */
int main(void)
{
dmodem_config c;
+3
View File
@@ -57,6 +57,7 @@ const int FRAME = 160; /* 20 ms at 8000 Hz */
/* a frame through the codec, in place */
class Codec {
public:
/* the codec called name (none, gsm or an AMR-NB rate); the program exits if it hasn't it */
explicit Codec(const std::string &name) : name_(name)
{
#ifdef HAVE_GSM
@@ -85,6 +86,7 @@ public:
}
}
/* the frame s (FRAME samples) encoded and decoded back, in place (as it is for none) */
void run(short *s)
{
#ifdef HAVE_GSM
@@ -144,6 +146,7 @@ void channel(int in, int out, std::string codec)
} // namespace
/* a filter (--filter), or two modems run on a line through the codec, their ptys on stderr */
int main(int argc, char *argv[])
{
dmd::Options opt;
+6
View File
@@ -66,6 +66,7 @@ bool spk_was_on;
long spk_samples;
std::string logs;
/* the engine's status kept, and the rates once it's online; the waiters woken */
void on_engine_status(const Status &s)
{
std::lock_guard<std::mutex> lk(mu);
@@ -78,6 +79,7 @@ void on_engine_status(const Status &s)
cv.notify_all();
}
/* the engine's exit counted, its result kept; the waiters woken */
void on_engine_exit(int r)
{
std::lock_guard<std::mutex> lk(mu);
@@ -86,6 +88,7 @@ void on_engine_exit(int r)
cv.notify_all();
}
/* whether the engine has exited n times within secs */
bool wait_exits(int n, int secs)
{
std::unique_lock<std::mutex> lk(mu);
@@ -121,6 +124,7 @@ bool expect(int fd, const char *re, int secs, std::string *got = nullptr)
return false;
}
/* s written to fd */
void put(int fd, const std::string &s)
{
if (write(fd, s.data(), s.size()) != (ssize_t)s.size())
@@ -182,6 +186,7 @@ pid_t start_dmodemd(const char *path, int *pty)
return pid;
}
/* the engine's settings: user e at dmodemd's loopback port, SIP on ENGINE_PORT, listening or not */
Config config(bool listen)
{
Config c;
@@ -268,6 +273,7 @@ void call_out(int app, int pty, const char *what, bool speaker)
} // namespace
/* the engine against the dmodemd at argv[1], call by call (see above): 1 if any check failed */
int main(int argc, char *argv[])
{
int pty = -1, app;
+1
View File
@@ -22,6 +22,7 @@
#include "line_speed.h"
#include "pipe_modem.h"
/* two modems back to back on pipes at the line's pace, their ptys on stderr, until they end */
int main(int argc, char *argv[])
{
dmd::Options opt;
+1
View File
@@ -17,6 +17,7 @@
#include "pipe_modem.h"
/* m's clock as the environment asks: the sample clock, LINE_SPEED times as fast, or (MODEM_REALTIME=0) as fast as it goes */
static inline void line_speed(dmd::PipeModem &m)
{
const char *s = getenv("LINE_SPEED");
+2
View File
@@ -48,6 +48,7 @@ namespace {
std::mutex out_mu;
void say(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
/* a line (printf's) on stdout, flushed, one writer at a time */
void say(const char *fmt, ...)
{
std::lock_guard<std::mutex> lk(out_mu);
@@ -129,6 +130,7 @@ void offer(int fd, std::string what, std::string after = "")
} // namespace
/* the engine on a peer line, its DTE and lines offered on ports and its news on stdout, the app's lines from stdin */
int main(int argc, char *argv[])
{
Config cfg;
+1
View File
@@ -143,6 +143,7 @@ void on_signal(int)
} // namespace
/* the engine and dmodemd (argv's, T.38 unless --no-t38) on a loopback SIP call, until killed */
int main(int argc, char *argv[])
{
bool t38 = true;
+2
View File
@@ -94,6 +94,7 @@ s16 next_page(void *, T4Page *p)
return 1;
}
/* a page the machine received, written as <dir>/got<n>.pbm */
void page_received(void *, T4Page *p)
{
write_pbm(dir + "/got" + std::to_string(++pages_got) + ".pbm", p);
@@ -146,6 +147,7 @@ void machine(int in, int out, struct t30_config cfg, double snr)
} // namespace
/* the modem and the T.30 machine on a line, sending or receiving as argv says */
int main(int argc, char *argv[])
{
dmd::Options opt;
+1
View File
@@ -11,6 +11,7 @@
namespace dmodem_android {
/* (the fake needs no descriptor) a descriptor's use only starts the transfer counts again */
void usb_use_fd(int fd)
{
if (fd >= 0)
+1
View File
@@ -48,6 +48,7 @@ bool pass(int from, int to)
} // namespace
/* the engine on the fake stick at the rate in argv[1] (9600), its DTE between stdin/stdout until it exits */
int main(int argc, char *argv[])
{
Config cfg;
+8
View File
@@ -38,6 +38,7 @@ while "ready" not in events and time.time() - t0 < 5:
class Modem:
"""the engine (usb_host) on line <n>'s fake stick: its DTE, its log"""
def __init__(self, n):
"""usb_host started on the stick at line n's socket, its DTE and log read by threads of their own"""
self.n = n
sock = os.path.join(tmp, n + ".sock")
if agere:
@@ -54,6 +55,7 @@ class Modem:
threading.Thread(target=self._log, daemon=True).start()
def _dte(self):
"""the DTE's output gathered into buf until it ends"""
while True:
d = os.read(self.p.stdout.fileno(), 4096)
if not d:
@@ -62,14 +64,17 @@ class Modem:
self.buf += d
def _log(self):
"""the log's lines gathered until it ends"""
for l in self.p.stderr:
self.log.append(l.decode(errors="replace").rstrip())
def write(self, b):
"""b to the DTE"""
self.p.stdin.write(b)
self.p.stdin.flush()
def expect(self, pat, t):
"""the first match of pat in what the DTE said within t s (what's up to it taken), or None"""
end = time.time() + t
while time.time() < end:
with self.lock:
@@ -81,10 +86,12 @@ class Modem:
return None
def cmd(self, c, pat=rb"OK\r\n", t=5):
"""the AT command c sent; pat's match within t s, or None"""
self.write(c + b"\r")
return self.expect(pat, t)
def logged(self, pat, t):
"""whether a log line matches pat within t s"""
end = time.time() + t
while time.time() < end:
if any(re.search(pat, l) for l in list(self.log)):
@@ -95,6 +102,7 @@ class Modem:
ok = True
def check(what, cond):
"""what was checked printed with yes or NO; a NO fails the test"""
global ok
print("%s: %s" % (what, "yes" if cond else "NO"))
ok = ok and bool(cond)
@@ -169,6 +169,7 @@ class Class1(private val io: TransferIo, private val log: (String) -> Unit = {})
const val T2_MS = 6000L
val RESULTS = setOf("OK", "ERROR", "NO CARRIER", "NO DIALTONE", "NO DIAL TONE", "BUSY", "NO ANSWER", "RING", "FCERROR")
/** [b]'s octets in hex, apart by spaces (for the log) */
fun hex(b: ByteArray) = b.joinToString(" ") { hex2(it.toInt() and 0xff) }
/** a frame: address, control (set when sent), FCF, FIF */
@@ -21,6 +21,7 @@ object EcmHdlc {
var bits = 0L
private set
/** a bit on, into the octet's next bit up (each full octet to [out]) */
fun bit(b: Int) {
if (b != 0) cur = cur or (1 shl n)
bits++
@@ -31,6 +32,7 @@ object EcmHdlc {
}
}
/** a flag, 0x7e, bottom bit first (not stuffed) */
fun flag() {
for (i in 0 until 8) bit((0x7e shr i) and 1)
}
@@ -53,6 +55,7 @@ object EcmHdlc {
for (f in frames) {
val fcs = Hdlc.fcs(f) xor 0xffff
var ones = 0
/** [octet]'s bits, bottom first, a zero stuffed after five ones */
fun put(octet: Int) {
for (i in 0 until 8) {
val b = (octet shr i) and 1
@@ -97,6 +100,7 @@ object EcmHdlc {
inFrame = true
}
/** a bit (unstuffed) into the frame's octets, while in one; one too long dropped as noise */
fun put(b: Int) {
if (!inFrame) return
if (b != 0) octet = octet or (1 shl nbits)
@@ -27,6 +27,7 @@ object FaxImage {
require(gray.size >= width * height) { "${gray.size} octets for $width by $height" }
val w = FaxPage.WIDTH
val page = FaxPage(w, height, fine)
/** the gray at [x], [y]: white right of the image */
fun at(x: Int, y: Int): Int = if (x < width) gray[y * width + x].toInt() and 0xff else 255
if (!dither) {
for (y in 0 until height) for (x in 0 until w) if (at(x, y) < 128) page.set(x, y, true)
@@ -12,16 +12,20 @@ import com.neodesktop.dmodem.io.*
* Small, and the pels exactly those that came.
*/
object FaxPdf {
/** [pages] as a PDF to [out] */
fun write(pages: List<FaxPage>, out: Sink) {
val o = Bytes()
val offsets = ArrayList<Int>()
/** the next object, [body], its offset kept for the xref */
fun obj(body: ByteArray) {
offsets.add(o.size)
o.write("${offsets.size} 0 obj\n".encodeToByteArray())
o.write(body)
o.write("\nendobj\n".encodeToByteArray())
}
/** the next object, its text Latin-1 */
fun obj(s: String) = obj(latin1(s))
/** the next object a stream of [data], its [dict] and length before it */
fun stream(dict: String, data: ByteArray) =
obj("<< $dict /Length ${data.size} >>\nstream\n".encodeToByteArray() + data + "\nendstream".encodeToByteArray())
@@ -51,6 +55,7 @@ object FaxPdf {
out.write(o.toByteArray())
}
/** [b] with its bits the other way round */
private fun reverse(b: Byte): Byte {
var c = b.toInt() and 0xff
c = (c and 0xf0 shr 4) or (c and 0x0f shl 4)
@@ -6,6 +6,7 @@ import kotlin.random.Random
/** A fax test page: a frame, bars of every width, text-like dashes, a checkerboard, a black row. */
object FaxTestPage {
/** the page, [rows] rows at fine or normal resolution, its speckles from [seed] */
fun of(fine: Boolean, rows: Int = 400, seed: Int = 1): FaxPage {
val p = FaxPage(FaxPage.WIDTH, rows, fine)
val r = Random(seed)
@@ -78,12 +78,15 @@ object T30 {
Rate(4800, 0x2, 0, 48, 48), Rate(2400, 0x0, 0, 24, 24),
)
/** whether a FIF's bit [n] is set (T.30's numbering: 1 is the first octet's bottom bit; false past its end) */
fun bit(fif: ByteArray, n: Int): Boolean = (n - 1) / 8 < fif.size && (fif[(n - 1) / 8].toInt() shr ((n - 1) % 8)) and 1 == 1
/** a FIF's bit [n] set (T.30's numbering) */
fun setBit(fif: ByteArray, n: Int) {
fif[(n - 1) / 8] = (fif[(n - 1) / 8].toInt() or (1 shl ((n - 1) % 8))).toByte()
}
/** a DIS or DCS's rate field, bits 11-14, as a number (bit 11 the lowest) */
private fun rateBits(fif: ByteArray) =
(if (bit(fif, 11)) 1 else 0) or (if (bit(fif, 12)) 2 else 0) or (if (bit(fif, 13)) 4 else 0) or (if (bit(fif, 14)) 8 else 0)
@@ -163,6 +166,7 @@ object T30 {
return ByteArray(20) { k -> if (k < s.length) s[s.length - 1 - k].code.toByte() else ' '.code.toByte() }
}
/** a CSI or TSI's text: its 20 characters back the right way, what isn't printable as spaces, trimmed */
fun readIdent(fif: ByteArray): String =
fif.take(20).reversed().map { b -> val c = b.toInt() and 0xff; if (c in 32..126) c.toChar() else ' ' }.joinToString("").trim()
@@ -238,6 +242,7 @@ object T30 {
// training: down the rates until one takes
var ri = 0
/** TSI, DCS and training at each rate in turn (three tries without an answer) until a CFR: that rate */
fun train(): Rate {
var tries = 0
while (ri < rates.size) {
@@ -462,11 +467,13 @@ object T30 {
var count = 0
var long = false
var last: ByteArray? = null
/** our answer [fr] sent (and kept, to send again) */
fun respond(fr: ByteArray) {
last = fr
c.command("+FTS=8")
c.transmitFrames(listOf(fr))
}
/** the page's data decoded and, unless empty or over 5% bad rows, to [page]; the page ended by [post] */
fun pageDone(post: Int): EcmEnd {
val dec = T4.decode(doc.toByteArray(), FaxPage.WIDTH, fine)
if (dec.page.rows > 0 && dec.badRows * 20 < dec.page.rows) {
@@ -13,8 +13,10 @@ import com.neodesktop.dmodem.io.*
class FaxPage(val width: Int, val rows: Int, val fine: Boolean, val bits: ByteArray = ByteArray(width / 8 * rows)) {
val stride: Int get() = width / 8
/** whether the pel at [x], [y] is black */
fun black(x: Int, y: Int): Boolean = (bits[y * stride + x / 8].toInt() shr (7 - x % 8)) and 1 == 1
/** the pel at [x], [y] made black ([on]) or white */
fun set(x: Int, y: Int, on: Boolean) {
val i = y * stride + x / 8
val m = 0x80 shr (x % 8)
@@ -78,6 +80,7 @@ object T4 {
)
private const val EOL = "000000000001"
/** a table's "run:bits" pairs, apart by spaces, as codes */
private fun codes(s: String) = s.trim().split(Regex("\\s+")).map { it.split(':').let { (r, b) -> Code(r.toInt(), b) } }
private val whiteByRun = (WHITE + EXTENDED).associateBy { it.run }
@@ -107,6 +110,7 @@ object T4 {
}
}
/** the node arrays twice the size, the new nodes empty */
private fun grow() {
val s = zero.size * 2
zero = zero.copyOf(s).also { it.fill(-1, s / 2, s) }
@@ -126,6 +130,7 @@ object T4 {
var count = 0L
private set
/** a bit into the byte's next bit up (each full byte to [out]) */
fun bit(b: Int) {
if (b != 0) cur = cur or (1 shl n)
n++
@@ -133,8 +138,10 @@ object T4 {
if (n == 8) { out.write(cur); cur = 0; n = 0 }
}
/** [s]'s '0's and '1's as bits, in order */
fun bits(s: String) { for (c in s) bit(if (c == '1') 1 else 0) }
/** the bits so far, the last byte's top bits zero */
fun bytes(): ByteArray {
if (n > 0) { out.write(cur); cur = 0; n = 0 }
return out.toByteArray()
@@ -168,6 +175,7 @@ object T4 {
return w.bytes()
}
/** a [run] of white or [black] in its codes: 2560 make-ups, a make-up, then the terminating code */
private fun runCode(w: BitWriter, run: Int, black: Boolean) {
val table = if (black) blackByRun else whiteByRun
var left = run
@@ -189,6 +197,7 @@ object T4 {
var bad = 0
val total = data.size * 8L
var pos = 0L
/** the data's next bit, or -1 at its end */
fun bit(): Int {
if (pos >= total) return -1
val b = (data[(pos / 8).toInt()].toInt() shr (pos % 8).toInt()) and 1
+5
View File
@@ -43,6 +43,7 @@ PY_DEF = re.compile(r"^(\s*)(?:async\s+)?def\s+\w+")
def tracked():
"""git's tracked sources of the kinds checked, outside external/"""
out = subprocess.run(["git", "-C", ROOT, "ls-files"], capture_output=True, text=True,
check=True).stdout.split("\n")
return [f for f in out if f.endswith(EXTS) and not f.startswith("external/")]
@@ -86,6 +87,7 @@ def commented(lines, i, raw):
def check_kt_swift(path, text):
"""Kotlin's or Swift's undocumented functions: (line, text) each"""
raw = text.split("\n")
lines = blank(text).split("\n")
bad = []
@@ -98,6 +100,7 @@ def check_kt_swift(path, text):
def check_sh(path, text):
"""a shell script's functions without a # comment above: (line, text) each"""
raw = text.split("\n")
bad = []
for i, l in enumerate(raw):
@@ -109,6 +112,7 @@ def check_sh(path, text):
def check_py(path, text):
"""Python's functions without a docstring or a # comment above: (line, text) each"""
raw = text.split("\n")
bad = []
for i, l in enumerate(raw):
@@ -130,6 +134,7 @@ def check_py(path, text):
def main(argv):
"""the files checked (all tracked ones without arguments): 1 if any is undocumented"""
files = argv[1:] or tracked()
total = 0
c_files = []