From 9b4debf4f5a67395ed6e1a2f65ad1d7700645a98 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 08:16:27 +0000 Subject: [PATCH] Comments for every function: the first two batches; doc_check.py stricter The tests' and shared code's functions in two of eight batches (comment lines only). doc_check.py skips only lines of annotations alone, so a function under an annotated property (@Volatile var) needs its own. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0172Hejd12i4aYikYW9vgpZs --- .../neodesktop/dmodem/bridge/UsbBridgeTest.kt | 45 +++++++++++++++++++ .../dmodem/bridge/UsbSerialAdaptersTest.kt | 5 +++ .../neodesktop/dmodem/bridge/XrSerialTest.kt | 19 ++++++++ .../neodesktop/dmodem/cell/CellLineTest.kt | 7 +++ .../dmodem/cell/CellSettingsTest.kt | 2 + .../dmodem/cell/CellTransportTest.kt | 7 +++ .../com/neodesktop/dmodem/cell/FakeNetwork.kt | 13 ++++++ .../com/neodesktop/dmodem/fax/CellFaxTest.kt | 4 ++ .../com/neodesktop/dmodem/fax/FaxAppTest.kt | 10 +++++ .../com/neodesktop/dmodem/fax/FaxCallTest.kt | 14 ++++++ .../com/neodesktop/dmodem/fax/FaxPdfTest.kt | 2 + .../java/com/neodesktop/dmodem/fax/FaxPty.kt | 2 + .../com/neodesktop/dmodem/fax/SipFaxTest.kt | 5 +++ .../neodesktop/dmodem/fax/T30InteropTest.kt | 9 ++++ .../neodesktop/dmodem/local/DistrosTest.kt | 13 ++++++ .../dmodem/local/LinuxSystemTest.kt | 13 ++++++ .../neodesktop/dmodem/local/LocalShellTest.kt | 14 ++++++ .../com/neodesktop/dmodem/local/TarTest.kt | 6 +++ .../dmodem/modem/BluetoothModemTest.kt | 3 ++ .../neodesktop/dmodem/modem/CallTonesTest.kt | 14 ++++++ .../com/neodesktop/dmodem/modem/DteHubTest.kt | 3 ++ .../dmodem/modem/IncomingCallsTest.kt | 4 ++ .../dmodem/modem/LineRecordingsTest.kt | 1 + .../neodesktop/dmodem/modem/LogFormatTest.kt | 4 ++ .../com/neodesktop/dmodem/transfer/ZModem.kt | 18 ++++++++ .../com/neodesktop/dmodem/fax/EcmTest.kt | 8 ++++ .../com/neodesktop/dmodem/fax/FakeClass1.kt | 11 +++++ .../com/neodesktop/dmodem/fax/T4Test.kt | 6 +++ .../com/neodesktop/dmodem/jobs/JobsTest.kt | 21 +++++++++ .../dmodem/peer/PeerLoopbackTest.kt | 13 ++++++ .../neodesktop/dmodem/ppp/PppLoopbackTest.kt | 8 ++++ .../dmodem/terminal/TerminalBridgeTest.kt | 3 ++ .../dmodem/terminal/TerminalEmulatorTest.kt | 21 +++++++++ .../dmodem/terminal/TerminalRunsTest.kt | 4 ++ .../dmodem/tones/CountryTonesTest.kt | 5 +++ .../dmodem/transfer/HexRecordsTest.kt | 11 +++++ .../dmodem/transfer/TextTransferTest.kt | 5 +++ .../dmodem/transfer/TransferLoopbackTest.kt | 10 +++++ .../kotlin/com/neodesktop/dmodem/io/Io.jvm.kt | 12 +++++ .../com/neodesktop/dmodem/io/Net.jvm.kt | 1 + .../dmodem/transfer/FolderIncoming.kt | 3 ++ .../dmodem/terminal/XtermFeaturesTest.kt | 17 +++++++ .../dmodem/tones/CountryTonesSourceTest.kt | 1 + .../com/neodesktop/dmodem/io/Io.native.kt | 1 + .../com/neodesktop/dmodem/io/Net.native.kt | 4 ++ .../com/neodesktop/dmodem/peer/PeerHost.kt | 1 + .../com/neodesktop/dmodem/peer/PosixPeer.kt | 7 +++ .../neodesktop/dmodem/ppp/UdpPacketTunnel.kt | 7 +++ .../neodesktop/dmodem/transfer/PosixFiles.kt | 9 ++++ .../neodesktop/dmodem/jobs/NativeJobsTest.kt | 4 ++ .../neodesktop/dmodem/peer/PosixPeerTest.kt | 6 +++ tools/country_tones.py | 2 + tools/doc_check.py | 8 ++-- tools/usb-serial-ids/generate.py | 3 ++ 54 files changed, 446 insertions(+), 3 deletions(-) diff --git a/app/src/test/java/com/neodesktop/dmodem/bridge/UsbBridgeTest.kt b/app/src/test/java/com/neodesktop/dmodem/bridge/UsbBridgeTest.kt index 0d320cc..d626f00 100644 --- a/app/src/test/java/com/neodesktop/dmodem/bridge/UsbBridgeTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/bridge/UsbBridgeTest.kt @@ -36,8 +36,11 @@ class UsbBridgeTest { override val state: StateFlow = MutableStateFlow(TerminalLink.State.Open) val listeners = CopyOnWriteArrayList() val got = ByteArrayOutputStream() + /** takes [l] for what the modem says */ override fun addListener(l: TerminalLink.Listener) { listeners.add(l) } + /** no more of it to [l] */ override fun removeListener(l: TerminalLink.Listener) { listeners.remove(l) } + /** kept as sent; a command's CR answered OK */ override fun write(data: ByteArray, offset: Int, length: Int): Boolean { synchronized(got) { got.write(data, offset, length) } if (String(data, offset, length).endsWith("\r")) { @@ -46,6 +49,7 @@ class UsbBridgeTest { } return true } + /** what the computer sent it, so far */ fun sent() = synchronized(got) { String(got.toByteArray()) } } @@ -59,50 +63,83 @@ class UsbBridgeTest { /** (a CDC adapter's driver: no DSR to read) */ @Volatile var noDsr = false @Volatile var closed = false + /** the computer's next bytes, waiting up to [timeout] ms; 0 if none */ override fun read(dest: ByteArray, timeout: Int): Int { if (closed) throw IOException("closed") val b = fromComputer.poll(timeout.toLong(), TimeUnit.MILLISECONDS) ?: return 0 System.arraycopy(b, 0, dest, 0, b.size) return b.size } + /** as the other read, [length] aside */ override fun read(dest: ByteArray, length: Int, timeout: Int): Int = read(dest, timeout) + /** kept, as said to the computer */ override fun write(src: ByteArray, timeout: Int) { synchronized(toComputer) { toComputer.write(src) } } + /** its first [length] kept, as said to the computer */ override fun write(src: ByteArray, length: Int, timeout: Int) { synchronized(toComputer) { toComputer.write(src, 0, length) } } + /** the computer's DCD, the modem's carrier */ override fun setDTR(value: Boolean) { dtr = value } + /** kept, for the test to see */ override fun setRTS(value: Boolean) { rts = value } + /** the computer's DTR; none for a CDC adapter's driver */ override fun getDSR(): Boolean = if (noDsr) throw UnsupportedOperationException() else dsr + /** the DTR last set */ override fun getDTR() = dtr + /** the RTS last set */ override fun getRTS() = rts + /** (the computer's DTR again) */ override fun getCD() = dsr + /** always clear to send */ override fun getCTS() = true + /** never ringing */ override fun getRI() = false + /** closed: reads fail from now on */ override fun close() { closed = true } + /** until closed */ override fun isOpen() = !closed + /** nothing to open */ override fun open(connection: UsbDeviceConnection?) {} + /** any format taken */ override fun setParameters(baudRate: Int, dataBits: Int, stopBits: Int, parity: Int) {} + /** no driver */ override fun getDriver(): UsbSerialDriver? = null + /** no device */ override fun getDevice(): UsbDevice? = null + /** the only port */ override fun getPortNumber() = 0 + /** no endpoint */ override fun getWriteEndpoint(): UsbEndpoint? = null + /** no endpoint */ override fun getReadEndpoint(): UsbEndpoint? = null + /** no serial number */ override fun getSerial(): String? = null + /** none of the lines */ override fun getControlLines(): EnumSet = EnumSet.noneOf(UsbSerialPort.ControlLine::class.java) + /** all of the lines */ override fun getSupportedControlLines(): EnumSet = EnumSet.allOf(UsbSerialPort.ControlLine::class.java) + /** any flow control taken */ override fun setFlowControl(flowControl: UsbSerialPort.FlowControl?) {} + /** no flow control */ override fun getFlowControl() = UsbSerialPort.FlowControl.NONE + /** only none */ override fun getSupportedFlowControl(): EnumSet = EnumSet.of(UsbSerialPort.FlowControl.NONE) + /** always XON */ override fun getXON() = true + /** nothing to purge */ override fun purgeHwBuffers(purgeWriteBuffers: Boolean, purgeReadBuffers: Boolean) {} + /** no break */ override fun setBreak(value: Boolean) {} + /** what was said to the computer, so far */ fun said() = synchronized(toComputer) { String(toComputer.toByteArray()) } } + /** [ok] within 5 s, or fails saying [what] */ private fun waitUntil(what: String, ok: () -> Boolean) { val end = System.currentTimeMillis() + 5000 while (!ok() && System.currentTimeMillis() < end) Thread.sleep(20) assertTrue(what, ok()) } + /** an adapter's port carries the computer's commands and the modem's answers, DCD follows the carrier, its DTR dropped hangs up */ @Test fun anAdapterCarriesTheModemAndItsLines() { val modem = FakeModem() @@ -132,6 +169,7 @@ class UsbBridgeTest { assertEquals(null, bridge.client.value) } + /** the phone's USB gadget, a pty for /dev/ttyGS0, carries the computer's commands; its root scripts parse */ @Test fun thePhonesUsbPortAsAGadget() { assumeTrue(File("/usr/bin/python3").canExecute()) @@ -196,6 +234,7 @@ for line in sys.stdin: @Volatile var mode = 0 val requests = CopyOnWriteArrayList() + /** GET_INFO, GET_INPUTS and GET_STATS answered as the firmware does, at most [length] bytes; null for others */ override fun read(request: Int, value: Int, length: Int): ByteArray? = when (request) { PicoSerialProtocol.GET_INFO -> byteArrayOf(1, 0, 1, 2, 0, mode.toByte(), role.toByte(), 0, 0x0c, 0, 0x4b, 0, 0, 0) PicoSerialProtocol.GET_INPUTS -> byteArrayOf(role.toByte(), computer.toByte(), outputs.toByte(), 1, 1) @@ -203,6 +242,7 @@ for line in sys.stdin: else -> null }?.copyOf(minOf(length, 64)).also { requests.add("in $request") }?.let { it.copyOf(minOf(it.size, length)) } + /** SET_OUTPUTS and SET_MODE as the firmware does them, each request kept */ override fun write(request: Int, value: Int): Boolean { requests.add("out $request %04x".format(value)) when (request) { @@ -217,6 +257,7 @@ for line in sys.stdin: } } + /** the firmware's info, inputs and stats structures parsed, SET_OUTPUTS' wValue, a CDC SERIAL_STATE */ @Test fun picoSerialStructuresAsTheFirmwareHasThem() { // (bytes from firmware/src/core/protocol.h's structs, compiled) @@ -249,6 +290,7 @@ for line in sys.stdin: assertEquals(null, CdcSerialState.parse(byteArrayOf(0xA1.toByte(), 0x2A, 0, 0, 0, 0, 2, 0, 0, 0), 10)) } + /** a pico-serial board's DCD, DSR and RI follow the modem, its computer's DTR read and dropped hangs up, the lines sent again after unplugging */ @Test fun aPicoSerialBoardsLinesEachTheirOwn() { val modem = FakeModem() @@ -296,6 +338,7 @@ for line in sys.stdin: assertEquals(PicoSerialProtocol.Mode.DCE, p.info()?.mode) } + /** a CDC adapter's SERIAL_STATE dropping DTR hangs up, though the port reads no DSR */ @Test fun aCdcAdaptersNotificationsHangUp() { val modem = FakeModem() @@ -310,6 +353,7 @@ for line in sys.stdin: System.arraycopy(n, 0, buf, 0, n.size) n.size }.start() + /** a SERIAL_STATE notification with [v] as its bits */ fun state(v: Int) = byteArrayOf(0xA1.toByte(), 0x20, 0, 0, 0, 0, 2, 0, v.toByte(), 0) val link = UsbPortLink(port, bridge, signals, "CDC adapter", extra = cdc) val t = Thread { link.serve() }.apply { start() } @@ -328,6 +372,7 @@ for line in sys.stdin: t.join(5000) } + /** a format string read, a bad one 8N1 at the speed */ @Test fun formats() { assertEquals(SerialFormat(9600, 7, 'E', 1), Bridges.format(9600, "7e1")) diff --git a/app/src/test/java/com/neodesktop/dmodem/bridge/UsbSerialAdaptersTest.kt b/app/src/test/java/com/neodesktop/dmodem/bridge/UsbSerialAdaptersTest.kt index 60d0945..14f05b2 100644 --- a/app/src/test/java/com/neodesktop/dmodem/bridge/UsbSerialAdaptersTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/bridge/UsbSerialAdaptersTest.kt @@ -19,9 +19,11 @@ import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(sdk = [35]) class UsbSerialAdaptersTest { + /** the driver class found for a device with these IDs, or null */ private fun driver(vendor: Int, product: Int) = UsbSerialAdapters.table().findDriver(TestUsbDevices.device("/dev/bus/usb/001/002", vendor, product)) + /** adapters under their makers' own IDs get their chip's driver */ @Test fun theirMakersIds() { // an ATEN UC-232A (a PL2303), a Silicon Labs CP210x under another ID, a CH340 variant, an FTDI clone that FTDI's driver bricked @@ -31,12 +33,14 @@ class UsbSerialAdaptersTest { assertEquals(FtdiSerialDriver::class.java, driver(0x0403, 0x0000)) } + /** Exar's UARTs get our own driver */ @Test fun exarsTheirOwn() { assertEquals(XrSerialDriver::class.java, driver(0x04e2, 0x1410)) assertEquals(XrSerialDriver::class.java, driver(0x04e2, 0x1422)) } + /** the chip makers' own IDs still get theirs */ @Test fun theChipMakersStill() { assertEquals(FtdiSerialDriver::class.java, driver(0x0403, 0x6001)) @@ -45,6 +49,7 @@ class UsbSerialAdaptersTest { assertEquals(Ch34xSerialDriver::class.java, driver(0x1a86, 0x7523)) } + /** a USB modem and an unknown device get none */ @Test fun notOthers() { // the Agere USB modem (UsbModems'), and nothing in particular diff --git a/app/src/test/java/com/neodesktop/dmodem/bridge/XrSerialTest.kt b/app/src/test/java/com/neodesktop/dmodem/bridge/XrSerialTest.kt index 18f6891..efd18ff 100644 --- a/app/src/test/java/com/neodesktop/dmodem/bridge/XrSerialTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/bridge/XrSerialTest.kt @@ -23,6 +23,7 @@ class XrSerialTest { /** the reads' answers, by wIndex */ val regs = mutableMapOf() + /** a read answered from [regs] by wIndex (-1 if none there), a write's bytes kept; each request recorded */ override fun transfer(requestType: Int, request: Int, value: Int, index: Int, data: ByteArray?, length: Int): Int { if (requestType and 0x80 != 0) { val v = regs[index] ?: return -1 @@ -35,8 +36,10 @@ class XrSerialTest { } } + /** a vendor write of [value] to register [index], as a V141x is sent it */ private fun w(index: Int, value: Int) = Req(0x40, 0x00, value, index) + /** each product ID's chip family, and the driver's 11 IDs under Exar's vendor ID */ @Test fun families() { assertEquals(XrChip.XR2280X, XrChip.of(0x1400)) @@ -51,6 +54,7 @@ class XrSerialTest { assertEquals(11, ids.getValue(0x04e2).size) } + /** a V141x's registers are written and read a byte at a time, the block in wIndex */ @Test fun v141xRegistersAreBytesWithTheBlockInTheIndex() { val f = FakeChip() @@ -61,6 +65,7 @@ class XrSerialTest { assertEquals(listOf(Req(0x40, 0x00, 0x08, 0x000b), Req(0xC0, 0x01, 0, 0x001f)), f.sent) } + /** a B142x's registers are words, to the interface's requests */ @Test fun b142xRegistersAreWordsToTheInterface() { val f = FakeChip() @@ -71,6 +76,7 @@ class XrSerialTest { assertEquals(listOf(Req(0xC1, 0x00, 0, 0x0010), Req(0x41, 0x00, 0x0128, 0x000e)), f.sent) } + /** an XR2280x and a B1411 are sent their own requests and register addresses */ @Test fun xr2280xAndB1411UseTheirOwnRequests() { val f = FakeChip() @@ -84,6 +90,7 @@ class XrSerialTest { ) } + /** a V141x opened: the UART off, the pins and lines set, 9600 8N1, the FIFOs reset and on again */ @Test fun v141xOpens() { val f = FakeChip() @@ -104,6 +111,7 @@ class XrSerialTest { ) } + /** a B142x opened with DTR and RTS: its custom driver on, the line set by CDC SET_LINE_CODING */ @Test fun b142xOpensWithCdcLineCoding() { val f = FakeChip() @@ -124,6 +132,7 @@ class XrSerialTest { ) } + /** a V141x's divisor and fraction masks for its speeds, and the registers a new line sets */ @Test fun v141xBaudRates() { // divisor = 48 MHz / baud, its fraction in 32nds picking the masks (RX's by the divisor's oddness) @@ -151,8 +160,10 @@ class XrSerialTest { assertTrue(w(0x0004, 0x00) in f.sent && w(0x0005, 0x71) in f.sent && w(0x0006, 0x02) in f.sent) } + /** a V141x's format register for each data bits, stop bits and parity, the unsupported ones refused */ @Test fun v141xFormats() { + /** the format register a V141x is sent for these */ fun format(bits: Int, stop: Int, parity: Int): Int { val f = FakeChip() XrUart(XrChip.V141X, f, 0).setLine(9600, bits, stop, parity) @@ -167,8 +178,10 @@ class XrSerialTest { assertThrows { format(9, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE) } } + /** the CDC families' SET_LINE_CODING for a line, to the port's interface */ @Test fun cdcFamiliesCodeTheLine() { + /** the SET_LINE_CODING request [chip] is sent for this line */ fun coding(chip: XrChip, baud: Int, bits: Int, stop: Int, parity: Int, itf: Int = 0): Req { val f = FakeChip() XrUart(chip, f, itf).setLine(baud, bits, stop, parity) @@ -189,6 +202,7 @@ class XrSerialTest { assertThrows { coding(XrChip.XR2280X, 9600, 6, UsbSerialPort.STOPBITS_1, 0) } } + /** DTR and RTS set through GPIO set and clear, and the status lines read, active low */ @Test fun linesOutAndIn() { val f = FakeChip() @@ -213,6 +227,7 @@ class XrSerialTest { assertTrue(XrUart(XrChip.B142X, b, 0).status().dsr) } + /** a break set and cleared, RTS/CTS and XON/XOFF flow control set, DTR/DSR refused */ @Test fun breakAndFlow() { val f = FakeChip() @@ -238,6 +253,7 @@ class XrSerialTest { assertEquals(listOf(Req(0x41, 0, 0xffff, 0x000a), Req(0x40, 0, 0xfff, 0x0c0a)), b.sent) } + /** a multi-port V141x's and a B142x's channels in their requests' addresses */ @Test fun multiPortChannels() { // XR21V1414: port n on interfaces 2n/2n+1, channel n in the block byte, its UART manager registers + n @@ -262,6 +278,7 @@ class XrSerialTest { assertEquals(listOf(Req(0x41, 0, 0x08, 0x020f), Req(0xC1, 0, 0, 0x0210)), b.sent) } + /** each port's comm and data interfaces paired, others skipped */ @Test fun portsPairInterfaces() { // two ports: comm 0 + data 1, comm 2 + data 3 @@ -273,6 +290,7 @@ class XrSerialTest { assertEquals(emptyList>(), XrUart.pairs(listOf(0 to 2))) } + /** a failed read throws, nothing recorded */ @Test fun failedTransfersThrow() { val f = FakeChip() @@ -280,6 +298,7 @@ class XrSerialTest { assertFalse(f.sent.isNotEmpty()) } + /** fails unless [f] throws a [T] */ private inline fun assertThrows(f: () -> Unit) { try { f() diff --git a/app/src/test/java/com/neodesktop/dmodem/cell/CellLineTest.kt b/app/src/test/java/com/neodesktop/dmodem/cell/CellLineTest.kt index d0639e4..9b34eee 100644 --- a/app/src/test/java/com/neodesktop/dmodem/cell/CellLineTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/cell/CellLineTest.kt @@ -19,16 +19,20 @@ import org.junit.Test class CellLineTest { private val closers = ArrayList<() -> Unit>() + /** the modems, transports and processes closed, last first */ @After fun tearDown() = closers.asReversed().forEach { runCatching { it() } } private inner class CellModem(name: String, val phone: FakeNetwork.Phone, listen: Boolean) : TestModem(name, CellTransport(phone, phone.audio, audioMs = 2000), listen, 60, closers) { + /** the number dialled: its digits, or null for none */ override fun target(dial: String) = dial.filter { it.isDigit() }.ifEmpty { null } } + /** the speed a CONNECT line gives */ private fun rate(connect: String) = Regex("CONNECT (\\d+)").find(connect)!!.groupValues[1].toInt() + /** two modems connect over a clean mobile call at 9600 or more, carry data both ways, and hang up */ @Test fun aMobileCall() { val net = FakeNetwork(closers = closers) @@ -58,6 +62,7 @@ class CellLineTest { assertEquals(CellPhone.State.IDLE, b.phone.state.value) } + /** through AMR 12.2 two V.21 modems connect at 300 and the data's start gets through */ @Test fun throughAmr() { assumeTrue("codec_line isn't built (native-test)", FakeNetwork.codecLine() != null) @@ -81,6 +86,7 @@ class CellLineTest { assertTrue(b.expect(data.take(40), 30).endsWith(data.take(40))) } + /** V.cvm through AMR 12.2: connected at 600 or more, LAPM data whole each way, +CVM? its figures */ @Test fun throughAmrInVcvm() { assumeTrue("codec_line isn't built (native-test)", FakeNetwork.codecLine() != null) @@ -116,6 +122,7 @@ class CellLineTest { assertTrue(fig, Regex("\\+CVM: \\d+,\\d+,\\d+,\\d+,").containsMatchIn(fig)) } + /** a number nobody has ends the call; a modem not taking calls leaves its phone ringing, no RING */ @Test fun nobodyAndNotForTheModem() { val net = FakeNetwork(closers = closers) diff --git a/app/src/test/java/com/neodesktop/dmodem/cell/CellSettingsTest.kt b/app/src/test/java/com/neodesktop/dmodem/cell/CellSettingsTest.kt index d6091eb..63b7f2c 100644 --- a/app/src/test/java/com/neodesktop/dmodem/cell/CellSettingsTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/cell/CellSettingsTest.kt @@ -8,6 +8,7 @@ import org.junit.Test /** On mobile calls the modem starts at the speed chosen (+MS), with the init commands on the same line. */ class CellSettingsTest { + /** mobile calls start with the +MS speed chosen and the init commands on the same line; other lines with the init commands alone */ @Test fun startCommands() { val cell = ModemSettings(line = ModemSettings.LINE_CELL) @@ -21,6 +22,7 @@ class CellSettingsTest { assertEquals("ATX3", ModemSettings(line = ModemSettings.LINE_WIFI).startCommands()) } + /** a CONNECT's modulation and protocols as labelled, from the last one; none for a plain speed */ @Test fun whatTheConnectSaid() { val label = com.neodesktop.dmodem.modem.ConnectInfo::label diff --git a/app/src/test/java/com/neodesktop/dmodem/cell/CellTransportTest.kt b/app/src/test/java/com/neodesktop/dmodem/cell/CellTransportTest.kt index 7999645..1d16697 100644 --- a/app/src/test/java/com/neodesktop/dmodem/cell/CellTransportTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/cell/CellTransportTest.kt @@ -16,9 +16,11 @@ import java.util.concurrent.TimeUnit class CellTransportTest { private val closers = ArrayList<() -> Unit>() + /** the network's phones and transports closed, last first */ @After fun tearDown() = closers.asReversed().forEach { runCatching { it() } } + /** waits until [cond], up to [ms]; fails saying [what] */ private fun waitUntil(what: String, ms: Long = 5000, cond: () -> Boolean) { val end = System.currentTimeMillis() + ms while (!cond()) { @@ -27,6 +29,7 @@ class CellTransportTest { } } + /** a call placed: the number dialled, the handshake answered, samples reaching the far end once answered; closed, hung up both ends */ @Test fun aCallPlacedAndHungUp() { val net = FakeNetwork(closers = closers) @@ -49,11 +52,13 @@ class CellTransportTest { assertEquals(CellPhone.State.IDLE, b.state.value) } + /** a call the phone never places fails, and so does one with no number */ @Test fun aCallNotPlaced() { val net = FakeNetwork(closers = closers) val a = net.phone("5550001") val stuck = object : CellPhone by a { + /** never placed */ override fun dial(number: String) {} } val t = CellTransport(stuck, a.audio, dialMs = 300, audioMs = 300) @@ -71,6 +76,7 @@ class CellTransportTest { } } + /** a call coming in: RING to the modem, its ANSWER answers the phone, its samples kept till then; the caller hanging up ends the line */ @Test fun aCallComingIn() { val net = FakeNetwork(closers = closers) @@ -94,6 +100,7 @@ class CellTransportTest { waitUntil("the end") { d.input.read(buf) < 0 } } + /** a call the caller gives up on before it's answered ends the RING, unanswered */ @Test fun theCallerGivesUp() { val net = FakeNetwork(closers = closers) diff --git a/app/src/test/java/com/neodesktop/dmodem/cell/FakeNetwork.kt b/app/src/test/java/com/neodesktop/dmodem/cell/FakeNetwork.kt index 864883f..b1e04f7 100644 --- a/app/src/test/java/com/neodesktop/dmodem/cell/FakeNetwork.kt +++ b/app/src/test/java/com/neodesktop/dmodem/cell/FakeNetwork.kt @@ -79,6 +79,7 @@ class FakeNetwork(private val codec: String? = null, private val closers: Mutabl return frames.poll() ?: ByteArray(FRAME_BYTES).also { primed = false } } + /** the frames waiting dropped, the jitter buffer to prime again */ @Synchronized fun clear() { frames.clear() @@ -98,6 +99,7 @@ class FakeNetwork(private val codec: String? = null, private val closers: Mutabl /** the call up (both ends off hook) */ @Volatile var connected = false + /** rings [number] if it's there and idle; else the call ends half a second later */ override fun dial(number: String) { dialled.add(number) val to = phones[number] @@ -112,6 +114,7 @@ class FakeNetwork(private val codec: String? = null, private val closers: Mutabl to.state.value = CellPhone.State.RINGING } + /** a ringing call taken: both ends connected */ override fun answer() { answered++ val o = other ?: return @@ -121,6 +124,7 @@ class FakeNetwork(private val codec: String? = null, private val closers: Mutabl o.connected = true } + /** both ends idle again, their call and its sound gone */ override fun hangUp() { hungUp++ val o = other @@ -134,7 +138,9 @@ class FakeNetwork(private val codec: String? = null, private val closers: Mutabl /** the phone's call sound (AudioRecord/AudioTrack on its clock) */ val audio = object : CallAudio { + /** always available */ override fun unavailable(): String? = null + /** the call's sound, a frame each 20 ms each way; only while off hook */ override fun open(): CallStreams { if (state.value != CellPhone.State.OFFHOOK) throw IOException("no call") val me = this@Phone @@ -144,7 +150,9 @@ class FakeNetwork(private val codec: String? = null, private val closers: Mutabl override val input = object : InputStream() { private var frame = ByteArray(0) private var at = 0 + /** (only whole buffers read) */ override fun read(): Int = throw UnsupportedOperationException() + /** the call's sound for this phone, up to [len] bytes, a frame each 20 ms on the clock: silence while the call isn't up; -1 once closed */ override fun read(b: ByteArray, off: Int, len: Int): Int { if (!open) return -1 if (at >= frame.size) { @@ -163,7 +171,9 @@ class FakeNetwork(private val codec: String? = null, private val closers: Mutabl } } override val output = object : OutputStream() { + /** (only whole buffers written) */ override fun write(b: Int) = throw UnsupportedOperationException() + /** this phone's sound to the other's, while the call's up; nowhere otherwise */ override fun write(b: ByteArray, off: Int, len: Int) { if (!open) throw IOException("closed") // (before the call's up, and after: nowhere) @@ -171,6 +181,7 @@ class FakeNetwork(private val codec: String? = null, private val closers: Mutabl if (me.connected && o != null) o.incoming.write(b, off, len) } } + /** both ways ended */ override fun close() { open = false } } } @@ -179,11 +190,13 @@ class FakeNetwork(private val codec: String? = null, private val closers: Mutabl val phones = HashMap() + /** a new phone on the network with [number] */ fun phone(number: String) = Phone(number).also { phones[number] = it } companion object { const val FRAME_BYTES = 320 + /** native-test's codec_line, if built, or null */ fun codecLine(): File? = listOfNotNull( System.getenv("DMODEM_CODEC_LINE"), "../build-host/codec_line", diff --git a/app/src/test/java/com/neodesktop/dmodem/fax/CellFaxTest.kt b/app/src/test/java/com/neodesktop/dmodem/fax/CellFaxTest.kt index 706036e..585f174 100644 --- a/app/src/test/java/com/neodesktop/dmodem/fax/CellFaxTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/fax/CellFaxTest.kt @@ -16,11 +16,13 @@ import org.junit.Test class CellFaxTest { private var line: FaxLineProcess? = null + /** the codec line stopped */ @After fun tearDown() { line?.close() } + /** a page faxed through [codec], at most [maxBps]: what the sender sent (null if it failed) and the pages received */ private fun call(codec: String, maxBps: Int, ecm: Boolean): Pair> { val bin = nativeTool("DMODEM_CODEC_LINE", "codec_line") assumeTrue("codec_line isn't built (native-test)", bin != null) @@ -62,6 +64,7 @@ class CellFaxTest { return sent to got } + /** without a codec the same modems and pacing get the page through */ @Test fun throughNoCodecTheFaxGoes() { // (the line itself, the codec out of it: the same modems, the same pacing) @@ -70,6 +73,7 @@ class CellFaxTest { assertEquals(1, got.size) } + /** through AMR 12.2 the fax fails: neither sent nor received */ @Test fun throughAmrTheTrainingFails() { // AMR-NB 12.2, the best a mobile call has: V.27ter's training at 2400 bit/s diff --git a/app/src/test/java/com/neodesktop/dmodem/fax/FaxAppTest.kt b/app/src/test/java/com/neodesktop/dmodem/fax/FaxAppTest.kt index ad841ad..7fc99a2 100644 --- a/app/src/test/java/com/neodesktop/dmodem/fax/FaxAppTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/fax/FaxAppTest.kt @@ -45,9 +45,11 @@ class FaxAppTest { private lateinit var b: String private val closers = ArrayList<() -> Unit>() + /** native-test's fax_line, if built, or null */ private fun faxLine(): File? = listOfNotNull(System.getenv("DMODEM_FAX_LINE"), "../build-host/fax_line", "build-host/fax_line") .map { File(it) }.firstOrNull { it.canExecute() } + /** fax_line started, modemA's pty on the app's DTE hub as the service has it, the app's fax set up */ @Before fun setUp() { val fl = faxLine() @@ -67,6 +69,7 @@ class FaxAppTest { runBlocking { FaxSettingsStore(ctx).update { it.copy(ident = "+1 555 0100", fine = true, maxBps = 14400) } } } + /** the app's modem log into the test's, the fax cancelled, the hub detached, fax_line stopped */ @After fun tearDown() { // (the app's modem log, into the test's) @@ -97,6 +100,7 @@ class FaxAppTest { return Class1(io) { log.add("B: $it"); TestLogs.note("B", it) } } + /** whether fax_line logged [what] within [secs] s */ private fun waitLog(what: String, secs: Int = 30): Boolean { val end = System.currentTimeMillis() + secs * 1000L while (System.currentTimeMillis() < end) { @@ -106,6 +110,7 @@ class FaxAppTest { return false } + /** the fax's state once it's done, within [secs] s; fails if it's still going */ private fun waitDone(secs: Int): Fax.State { val end = System.currentTimeMillis() + secs * 1000L while (System.currentTimeMillis() < end) { @@ -116,6 +121,7 @@ class FaxAppTest { throw AssertionError("still going: ${Fax.state.value}\n" + (ModemState.log.flow.value.takeLast(40) + log.takeLast(40)).joinToString("\n")) } + /** a 90-line text document sent: two fine A4 pages with text on them, the remote's ID both ways, in the list of faxes, the hub free again */ @Test fun aTextDocumentSent() { val doc = File(ctx.cacheDir, "letter.txt").apply { @@ -153,6 +159,7 @@ class FaxAppTest { assertTrue(!ModemState.dte.claimed) } + /** a fax answered: its pages saved as a PDF in the app's Downloads, every pel as sent, in the list of faxes */ @Test fun aFaxAnsweredAndSaved() { val c = other() @@ -195,6 +202,7 @@ class FaxAppTest { return { sb.toString() } } + /** waits until [cond], up to [secs] s; fails with the log's end */ private fun waitFor(what: String, secs: Int = 30, cond: () -> Boolean) { val end = System.currentTimeMillis() + secs * 1000L while (!cond()) { @@ -203,6 +211,7 @@ class FaxAppTest { } } + /** with adaptive answer a fax machine's call is answered as FAX and received by the app on its own */ @Test fun aFaxMachinesCallAnsweredAdaptively() { // the service's start: adaptive answer on (in data mode, as the terminal has it) @@ -233,6 +242,7 @@ class FaxAppTest { assertTrue(!ModemState.dte.claimed) } + /** with adaptive answer a modem's call is answered as DATA, a CONNECT for the terminal, no fax */ @Test fun aDataCallAnsweredAdaptively() { val seen = hubText() diff --git a/app/src/test/java/com/neodesktop/dmodem/fax/FaxCallTest.kt b/app/src/test/java/com/neodesktop/dmodem/fax/FaxCallTest.kt index 9da21b6..deaa500 100644 --- a/app/src/test/java/com/neodesktop/dmodem/fax/FaxCallTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/fax/FaxCallTest.kt @@ -40,12 +40,14 @@ class FaxCallTest { private lateinit var b: String private val ends = ArrayList() + /** native-test's fax_line (or DMODEM_FAX_LINE's), if built, or null */ private fun modemTest(): File? = listOfNotNull( System.getenv("DMODEM_FAX_LINE"), "../build-host/fax_line", "build-host/fax_line", ).map { File(it) }.firstOrNull { it.canExecute() } + /** fax_line started, both modems' ptys from its log */ @Before fun setUp() { val mt = modemTest() @@ -61,6 +63,7 @@ class FaxCallTest { b = log.first { it.startsWith("created modemB: ") }.substringAfter(": ") } + /** the ptys closed, fax_line stopped */ @After fun tearDown() { ends.forEach { it.close() } @@ -95,6 +98,7 @@ class FaxCallTest { ends.add(this) } + /** its pty closed */ fun close() { runCatching { input.close() } runCatching { output.close() } @@ -102,6 +106,7 @@ class FaxCallTest { var rates: List = emptyList() + /** class 1 on, as caller (X3) or answerer, and the modem's rates up to [maxBps] */ fun setUp(caller: Boolean, maxBps: Int = 14400) { assertEquals("OK", c1.command("E0")) assertEquals("OK", c1.command(if (caller) "X3+FCLASS=1" else "+FCLASS=1")) @@ -109,6 +114,7 @@ class FaxCallTest { } } + /** whether fax_line or a pty logged [what] within [secs] s */ private fun waitLog(what: String, secs: Int = 30): Boolean { val end = System.currentTimeMillis() + secs * 1000L while (System.currentTimeMillis() < end) { @@ -118,14 +124,18 @@ class FaxCallTest { return false } + /** the log's last 80 lines */ private fun dump() = log.takeLast(80).joinToString("\n") + /** our sender to our receiver with ECM */ @Test fun ourSenderToOurReceiver() = ourCall(ecm = true) + /** our sender to our receiver without ECM */ @Test fun ourSenderToOurReceiverWithoutEcm() = ourCall(ecm = false) + /** two fine pages from our sender to our receiver, [ecm] or not: both sides' IDs and ECM, a fast rate, every pel as sent */ private fun ourCall(ecm: Boolean) { val pages = listOf(FaxTestPage.of(true, rows = 600, seed = 1), FaxTestPage.of(true, rows = 300, seed = 2)) val tx = PtyEnd(a).apply { setUp(caller = true) } @@ -166,11 +176,14 @@ class FaxCallTest { // efax --------------------------------------------------------------- + /** whether efax and efix are installed */ private fun efaxThere() = File("/usr/bin/efax").canExecute() && File("/usr/bin/efix").canExecute() + /** [cmd] run in [dir], its output to a file there: its exit status */ private fun run(vararg cmd: String, dir: File): Int = ProcessBuilder(*cmd).directory(dir).redirectErrorStream(true).redirectOutput(File(dir, "${File(cmd[0]).name}.out")).start().waitFor() + /** efax sends us a page: received, below efax's blank header band, as it was */ @Test fun efaxSendsToUs() { assumeTrue("efax isn't installed", efaxThere()) @@ -208,6 +221,7 @@ class FaxCallTest { assertArrayEquals(page.bits, g.bits.copyOfRange(band * g.stride, g.bits.size)) } + /** we send efax two pages, without ECM: its files, converted back, as they were sent */ @Test fun weSendToEfax() { assumeTrue("efax isn't installed", efaxThere()) diff --git a/app/src/test/java/com/neodesktop/dmodem/fax/FaxPdfTest.kt b/app/src/test/java/com/neodesktop/dmodem/fax/FaxPdfTest.kt index a8bcd4e..3fdf868 100644 --- a/app/src/test/java/com/neodesktop/dmodem/fax/FaxPdfTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/fax/FaxPdfTest.kt @@ -26,6 +26,7 @@ class FaxPdfTest { return dir.listFiles { f -> f.name.startsWith("img-") }!!.sortedBy { it.name }.map { readPbm(it) } } + /** a P4 PBM file as a page (1 black), its header's comments skipped */ fun readPbm(f: File): FaxPage { val d = f.readBytes() var i = 0 @@ -45,6 +46,7 @@ class FaxPdfTest { } } + /** two pages written as a small PDF read back by pdfimages exactly, and drawn by pdftoppm 1728 pels across at 204 dpi */ @Test fun pagesReadBackExactly() { assumeTrue("poppler-utils isn't installed", File("/usr/bin/pdfimages").canExecute()) diff --git a/app/src/test/java/com/neodesktop/dmodem/fax/FaxPty.kt b/app/src/test/java/com/neodesktop/dmodem/fax/FaxPty.kt index 4d68b26..badc82a 100644 --- a/app/src/test/java/com/neodesktop/dmodem/fax/FaxPty.kt +++ b/app/src/test/java/com/neodesktop/dmodem/fax/FaxPty.kt @@ -66,8 +66,10 @@ class FaxLineProcess(cmd: List) : AutoCloseable { return Class1(io) { line -> log.add("$tag: $line"); TestLogs.note(tag, line) } } + /** the log's last [n] lines */ fun dump(n: Int = 80) = log.takeLast(n).joinToString("\n") + /** the ptys closed, the program stopped (killed if it's still there after 5 s) */ override fun close() { closers.forEach { runCatching { it() } } proc.destroy() diff --git a/app/src/test/java/com/neodesktop/dmodem/fax/SipFaxTest.kt b/app/src/test/java/com/neodesktop/dmodem/fax/SipFaxTest.kt index 7f73a64..4db5aa4 100644 --- a/app/src/test/java/com/neodesktop/dmodem/fax/SipFaxTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/fax/SipFaxTest.kt @@ -20,11 +20,13 @@ import org.junit.Test class SipFaxTest { private var line: FaxLineProcess? = null + /** the line program stopped */ @After fun tearDown() { line?.close() } + /** two fine pages from the engine to dmodemd over SIP, [ecm] or not: every pel as sent, both IDs, and T.38 taken if [t38], else not */ private fun call(t38: Boolean, ecm: Boolean) { val bin = nativeTool("DMODEM_SIP_FAX_LINE", "sip_fax_line") assumeTrue("sip_fax_line isn't built (native-test)", bin != null) @@ -79,12 +81,15 @@ class SipFaxTest { assertEquals(l.log.filter { it.contains("t38", ignoreCase = true) }.take(30).joinToString("\n"), t38, onT38) } + /** over T.38 without ECM */ @Test fun overT38() = call(t38 = true, ecm = false) + /** over T.38 in ECM */ @Test fun overT38InEcm() = call(t38 = true, ecm = true) + /** on audio, T.38 off, in ECM */ @Test fun onAudioWithoutT38() = call(t38 = false, ecm = true) } diff --git a/app/src/test/java/com/neodesktop/dmodem/fax/T30InteropTest.kt b/app/src/test/java/com/neodesktop/dmodem/fax/T30InteropTest.kt index a8602cf..9a62cfe 100644 --- a/app/src/test/java/com/neodesktop/dmodem/fax/T30InteropTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/fax/T30InteropTest.kt @@ -27,6 +27,7 @@ class T30InteropTest { private var line: FaxLineProcess? = null + /** t30_line stopped */ @After fun tearDown() { line?.close() @@ -43,6 +44,7 @@ class T30InteropTest { return c } + /** t30_line's log's end */ private fun dump() = line!!.dump() /** the machine's RESULT line's fields: ok, pages, bps, ecm */ @@ -58,6 +60,7 @@ class T30InteropTest { return mapOf("ok" to f[1], "pages" to f[3], "bps" to f[5], "ecm" to f[7], "why" to f.drop(8).joinToString(" ")) } + /** two pages from us to D-Modem-RE's T.30, [ecm] or not, on a line [snr] dB clean if given: it got them, every pel, as we sent them */ private fun theyReceive(ecm: Boolean, snr: Double = 0.0) { val dir = tmp.newFolder() val args = mutableListOf("receive", dir.path) @@ -85,6 +88,7 @@ class T30InteropTest { } } + /** D-Modem-RE's T.30 sends us its pages, [ecm] or not, at most [maxBps], [snr] dB clean if given: every pel as it sent them; the pages */ private fun theySend(ecm: Boolean, snr: Double = 0.0, maxBps: Int = 14400): List { val dir = tmp.newFolder() val args = mutableListOf("send", dir.path, "--bps", maxBps.toString()) @@ -113,12 +117,15 @@ class T30InteropTest { return got } + /** we send in ECM */ @Test fun weSendInEcm() = theyReceive(ecm = true) + /** we send without ECM */ @Test fun weSendWithoutEcm() = theyReceive(ecm = false) + /** we receive in ECM */ @Test fun weReceiveInEcm() { theySend(ecm = true) @@ -131,12 +138,14 @@ class T30InteropTest { theySend(ecm = false) } + /** we send in ECM on a noisy line (21 dB), its spoilt frames sent again */ @Test fun weSendInEcmOnANoisyLine() { theyReceive(ecm = true, snr = 21.0) println("PPRs to us: " + line!!.log.count { it.contains("<- frame ff 13 bc") }) } + /** we receive in ECM on a noisy line (21 dB), its spoilt frames asked for again */ @Test fun weReceiveInEcmOnANoisyLine() { theySend(ecm = true, snr = 21.0) diff --git a/app/src/test/java/com/neodesktop/dmodem/local/DistrosTest.kt b/app/src/test/java/com/neodesktop/dmodem/local/DistrosTest.kt index 165481a..442606c 100644 --- a/app/src/test/java/com/neodesktop/dmodem/local/DistrosTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/local/DistrosTest.kt @@ -22,6 +22,7 @@ import java.nio.file.Paths import java.security.MessageDigest import java.util.zip.GZIPOutputStream +/** [f]'s SHA-256, in hex */ private fun sha256(f: File) = MessageDigest.getInstance("SHA-256").digest(f.readBytes()).joinToString("") { "%02x".format(it) } /** @@ -40,8 +41,11 @@ class DistrosTest { /** URLs answered from a map, downloads copied from local files */ private class FakeHttp(val pages: Map, val files: Map = emptyMap()) : Http() { val asked = ArrayList() + /** the page at [url], kept as asked; a 404 if there's none */ override fun text(url: String): String { asked.add(url); return pages[url] ?: throw IOException("404 $url") } + /** the local file's size for [url], or -1 */ override fun size(url: String): Long = files[url]?.length() ?: -1 + /** the local file for [url] copied to [to]: its SHA-256 */ override fun download(url: String, to: File, size: Long, progress: (Float) -> Unit): String { val f = files[url] ?: throw IOException("404 $url") f.copyTo(to, overwrite = true) @@ -62,6 +66,7 @@ class DistrosTest { archlinux;current;amd64;default;20261016_04:18;/images/archlinux/current/amd64/default/20261016_04:18/ """.trimIndent() + /** the Linux Containers' index read: the newest Fedora by number, its checksum; Debian only for the machines it's built for, Arch not for this one */ @Test fun theLinuxContainersIndex() { val rows = Distro.parseLxcIndex(index) @@ -88,6 +93,7 @@ class DistrosTest { assertTrue(e?.message, e?.message!!.contains("isn't built for this phone's processor")) } + /** Ubuntu's newest point release for the machine, by number, with its checksum */ @Test fun ubuntusNewestPointRelease() { val base = "${Distro.UBUNTU_MIRROR}/24.04/release" @@ -107,6 +113,7 @@ class DistrosTest { assertEquals("Ubuntu 24.04.10 LTS", r.name) } + /** a custom system's ID from its name, lower-case and hyphenated */ @Test fun customNames() { assertEquals("custom-my-arch-build-2", Distro.customId("My Arch build #2")) @@ -132,6 +139,7 @@ class DistrosTest { return t } + /** [dir] as a tarball made by tar, gzipped or xz'd for "gz" and "xz" */ private fun tar(dir: File, compress: String): File { assumeTrue("no tar here", File("/usr/bin/tar").canExecute() || File("/bin/tar").canExecute()) val plain = File(tmp.root, "t-${System.nanoTime()}.tar") @@ -145,8 +153,10 @@ class DistrosTest { } } + /** a system under the test's folder, its name server 10.0.0.53 */ private fun system(id: String) = LinuxSystem(File(tmp.root, "linux/$id"), tmp.root, tmp.newFolder(), nameServers = { listOf("10.0.0.53") }) + /** installed from a .tar.gz, a .tar.xz (its system in one folder, moved up) and a plain .tar, the download gone */ @Test fun installedFromEachKindOfArchive() { for (kind in listOf("gz", "xz", "tar")) { @@ -162,6 +172,7 @@ class DistrosTest { } } + /** set up for proot: the resolver a file, apt's and pacman's sandboxes off (once), mtab, the prompt, root's shell through links resolved inside */ @Test fun setUpForProot() { val f = tar(tree(), "gz") @@ -197,6 +208,7 @@ class DistrosTest { assertFalse(sys.existsInside("/bin/host-only/linux")) } + /** a wrong checksum leaves nothing; a tarball that isn't a Linux system isn't installed */ @Test fun aWrongChecksumOrNotASystemLeavesNothing() { val f = tar(tree(), "gz") @@ -214,6 +226,7 @@ class DistrosTest { assertNull(sys.info) } + /** an Alpine installed by the first release is still known by its name */ @Test fun theFirstReleasesAlpineStillKnown() { val sys = system("alpine") diff --git a/app/src/test/java/com/neodesktop/dmodem/local/LinuxSystemTest.kt b/app/src/test/java/com/neodesktop/dmodem/local/LinuxSystemTest.kt index 1146d21..a1e15f8 100644 --- a/app/src/test/java/com/neodesktop/dmodem/local/LinuxSystemTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/local/LinuxSystemTest.kt @@ -94,15 +94,18 @@ class LinuxSystemTest { } } + /** a system under the test's folder, with the phone's storage, 9.9.9.9 and this host's proxy */ private fun newSystem(id: String) = LinuxSystem( File(Setup.base, id), Setup.programs, File(Setup.base, "tmp"), storage = { Setup.storage }, nameServers = { listOf("9.9.9.9") }, extraEnv = proxyEnv(), ) + /** once for the class: proot built, the storage, Alpine installed; skipped where it can't be */ @Before fun setUp() { Setup.skipped?.let { assumeTrue(it, false) } if (Setup.done) return + /** skipped from now on, saying [why] */ fun skip(why: String) { Setup.skipped = why; assumeTrue(why, false) } if (Setup.machine == null) skip("no Linux for ${System.getProperty("os.arch")}") if (!runCatching { URL(Distro.ALPINE_MIRROR).openConnection().apply { connectTimeout = 10_000 }.getInputStream().close(); true }.getOrDefault(false)) skip("Alpine can't be reached") @@ -131,6 +134,7 @@ class LinuxSystemTest { /** the shell's output, its colours left out; the cursor's position told when asked (busybox's shell asks, as a terminal answers) */ private class Screen(private val link: LocalLink) : TerminalLink.Listener { private val sb = StringBuilder() + /** kept, a cursor position report asked for answered */ override fun onData(data: ByteArray, length: Int) { val t = String(data, 0, length) if (t.contains("\u001b[6n")) link.write("\u001b[1;1R".toByteArray()) @@ -142,6 +146,7 @@ class LinuxSystemTest { } } + /** a shell on [sys], 100 by 30, started */ private fun shell(sys: LinuxSystem): Pair { val l = sys.link(100, 30) val s = Screen(l) @@ -150,6 +155,7 @@ class LinuxSystemTest { return l to s } + /** waits until [cond] holds for [s]'s text, up to [secs] s; fails with the screen */ private fun waitFor(what: String, s: Screen, secs: Int = 30, cond: (String) -> Boolean) { val end = System.currentTimeMillis() + secs * 1000L while (!cond(s.text)) { @@ -158,6 +164,7 @@ class LinuxSystemTest { } } + /** Alpine installed with its name, the resolver and the prompt set up; made-up /proc files only for those hidden */ @Test fun alpineInstalledAndSetUp() { val sys = Setup.alpine @@ -171,6 +178,7 @@ class LinuxSystemTest { assertTrue(hidden.command().any { it.endsWith(":/proc/stat") }) } + /** a root shell with the phone's storage in /sdcard, its size and hard links; exit's status 0 */ @Test fun aRootShellWithThePhonesStorage() { val (l, s) = shell(Setup.alpine) @@ -191,6 +199,7 @@ class LinuxSystemTest { assertEquals(0, l.exitStatus) } + /** Alpine's apk adds Lua and runs it */ @Test fun apkAddsPackages() = packageManager(Setup.alpine, "alpine") @@ -266,6 +275,7 @@ class LinuxSystemTest { assertTrue(failures.joinToString("\n\n"), failures.isEmpty()) } + /** a system removed without what its link to the phone's storage leads to */ @Test fun removedLeavingTheStorage() { val other = newSystem("other") @@ -284,8 +294,11 @@ class LinuxSystemTest { val modem = object : TerminalLink { override val state = kotlinx.coroutines.flow.MutableStateFlow(TerminalLink.State.Open) val listeners = java.util.concurrent.CopyOnWriteArrayList() + /** takes [l] for what the modem says */ override fun addListener(l: TerminalLink.Listener) { listeners.add(l) } + /** no more of it to [l] */ override fun removeListener(l: TerminalLink.Listener) { listeners.remove(l) } + /** kept as sent; a command's CR answered */ override fun write(data: ByteArray, offset: Int, length: Int): Boolean { val t = String(data, offset, length, Charsets.ISO_8859_1) got.append(t) diff --git a/app/src/test/java/com/neodesktop/dmodem/local/LocalShellTest.kt b/app/src/test/java/com/neodesktop/dmodem/local/LocalShellTest.kt index b5984a7..3c219b4 100644 --- a/app/src/test/java/com/neodesktop/dmodem/local/LocalShellTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/local/LocalShellTest.kt @@ -27,6 +27,7 @@ class LocalShellTest { private val links = ArrayList() companion object { + /** pty.c built for the host and loaded, once for the class */ @BeforeClass @JvmStatic fun buildPty() = Pty.load(hostPty()) @@ -50,18 +51,22 @@ class LocalShellTest { } } + /** the shells started closed */ @After fun tearDown() = links.forEach { it.close() } private class Screen : TerminalLink.Listener { private val sb = StringBuilder() + /** kept, as it came */ override fun onData(data: ByteArray, length: Int) { synchronized(sb) { sb.append(String(data, 0, length)) } } val text get() = synchronized(sb) { sb.toString() } + /** what came so far forgotten */ fun clear() = synchronized(sb) { sb.setLength(0) } } + /** [link] started, a [Screen] taking what it says */ private fun start(link: LocalLink): Screen { links.add(link) val s = Screen() @@ -70,6 +75,7 @@ class LocalShellTest { return s } + /** waits until [cond] holds for [s]'s text, up to 10 s; fails with the screen */ private fun waitFor(what: String, s: Screen, cond: (String) -> Boolean) { val end = System.currentTimeMillis() + 10_000 while (!cond(s.text)) { @@ -78,11 +84,14 @@ class LocalShellTest { } } + /** an interactive /bin/sh in the test's folder, [cols] by [rows] */ private fun sh(cols: Int = 80, rows: Int = 24) = LocalLink(listOf("/bin/sh", "-i"), mapOf("PATH" to "/usr/bin:/bin", "PS1" to "$ ", "TERM" to "xterm-256color"), tmp.root.path, cols, rows) + /** [s] typed on the shell's terminal */ private fun LocalLink.type(s: String) = assertTrue(write(s.toByteArray())) + /** a shell on its own pty: its output, its window's size and changes, the directory it started in */ @Test fun aShellOnItsOwnTerminal() { val l = sh() @@ -100,6 +109,7 @@ class LocalShellTest { waitFor("its directory", s) { it.contains(tmp.root.canonicalPath) || it.contains(tmp.root.path) } } + /** ^C interrupts the running job, not the shell */ @Test fun ctrlCInterruptsTheJobNotTheShell() { val l = sh() @@ -114,6 +124,7 @@ class LocalShellTest { assertEquals(TerminalLink.State.Open, l.state.value) } + /** the shell's exit: closed with its status, nothing written after */ @Test fun itsExitAndItsStatus() { val l = sh() @@ -126,6 +137,7 @@ class LocalShellTest { assertTrue("nothing written after", !l.write("x".toByteArray())) } + /** closed: the shell and its background jobs hung up */ @Test fun closedHangsUpTheShellAndItsJobs() { val l = sh() @@ -144,6 +156,7 @@ class LocalShellTest { assertTrue("the job went with it", !marker.exists()) } + /** a shell that can't be run: status 127 and the exec failure on the screen */ @Test fun noSuchShell() { val l = LocalLink(listOf("/nonexistent/sh"), emptyMap(), null) @@ -154,6 +167,7 @@ class LocalShellTest { assertTrue(s.text, s.text.contains("exec failed: /nonexistent/sh")) } + /** mksh with the app's start-up file: the coloured prompt, the environment, the aliases; a start-up file the user changed kept */ @Test fun theAppsShellWithItsStartUpFile() { assumeTrue("mksh (Android's shell) isn't installed", File("/usr/bin/mksh").canExecute()) diff --git a/app/src/test/java/com/neodesktop/dmodem/local/TarTest.kt b/app/src/test/java/com/neodesktop/dmodem/local/TarTest.kt index 7940eef..bea4924 100644 --- a/app/src/test/java/com/neodesktop/dmodem/local/TarTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/local/TarTest.kt @@ -20,6 +20,7 @@ class TarTest { @get:Rule val tmp = TemporaryFolder() + /** [dir] as a tarball the system's tar makes in [format] */ private fun tar(dir: File, format: String): File { assumeTrue("no tar here", File("/usr/bin/tar").canExecute() || File("/bin/tar").canExecute()) val out = File(tmp.root, "t-$format.tar") @@ -30,6 +31,7 @@ class TarTest { return out } + /** a GNU and a pax tar unpacked as made: modes, symbolic and hard links, long names, a big file, an empty folder */ @Test fun aTreeAsTarMadeIt() { val src = tmp.newFolder("src") @@ -65,6 +67,7 @@ class TarTest { /** a tar written by hand: entries the system's tar wouldn't make */ private class Writer { val out = ByteArrayOutputStream() + /** an entry: a ustar header for [name] of [type], then [data] padded to 512 */ fun entry(name: String, type: Char, data: ByteArray = ByteArray(0), link: String = "") { val h = ByteArray(512) name.toByteArray().copyInto(h, 0) @@ -79,9 +82,11 @@ class TarTest { out.write(data) out.write(ByteArray((512 - data.size % 512) % 512)) } + /** the tar so far, with its two zero blocks to end it */ fun bytes() = out.toByteArray() + ByteArray(1024) } + /** entries escaping the destination (.., through a link, a hard link out) refused, absolute names kept inside */ @Test fun nothingWrittenOutside() { val outside = tmp.newFolder("outside") @@ -101,6 +106,7 @@ class TarTest { assertFalse(File(dest, "hard").exists()) } + /** a tree removed, read-only folders too, without following its links out */ @Test fun removedWithoutFollowingLinks() { val outside = tmp.newFolder("storage") diff --git a/app/src/test/java/com/neodesktop/dmodem/modem/BluetoothModemTest.kt b/app/src/test/java/com/neodesktop/dmodem/modem/BluetoothModemTest.kt index b0412c1..4e0f871 100644 --- a/app/src/test/java/com/neodesktop/dmodem/modem/BluetoothModemTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/modem/BluetoothModemTest.kt @@ -25,12 +25,14 @@ class BluetoothModemTest { private val ctx: Context = ApplicationProvider.getApplicationContext() private val adapter get() = ctx.getSystemService(BluetoothManager::class.java).adapter + /** [ok] within 5 s, or fails saying [what] */ private fun waitUntil(what: String, ok: () -> Boolean) { val end = System.currentTimeMillis() + 5000 while (!ok() && System.currentTimeMillis() < end) Thread.sleep(20) assertTrue(what, ok()) } + /** a paired modem connected over its Dial-Up Networking service, the hub's AT command reaching it and its OK heard */ @Test fun theTerminalTalksToIt() { shadowOf(ctx as Application).grantPermissions(Manifest.permission.BLUETOOTH_CONNECT) @@ -56,6 +58,7 @@ class BluetoothModemTest { hub.detach() } + /** with Bluetooth off, connecting fails saying so */ @Test fun offSaysSo() { shadowOf(ctx as Application).grantPermissions(Manifest.permission.BLUETOOTH_CONNECT) diff --git a/app/src/test/java/com/neodesktop/dmodem/modem/CallTonesTest.kt b/app/src/test/java/com/neodesktop/dmodem/modem/CallTonesTest.kt index b4ee7ae..f0823cf 100644 --- a/app/src/test/java/com/neodesktop/dmodem/modem/CallTonesTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/modem/CallTonesTest.kt @@ -21,7 +21,9 @@ class CallTonesTest { private class FakePlayer : CallProgress.Player { val heard = CopyOnWriteArrayList() @Volatile var now: CallTones.Kind? = null + /** kept as heard, [kind] now playing */ override fun play(kind: CallTones.Kind, ms: Int) { heard.add("$kind $ms"); now = kind } + /** the tone playing stopped (only [only], if given), kept as heard */ override fun stop(only: CallTones.Kind?) { if (only != null && now != only) return heard.add("stop" + (only?.let { " $it" } ?: "")) @@ -31,11 +33,13 @@ class CallTonesTest { private var clock = 100_000L + /** a call's progress on a fake player, on the test's clock */ private fun progress(): Pair { val p = FakePlayer() return CallProgress(p) { clock } to p } + /** BUSY from the modem, split or not, plays the busy tone */ @Test fun busyWhenTheModemSaysSo() { val (cp, p) = progress() @@ -46,6 +50,7 @@ class CallTonesTest { assertEquals(listOf("BUSY 4000"), p.heard) } + /** a dial ending in NO CARRIER or NO DIALTONE before a connect plays congestion; a call that connected, none */ @Test fun congestionForADialThatNeverGotThrough() { val (cp, p) = progress() @@ -69,6 +74,7 @@ class CallTonesTest { assertEquals(listOf("CONGESTION 4000"), p.heard) } + /** an answered call's NO CARRIER plays no tone; long after the ring it's a dial again */ @Test fun aCallAnsweredIsntOneDialled() { val (cp, p) = progress() @@ -85,6 +91,7 @@ class CallTonesTest { assertEquals(listOf("CONGESTION 4000"), p.heard) } + /** the other phone ringing plays the ringing tone; BUSY there the busy tone, left playing; answered, the ringing stopped */ @Test fun theOtherPhoneRinging() { val (cp, p) = progress() @@ -108,15 +115,20 @@ class CallTonesTest { private class FakeSink : ModemSpeaker.Sink { val got = ByteArrayOutputStream() @Volatile var closed = false + /** kept, as written */ override fun write(pcm: ByteArray, n: Int) = synchronized(got) { got.write(pcm, 0, n) } + /** any volume taken */ override fun volume(v: Float) {} + /** closed, for the test to see */ override fun close() { closed = true } + /** the samples written so far, 16-bit little-endian */ fun samples(): ShortArray = synchronized(got) { val b = got.toByteArray() ShortArray(b.size / 2) { ((b[2 * it].toInt() and 0xff) or (b[2 * it + 1].toInt() shl 8)).toShort() } } } + /** [f] Hz's level in [x] from [from], over [n] samples (Goertzel's) */ private fun level(x: ShortArray, f: Double, from: Int, n: Int): Double { val k = 2 * cos(2 * PI * f / 8000) var s1 = 0.0 @@ -129,6 +141,7 @@ class CallTonesTest { return 2 * sqrt(s1 * s1 + s2 * s2 - k * s1 * s2) / n } + /** a second of the UK's dial tone (350 and 440 Hz, not 400), then the tail's silence; closed, nothing playing */ @Test fun aSecondOfTheCountrysDialTone() { val sinks = CopyOnWriteArrayList() @@ -151,6 +164,7 @@ class CallTonesTest { assertTrue(System.nanoTime() - t0 < 5_000_000_000) } + /** the ringing tone played until stopped (not by another's stop); off, nothing plays; the preview plays all four anyway */ @Test fun stoppedAndTurnedOff() { val sinks = CopyOnWriteArrayList() diff --git a/app/src/test/java/com/neodesktop/dmodem/modem/DteHubTest.kt b/app/src/test/java/com/neodesktop/dmodem/modem/DteHubTest.kt index 816469a..99b3f5b 100644 --- a/app/src/test/java/com/neodesktop/dmodem/modem/DteHubTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/modem/DteHubTest.kt @@ -21,6 +21,7 @@ class DteHubTest { val hubIn = PipedInputStream(toHub, 65536) } + /** every listener gets all the modem says */ @Test fun everyListenerGetsTheModemsOutput() { val hub = DteHub() @@ -39,6 +40,7 @@ class DteHubTest { hub.detach() } + /** writes reach the modem only while one's attached */ @Test fun writesGoToTheModemUntilDetached() { val hub = DteHub() @@ -57,6 +59,7 @@ class DteHubTest { assertFalse(hub.write("AT\r")) } + /** listeners stay across a new modem attached, writes going to the new one only */ @Test fun listenersStayAcrossAModemRestart() { val hub = DteHub() diff --git a/app/src/test/java/com/neodesktop/dmodem/modem/IncomingCallsTest.kt b/app/src/test/java/com/neodesktop/dmodem/modem/IncomingCallsTest.kt index e4005b7..ae6ecfc 100644 --- a/app/src/test/java/com/neodesktop/dmodem/modem/IncomingCallsTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/modem/IncomingCallsTest.kt @@ -12,6 +12,7 @@ class IncomingCallsTest { private var clock = 1_000_000L private val calls = IncomingCalls { clock } + /** a RING, split or not, a call ringing; the next one counted, since unchanged; off hook it's over, a RING then no call */ @Test fun ringingThenAnswered() { calls.modemText("\r\nRI") @@ -32,6 +33,7 @@ class IncomingCallsTest { assertNull(calls.state.value) } + /** the other phone's name, given before the first RING or after it, as the call's caller */ @Test fun theOtherPhoneByName() { calls.caller("D-Modem on Pixel 8") @@ -45,6 +47,7 @@ class IncomingCallsTest { assertEquals("192.168.1.20", calls.state.value!!.from) } + /** no RING for 9 s: the caller gave up; 7 s still ringing */ @Test fun theCallerGivesUp() { calls.modemText("RING\r\n") @@ -56,6 +59,7 @@ class IncomingCallsTest { assertNull(calls.state.value) } + /** ignored, it rings on out of sight; once over, the next call shows; RINGING isn't RING */ @Test fun ignoredUntilItsOver() { calls.modemText("RING\r\n") diff --git a/app/src/test/java/com/neodesktop/dmodem/modem/LineRecordingsTest.kt b/app/src/test/java/com/neodesktop/dmodem/modem/LineRecordingsTest.kt index 368b13f..4628ffc 100644 --- a/app/src/test/java/com/neodesktop/dmodem/modem/LineRecordingsTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/modem/LineRecordingsTest.kt @@ -17,6 +17,7 @@ import java.io.File class LineRecordingsTest { private val ctx: Context = ApplicationProvider.getApplicationContext() + /** recordings listed newest first, other files left out; pruned, the newest few kept */ @Test fun newestFirstLastKept() { val base = LineRecordings.path(ctx)!! diff --git a/app/src/test/java/com/neodesktop/dmodem/modem/LogFormatTest.kt b/app/src/test/java/com/neodesktop/dmodem/modem/LogFormatTest.kt index e0d89e0..d6a9468 100644 --- a/app/src/test/java/com/neodesktop/dmodem/modem/LogFormatTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/modem/LogFormatTest.kt @@ -15,6 +15,7 @@ class LogFormatTest { private val t = 1792987923417L private val lastOfDay = 1793059199999L + /** the default stamp on each line, a line for each new day */ @Test fun stampedWithADayLine() = assertEquals( listOf("---- Monday 26 October 2026 ----", "[04:12:03.417] app: one", "[23:59:59.999] app: two", @@ -22,12 +23,14 @@ class LogFormatTest { LogFormat.render(listOf(LogLine(t, "app: one"), LogLine(lastOfDay, "app: two"), LogLine(lastOfDay + 1, "app: three")), LogFormat.DEFAULT, utc), ) + /** no stamp: the lines as they are, still the day's line */ @Test fun noStamp() = assertEquals( listOf("---- Monday 26 October 2026 ----", "app: one"), LogFormat.render(listOf(LogLine(t, "app: one")), "", utc), ) + /** another pattern's stamp; one that isn't valid, the default's */ @Test fun otherPatternsAndBadOnes() { assertEquals("2026-10-26T04:12:03 app: one", LogFormat.render(listOf(LogLine(t, "app: one")), "yyyy-MM-dd'T'HH:mm:ss", utc)[1]) @@ -37,6 +40,7 @@ class LogFormatTest { assertEquals("[04:12:03.417] app: one", LogFormat.render(listOf(LogLine(t, "app: one")), "HH:mm:ss.msec", utc)[1]) } + /** the buffer keeps its last lines, each with the time it was added */ @Test fun theBufferTimesItsLines() { var now = t diff --git a/shared/src/commonMain/kotlin/com/neodesktop/dmodem/transfer/ZModem.kt b/shared/src/commonMain/kotlin/com/neodesktop/dmodem/transfer/ZModem.kt index f267e47..36f2da5 100644 --- a/shared/src/commonMain/kotlin/com/neodesktop/dmodem/transfer/ZModem.kt +++ b/shared/src/commonMain/kotlin/com/neodesktop/dmodem/transfer/ZModem.kt @@ -19,6 +19,7 @@ class ZModem( ) { private var p = Progress() + /** [f] applied to the progress so far, and that passed on */ private fun report(f: (Progress) -> Progress) { p = f(p) progress(p) @@ -35,10 +36,13 @@ class ZModem( /** ZF0 (ZF0 is p[3], as the spec numbers the flags) */ val f0: Int get() = p[3].toInt() and 0xff + /** the header's type by name, and its position */ override fun toString() = "Header(${NAMES.getOrElse(type) { "$type" }}, $pos)" companion object { + /** a header of [type] carrying [pos] (ZP0 lowest) */ fun pos(type: Int, pos: Long) = Header(type, ByteArray(4) { ((pos shr (8 * it)) and 0xff).toByte() }) + /** a header of [type] carrying flags ZF0..ZF3 (ZF0 in p[3]) */ fun flags(type: Int, f0: Int, f1: Int = 0, f2: Int = 0, f3: Int = 0) = Header(type, byteArrayOf(f3.toByte(), f2.toByte(), f1.toByte(), f0.toByte())) } @@ -61,6 +65,7 @@ class ZModem( io.write(b.toByteArray()) } + /** [v] as two lower-case hex digits */ private fun hex2(v: Int): ByteArray = v.toString(16).padStart(2, '0').encodeToByteArray() /** a header in binary (the sender's): CRC-32 when the receiver can */ @@ -140,6 +145,7 @@ class ZModem( } } + /** the next octet from the line; an error when none comes in time */ private fun readByte(): Int { val c = io.read(timeoutMs) if (c < 0) throw IOException("the other side went quiet") @@ -186,6 +192,7 @@ class ZModem( } } + /** a binary header's type, ZP0..ZP3 and check (CRC-32 if [c32]): the header, or null if it was damaged */ private fun readBinHeader(c32: Boolean): Header? { val raw = ByteArray(5) for (i in 0 until 5) { @@ -213,6 +220,7 @@ class ZModem( /** how the sender's data comes: CRC-32 when its headers did */ private var rxCrc32 = false + /** a hex header's seven octets and its CR LF: the header, or null if its digits or check were bad */ private fun readHexHeader(): Header? { val raw = ByteArray(7) for (i in 0 until 7) { @@ -229,6 +237,7 @@ class ZModem( return Header(raw[0].toInt() and 0xff, raw.copyOfRange(1, 5)) } + /** a hex digit's value, -1 if [c] isn't one */ private fun hexDigit(c: Int): Int = when (c) { in '0'.code..'9'.code -> c - '0'.code in 'a'.code..'f'.code -> c - 'a'.code + 10 @@ -272,6 +281,7 @@ class ZModem( fun receive(into: Incoming): List { val names = ArrayList() var errors = 0 + /** our ZRINIT: full duplex, overlapped I/O, CRC-32 */ fun zrinit() = sendHex(Header.flags(ZRINIT, CANFDX or CANOVIO or CANFC32)) zrinit() var lastHeaderAt = monotonicMs() @@ -342,10 +352,12 @@ class ZModem( // comes of its stream from before, broken headers in its data, isn't an error and // isn't asked for again: each ZRPOS a restart of its own, its leftovers more of them) var rposAt = 0L + /** a ZRPOS for [pos] sent, and when noted */ fun rpos() { sendHex(Header.pos(ZRPOS, pos)) rposAt = monotonicMs() } + /** whether a ZRPOS is still too recent for the sender to have heard it */ fun waiting() = monotonicMs() - rposAt < RPOS_GRACE_MS try { out.use { o -> @@ -449,6 +461,7 @@ class ZModem( io.write("OO".encodeToByteArray()) } + /** ZRQINIT until the receiver's ZRINIT (answering a ZCHALLENGE on the way): that header */ private fun waitForZrinit(): Header { var tries = 0 sendHex(Header(ZRQINIT)) @@ -472,6 +485,7 @@ class ZModem( } } + /** the next header, or null when it was damaged or didn't come (a cancel still thrown) */ private fun readHeaderOrNull(): Header? = try { readHeader() } catch (e: TransferCancelled) { throw e } catch (_: IOException) { null } @@ -517,6 +531,7 @@ class ZModem( var pos = 0L private set + /** the file positioned at [to]: reopened first to go back, skipped or read forward */ fun seek(to: Long) { if (to < pos) { input.close() @@ -534,6 +549,7 @@ class ZModem( } } + /** [buf] filled from the file as far as it goes: how much was read */ fun read(buf: ByteArray): Int { var len = 0 while (len < buf.size) { @@ -545,6 +561,7 @@ class ZModem( return len } + /** the file closed */ fun close() = input.close() } @@ -560,6 +577,7 @@ class ZModem( var at = start // (errors counted while no progress is made: a long noisy file still gets there) var lastBack = -1L + /** the stream restarted at [to] (another error, counted while no progress is made) and the line's leftovers purged */ fun back(to: Long) { if (to > lastBack) errors = 0 lastBack = to diff --git a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/fax/EcmTest.kt b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/fax/EcmTest.kt index 1a72a2e..5e96d44 100644 --- a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/fax/EcmTest.kt +++ b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/fax/EcmTest.kt @@ -20,6 +20,7 @@ import kotlin.test.assertTrue */ class EcmTest { + /** ECM's HDLC frames come back as sent (flags and ones stuffed), and a damaged bit costs a frame, not the rest */ @Test fun hdlcThereAndBack() { val r = Random(7) @@ -53,6 +54,7 @@ class EcmTest { private class Result(val sent: FaxProgress?, val received: FaxProgress?, val pages: List, val txError: Throwable?, val rxError: Throwable?) + /** a fax of [pages] from A to B over [line] (ECM on either side as asked): what each side made of it */ private fun call(line: FakeFaxLine, pages: List, txEcm: Boolean = true, rxEcm: Boolean = true): Result { val tx = line.a.c1 val rx = line.b.c1 @@ -86,6 +88,7 @@ class EcmTest { return Result(sent, received, got, txError, rxError) } + /** both sides done without an error, and B got [want] exactly */ private fun assertPages(want: List, r: Result) { assertEquals(null, r.txError) assertEquals(null, r.rxError) @@ -97,6 +100,7 @@ class EcmTest { } } + /** a call in ECM: the noisy page in several blocks, each confirmed, nothing asked again nor a lower rate */ @Test fun aCallInEcm() { val line = FakeFaxLine() @@ -114,6 +118,7 @@ class EcmTest { assertTrue("B>8c" in seen) } + /** frames spoilt in the first block are asked for again once (PPR), at the same rate */ @Test fun theFramesThatDidNotComeAgain() { val line = FakeFaxLine() @@ -129,6 +134,7 @@ class EcmTest { assertEquals(14400, r.sent!!.bps) } + /** a burst spoilt four times brings the rate down a step (CTC), and the page still gets there */ @Test fun aLowerRateAfterFourTries() { val line = FakeFaxLine() @@ -146,6 +152,7 @@ class EcmTest { assertEquals(12000, r.sent!!.bps) } + /** a block that never gets through is given up (EOR), and the call goes on to the next page whole */ @Test fun aBlockGivenUp() { val line = FakeFaxLine() @@ -166,6 +173,7 @@ class EcmTest { assertContentEquals(pages[1].bits, r.pages.last().bits) } + /** a receiver without ECM gets the page without it */ @Test fun withoutEcmWhenTheReceiverHasNone() { val line = FakeFaxLine() diff --git a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/fax/FakeClass1.kt b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/fax/FakeClass1.kt index bf87c9d..817b1be 100644 --- a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/fax/FakeClass1.kt +++ b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/fax/FakeClass1.kt @@ -33,6 +33,7 @@ class FakeFaxLine { val seen = ArrayList() private val lock = SynchronizedObject() + /** the FCFs seen so far, a copy */ fun seen(): List = synchronized(lock) { seen.toList() } inner class Modem(val name: String) { @@ -51,15 +52,19 @@ class FakeFaxLine { /** what the modem says, to here instead of [io] (a FaxJob's feed) */ @Volatile var tap: ((ByteArray) -> Unit)? = null + /** what the modem says, to [tap] if set, else to its DTE */ private fun toHost(b: ByteArray) { val t = tap if (t != null) t(b) else io.feed(b) } + /** a transmission from the other modem, kept for this one's receiver */ fun deliver(t: Tx) = synchronized(lock) { inbox.add(t) } + /** whether the DTE has sent something not yet read */ private fun dteWaiting() = at < cur.size || fromDte.isNotEmpty() + /** the DTE's next octet (waited for); an error once stopped */ private fun byte(): Int { while (at >= cur.size) { if (stopped) throw IllegalStateException("stopped") @@ -69,6 +74,7 @@ class FakeFaxLine { return cur[at++].toInt() and 0xff } + /** [s] said to the DTE as a result line */ private fun say(s: String) = toHost("\r\n$s\r\n".encodeToByteArray()) /** shielded data from the DTE, to */ @@ -84,6 +90,7 @@ class FakeFaxLine { } } + /** [d] to the DTE shielded, after */ private fun toDte(d: ByteArray) { val o = Bytes() for (b in d) { o.write(b.toInt()); if (b.toInt() and 0xff == Class1.DLE) o.write(Class1.DLE) } @@ -105,6 +112,7 @@ class FakeFaxLine { } } + /** the transmission come in first, taken */ private fun take() = synchronized(lock) { inbox.removeAt(0) } /** +FTH=3 from its CONNECT: frames until the final one (or an empty one) */ @@ -149,6 +157,7 @@ class FakeFaxLine { say("NO CARRIER") } + /** an AT command from the DTE carried out: answered, and what it sends or receives done */ private fun command(cmd: String) { val c = cmd.uppercase().removePrefix("AT") when { @@ -172,6 +181,7 @@ class FakeFaxLine { } } + /** the modem's thread: the DTE's command lines read and carried out until it stops */ fun start() = background("fake modem $name") { val line = StringBuilder() try { @@ -199,6 +209,7 @@ class FakeFaxLine { b.start() } + /** both modems stopped */ fun stop() { a.stopped = true b.stopped = true diff --git a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/fax/T4Test.kt b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/fax/T4Test.kt index 25ad4bb..f58f65c 100644 --- a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/fax/T4Test.kt +++ b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/fax/T4Test.kt @@ -12,8 +12,10 @@ import kotlin.random.Random /** T.4's MH coding both ways; T.30's DIS/DCS bits and identities. */ class T4Test { + /** the test page, standard or fine */ private fun testPage(fine: Boolean, rows: Int = 400, seed: Int = 1) = FaxTestPage.of(fine, rows, seed) + /** a page in MH comes back as it was, standard and fine */ @Test fun aPageThereAndBack() { for (fine in listOf(false, true)) { @@ -26,6 +28,7 @@ class T4Test { } } + /** a minimum scan time pads each row with fill, and the rows still decode */ @Test fun theMinimumScanTimeAsFill() { val page = FaxPage(FaxPage.WIDTH, 10, false) @@ -37,6 +40,7 @@ class T4Test { assertEquals(10, T4.decode(filled, fine = false).page.rows) } + /** a damaged byte costs a row or two, and the page keeps its height */ @Test fun aDamagedRowIsTheOneBeforeItAgain() { val page = testPage(false, rows = 120) @@ -48,6 +52,7 @@ class T4Test { assertEquals(page.rows, back.page.rows) } + /** random data decodes without looping or reading past its end */ @Test fun theCodesArePrefixFree() { // (decoding random data never loops nor reads past the end) @@ -55,6 +60,7 @@ class T4Test { T4.decode(junk, fine = false) } + /** DIS and DCS carry the rates and scan times asked, and identities go and come back */ @Test fun disAndDcs() { val dis = T30.dis(T30.RATES) diff --git a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/jobs/JobsTest.kt b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/jobs/JobsTest.kt index e38accc..fe54419 100644 --- a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/jobs/JobsTest.kt +++ b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/jobs/JobsTest.kt @@ -39,16 +39,20 @@ import kotlin.test.assertTrue class JobsTest { private class Memory : Incoming { val files = LinkedHashMap() + /** a new file [name] in memory: its stream and that name */ override fun create(name: String, size: Long): Pair = Bytes().let { b -> files[name] = b; b to name } + /** file [name] forgotten */ override fun abandon(name: String) { files.remove(name) } } private class Log : LogOut { val lock = SynchronizedObject() val lines = ArrayList() + /** [line] kept, in order */ override fun log(line: String) { synchronized(lock) { lines.add(line) } } } + /** waits up to [ms] for [cond], else fails for want of [what] */ private fun waitFor(what: String, ms: Long = 30_000, cond: () -> Boolean) { val end = monotonicMs() + ms while (!cond()) { @@ -57,6 +61,7 @@ class JobsTest { } } + /** a fax sent by one FaxJob and received by another, ECM, as a PDF, with the remote's identity and changes reported */ @Test fun aFaxBothWays() { val line = FakeFaxLine() @@ -90,6 +95,7 @@ class JobsTest { assertTrue(changes > 3) } + /** a modem that answers ERROR to every fax command: that's the result, and the modem is put back to data */ @Test fun noFaxModeAnswered() { // a modem that answers ERROR to everything: why, and the modem back to data @@ -106,9 +112,11 @@ class JobsTest { assertTrue("AT+FCLASS=0\r" in said, "$said") } + /** [data] as a file [name] to send */ private fun outgoing(name: String, data: ByteArray) = Outgoing(name, data.size.toLong(), 0) { object : Source { var at = 0 + /** the next of [data], into [b]: how much, -1 at its end */ override fun read(b: ByteArray, off: Int, len: Int): Int { if (at >= data.size) return -1 val n = minOf(len, data.size - at) @@ -119,6 +127,7 @@ class JobsTest { } } + /** a ZMODEM file from one TransferJob to another arrives whole, and a ZMODEM start is detected in the stream */ @Test fun aTransferBetweenTwoJobs() { val data = Random(7).nextBytes(40_000) @@ -149,14 +158,19 @@ class JobsTest { val lock = SynchronizedObject() val serverPackets = ByteQueue() + /** an address of four octets */ private fun a(vararg b: Int): Inet4 = inet4(ByteArray(4) { b[it].toByte() }) val server = Ppp({ b -> job.feed(Latin1.string(b)) }, events = object : Ppp.Events { + /** (the server's link up: nothing to do) */ override fun up(config: Ppp.IpConfig) {} + /** a packet from the client, kept for the test */ override fun ip(packet: ByteArray) = serverPackets.put(packet) + /** the link gone down: offline */ override fun down(reason: String) { online = false } }, retryMs = 300, server = Ppp.Server(a(10, 64, 64, 1), a(10, 64, 64, 2), a(10, 64, 64, 1))) + /** the ISP's thread: commands answered, ATD connected and PPP started, then the line to PPP's server */ fun start() = background("isp") { val cmd = StringBuilder() while (!stopped) { @@ -180,6 +194,7 @@ class JobsTest { } } + /** what the ISP has heard so far */ fun said() = synchronized(lock) { said.toString() } } @@ -188,11 +203,15 @@ class JobsTest { @Volatile var dns = emptyList() @Volatile var closed = false val packets = ByteQueue() + /** a packet from the link, kept for the test */ override fun packet(p: ByteArray) = packets.put(p) + /** the link's address and DNS noted: up */ override fun up(address: String, dns: List, mtu: Int): Boolean { this.address = address; this.dns = dns; return true } + /** the tunnel noted closed */ override fun close() { closed = true } } + /** dial-up through the fake ISP: the link's address and DNS to the tunnel, a packet each way, counts, and the hang-up with +++ and ATH */ @Test fun dialUpInternet() { val isp = FakeIsp() @@ -228,6 +247,7 @@ class JobsTest { } } + /** a BUSY to the dial ends the call as busy, and the tunnel is closed */ @Test fun dialUpBusy() { lateinit var job: DialUpJob @@ -242,6 +262,7 @@ class JobsTest { assertTrue(tunnel.closed) } + /** grey images as fax pages: thresholded, white to the fax's width, dithered about half black, and A4's rows */ @Test fun greyAsFaxPages() { // a 4 by 2 image: black, white, dark grey, light grey diff --git a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/peer/PeerLoopbackTest.kt b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/peer/PeerLoopbackTest.kt index adb008c..214b39c 100644 --- a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/peer/PeerLoopbackTest.kt +++ b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/peer/PeerLoopbackTest.kt @@ -34,6 +34,7 @@ class PeerLoopbackTest { /** a pipe's end: reads [inw], writes [outw] */ private class End(private val inw: Way, private val outw: Way, override val name: String) : Duplex { override val input = object : Source { + /** the next of what came the other way, into [b] (waited for): how much, -1 once closed */ override fun read(b: ByteArray, off: Int, len: Int): Int { while (inw.at >= inw.cur.size) { if (inw.closed) return -1 @@ -47,17 +48,20 @@ class PeerLoopbackTest { } } override val output = object : Sink { + /** [b] sent the other way; an error once either way is closed */ override fun write(b: ByteArray, off: Int, len: Int) { if (outw.closed || inw.closed) throw com.neodesktop.dmodem.io.IOException("closed") outw.q.put(b.copyOfRange(off, off + len)) } } + /** both ways closed */ override fun close() { inw.closed = true outw.closed = true } } + /** a pipe between [a] and [b]: each one's end */ private fun pipe(a: String, b: String): Pair { val ab = Way() val ba = Way() @@ -67,15 +71,19 @@ class PeerLoopbackTest { /** phones by name: connect() to one listening */ private class Exchange { val listeners = HashMap Unit>() + /** the transport for phone [me]: listening by its name, connecting to another's */ fun transport(me: String) = object : PeerTransport { override val label = "memory" + /** [accept] noted as this phone's, for calls to it */ override fun listen(accept: (Duplex) -> Unit) { listeners[me] = accept } + /** a call to the phone listening at [address]: a pipe, its far end handed to that phone */ override fun connect(address: String): Duplex { val accept = listeners[address] ?: throw com.neodesktop.dmodem.io.IOException("nobody at $address") val (mine, theirs) = (object {}).let { pipeOf(me, address) } background("accept") { accept(theirs) } return mine } + /** this phone no longer listening */ override fun close() { listeners.remove(me) } } lateinit var pipeOf: (String, String) -> Pair @@ -92,6 +100,7 @@ class PeerLoopbackTest { init { line.start(listen) } + /** what the phone was told so far, a copy */ fun events() = synchronized(lock) { events.toList() } /** the modem off hook: its side of the line, answering samples with ours */ @@ -116,6 +125,7 @@ class PeerLoopbackTest { } } + /** waits up to [ms] for [cond], else fails for want of [what] */ private fun waitFor(what: String, ms: Long = 15_000, cond: () -> Boolean) { val end = monotonicMs() + ms while (!cond()) { @@ -124,6 +134,7 @@ class PeerLoopbackTest { } } + /** a call rung and answered, each modem hearing the other's samples; a third caller busy; the hang-up ending the far side */ @Test fun aCallRungAnsweredHeardAndHungUp() { val ex = Exchange().apply { pipeOf = { a, b -> pipe(a, b) } } @@ -163,6 +174,7 @@ class PeerLoopbackTest { } } + /** a wrong PIN or none is turned down without ringing; the right one rings and is answered */ @Test fun aPinToCall() { val ex = Exchange().apply { pipeOf = { a, b -> pipe(a, b) } } @@ -192,6 +204,7 @@ class PeerLoopbackTest { } } + /** the PIN proof is md5 of the nonce and PIN, and differs with either */ @Test fun theProof() { // (the PIN never on the line: md5("DMODEM/1:" nonce ":" PIN)) diff --git a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/ppp/PppLoopbackTest.kt b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/ppp/PppLoopbackTest.kt index d6d3bd4..b741dbd 100644 --- a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/ppp/PppLoopbackTest.kt +++ b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/ppp/PppLoopbackTest.kt @@ -29,13 +29,17 @@ class PppLoopbackTest { @Volatile var config: Ppp.IpConfig? = null @Volatile var down: String? = null val packets = ByteQueue() + /** the link's configuration, noted */ override fun up(config: Ppp.IpConfig) { this.config = config } + /** an IP packet from the link, kept for the test */ override fun ip(packet: ByteArray) = packets.put(packet) + /** why the link went down, noted */ override fun down(reason: String) { down = reason } } private class Flag { @Volatile var on = false } + /** waits up to [ms] for [cond], else fails for want of [what] */ private fun waitFor(what: String, ms: Long = 10_000, cond: () -> Boolean) { val end = monotonicMs() + ms while (!cond()) { @@ -44,8 +48,10 @@ class PppLoopbackTest { } } + /** an address of four octets */ private fun a(vararg b: Int): Inet4 = inet4(ByteArray(4) { b[it].toByte() }) + /** a client and its server: the link up with the server's address and DNS, a UDP packet each way, and the client's hang-up downing both */ @Test fun aClientAndItsServer() = runBlocking { val toServer = ByteQueue() @@ -88,8 +94,10 @@ class PppLoopbackTest { } } + /** MD5 gives RFC 1321's digests, over more than one block too */ @Test fun md5() { + /** [b] in lower-case hex */ fun hex(b: ByteArray) = b.joinToString("") { (it.toInt() and 0xff).toString(16).padStart(2, '0') } assertEquals("d41d8cd98f00b204e9800998ecf8427e", hex(Md5.digest(ByteArray(0)))) assertEquals("900150983cd24fb0d6963f7d28e17f72", hex(Md5.digest("abc".encodeToByteArray()))) diff --git a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/terminal/TerminalBridgeTest.kt b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/terminal/TerminalBridgeTest.kt index da04fa6..6325b92 100644 --- a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/terminal/TerminalBridgeTest.kt +++ b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/terminal/TerminalBridgeTest.kt @@ -8,6 +8,7 @@ import kotlin.test.assertTrue /** The terminal as Swift has it: octets as Latin-1 strings each way, rows as runs, keys, replies. */ class TerminalBridgeTest { + /** octets in show on the screen as runs with the cursor after them, a position report's answer is taken once, and the title is set */ @Test fun octetsInScreenOutRepliesBack() { val t = TerminalBridge(20, 4) @@ -26,6 +27,7 @@ class TerminalBridgeTest { assertEquals("BBS", t.title) } + /** typed text and keys as the octets to send: CR for a newline, control characters, UTF-8, and application cursor keys when asked */ @Test fun typedAndKeys() { val t = TerminalBridge(20, 4) @@ -41,6 +43,7 @@ class TerminalBridgeTest { assertEquals("\u001bOA", t.key("UP")) } + /** CP437 shows 0xdb as a full block, and typing one sends 0xdb */ @Test fun cp437ForTheBbs() { val t = TerminalBridge(10, 2) diff --git a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/terminal/TerminalEmulatorTest.kt b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/terminal/TerminalEmulatorTest.kt index 04af930..87124a8 100644 --- a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/terminal/TerminalEmulatorTest.kt +++ b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/terminal/TerminalEmulatorTest.kt @@ -11,12 +11,16 @@ import kotlin.test.Test class TerminalEmulatorTest { private val replies = StringBuilder() + /** a terminal of this size whose replies go to [replies] */ private fun term(cols: Int = 10, rows: Int = 4, history: Int = 100) = TerminalEmulator(cols, rows, history) { b -> b.forEach { replies.append((it.toInt() and 0xff).toChar()) } } + /** row [r]'s text */ private fun TerminalEmulator.row(r: Int) = line(r).text() + /** [s] fed in as Latin-1 octets */ private fun TerminalEmulator.send(s: String) = append(s.latin1()) + /** text wraps at the width, and what scrolls off the top goes into the history, still joined to its next line */ @Test fun textWrapsAndScrollsIntoTheHistory() { val t = term(5, 2) @@ -30,6 +34,7 @@ class TerminalEmulatorTest { assertEquals("hello worl", t.text(-1, 0, 0, 4)) } + /** a character in the last column leaves the cursor there until the next one wraps */ @Test fun theLastColumnWaitsBeforeWrapping() { val t = term(5, 3) @@ -41,6 +46,7 @@ class TerminalEmulatorTest { assertEquals("", t.row(1)) } + /** cursor positioning, erase to the end of the line, delete, insert and erase characters, and clearing the screen */ @Test fun cursorMovesAndErases() { val t = term(10, 4) @@ -59,6 +65,7 @@ class TerminalEmulatorTest { assertEquals(0, t.cursorY) } + /** SGR's colours (16, 256, true colour both ways of writing it, bright) and attributes set and reset */ @Test fun sgrColoursAndAttributes() { val t = term() @@ -79,6 +86,7 @@ class TerminalEmulatorTest { assertEquals(10, Style.bg(l.styles[6])) } + /** a line feed at a scrolling region's bottom scrolls only the region, nothing into the history; lines inserted and deleted in it */ @Test fun scrollingRegionKeepsTheRestAndTheHistory() { val t = term(5, 4) @@ -97,6 +105,7 @@ class TerminalEmulatorTest { assertEquals("c", t.row(1)) } + /** the alternate screen starts blank and leaving it brings the main screen and its cursor back */ @Test fun theAlternateScreenComesAndGoes() { val t = term(5, 3) @@ -111,6 +120,7 @@ class TerminalEmulatorTest { assertEquals(4, t.cursorX) } + /** position, device attribute and status reports answered, and ENQ with the answerback */ @Test fun answersForTheRemote() { val t = term(10, 5) @@ -122,6 +132,7 @@ class TerminalEmulatorTest { assertEquals("DMODEM", replies.toString()) } + /** ANSI.SYS's save and restore of the cursor */ @Test fun ansiSysSaveAndRestore() { val t = term() @@ -129,6 +140,7 @@ class TerminalEmulatorTest { assertEquals("abc", t.row(0)) } + /** DEC line drawing in G0, and in G1 by shift out and in */ @Test fun decLineDrawing() { val t = term() @@ -138,6 +150,7 @@ class TerminalEmulatorTest { assertEquals("─q", t.row(1)) } + /** CP437's octets as their characters, and UTF-8 split across reads put together */ @Test fun cp437AndUtf8() { val t = term(20, 2) @@ -153,17 +166,20 @@ class TerminalEmulatorTest { assertEquals("€é", t.row(1)) } + /** every CP437 octet decodes and encodes back to itself */ @Test fun cp437TableIsWhole() { for (b in 0x80..0xff) assertEquals(b, Cp437.encode(Cp437.decode(b))) assertEquals("╔".let { byteArrayOf(0xc9.toByte()).toList() }, TermCharset.CP437.encode("╔").toList()) } + /** OSC sets the title, and a DCS string is skipped */ @Test fun oscSetsTheTitleAndControlStringsAreSkipped() { val t = term() var title: String? = null t.listener = object : TerminalEmulator.Listener { + /** the title noted */ override fun onTitle(title2: String) { title = title2 } } t.send("\u001b]0;BBS Main\u0007\u001bPq#0;1;2\u001b\\ok") @@ -171,6 +187,7 @@ class TerminalEmulatorTest { assertEquals("ok", t.row(0)) } + /** resizing keeps the cursor's line on screen, rows going into and coming back from the history, and narrower wraps */ @Test fun resizeKeepsTheCursorsLine() { val t = term(10, 4) @@ -191,6 +208,7 @@ class TerminalEmulatorTest { assertEquals("9", t.row(3)) } + /** tab stops, backspace, and back tab */ @Test fun tabsAndBackspace() { val t = term(20, 2) @@ -199,6 +217,7 @@ class TerminalEmulatorTest { assertEquals("a d", t.row(0)) } + /** REP repeats the last character, and insert mode pushes the line right */ @Test fun repeatAndInsertMode() { val t = term() @@ -208,6 +227,7 @@ class TerminalEmulatorTest { assertEquals("Yxxxx", t.row(0)) } + /** keys and control/alt characters as the octets the remote expects, in the cursor, backspace and enter modes */ @Test fun keys() { val k = KeyEncoder() @@ -230,6 +250,7 @@ class TerminalEmulatorTest { assertEquals("\u001b\u0018", k.char('x'.code, alt = true, ctrl = true)) } + /** links found at a column and in a line, with trailing punctuation left off and www. given http:// */ @Test fun links() { val s = "see https://example.com/a_(b). or www.bbs.org, ok" diff --git a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/terminal/TerminalRunsTest.kt b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/terminal/TerminalRunsTest.kt index 64e3d19..594e728 100644 --- a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/terminal/TerminalRunsTest.kt +++ b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/terminal/TerminalRunsTest.kt @@ -10,8 +10,10 @@ import kotlin.test.assertTrue /** A screen's rows as styled runs (what the iOS app draws): the text, its cells, its colours resolved. */ class TerminalRunsTest { private val vga = TermTheme.VGA + /** [rgb] opaque */ private fun argb(rgb: Int) = 0xff000000.toInt() or rgb + /** a row's runs split where the style changes: colours, bold as bright (or heavy), inverse swapping the defaults, all cells counted */ @Test fun plainColouredBoldInverse() { val t = TerminalEmulator(20, 3) @@ -33,6 +35,7 @@ class TerminalRunsTest { assertEquals(argb(0xaa0000), heavy[1].fg) } + /** a wide character is one run's text over two cells, true colour resolved, and an unwritten row is spaces in the theme's colours */ @Test fun wideCharactersAndTrueColour() { val t = TerminalEmulator(10, 2) @@ -48,6 +51,7 @@ class TerminalRunsTest { assertEquals(vga.bgArgb, blank.bg) } + /** a colour the remote sets (OSC 4) is the one runs use */ @Test fun theRemotesPalette() { val t = TerminalEmulator(10, 1) diff --git a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/tones/CountryTonesTest.kt b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/tones/CountryTonesTest.kt index a86e517..d0060cb 100644 --- a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/tones/CountryTonesTest.kt +++ b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/tones/CountryTonesTest.kt @@ -30,6 +30,7 @@ class CountryTonesTest { return 2 * sqrt(s1 * s1 + s2 * s2 - k * s1 * s2) / n } + /** the table: every country once, found by any of its names, the USA's and others' tones as the ITU has them, all audible and cadenced */ @Test fun theTable() { assertEquals(192, CountryTones.all.size) @@ -57,6 +58,7 @@ class CountryTonesTest { } } + /** a dial tone's sound: both its frequencies at half the level, nothing else, faded in and out */ @Test fun aDialToneSound() { val us = CountryTones.find("USA")!! @@ -70,6 +72,7 @@ class CountryTonesTest { assertTrue(abs(x[0].toInt()) < 2000 && abs(x.last().toInt()) < 2000) } + /** a busy tone's cadence: on and off in turn, ramped not clicking, and started from a point in it */ @Test fun aBusyTonesCadence() { val us = CountryTones.find("USA")!! @@ -86,6 +89,7 @@ class CountryTonesTest { assertTrue(level(later, 480.0) < 0.001) } + /** Japan's ringing tone: 400 Hz swung at 15 Hz (sidebands), on and off in its cadence */ @Test fun aModulatedTone() { // Japan's ringing tone: 400 Hz, its level swung at 15 Hz (sidebands at 385 and 415) @@ -96,6 +100,7 @@ class CountryTonesTest { assertTrue(jp.onAt(0.5) && !jp.onAt(1.5) && jp.onAt(3.2)) } + /** tones played in 50 ms pieces are the same samples as in one, with no jump bigger than the tone's own slope */ @Test fun inPiecesAsInOne() { // a player's 50 ms chunks (the last one fading out) are the same sound as one long one: no clicks between them diff --git a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/transfer/HexRecordsTest.kt b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/transfer/HexRecordsTest.kt index 4e6e512..f8f8dd0 100644 --- a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/transfer/HexRecordsTest.kt +++ b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/transfer/HexRecordsTest.kt @@ -24,9 +24,11 @@ import kotlin.test.assertTrue * ([HexTransfer], through [Transfer]). */ class HexRecordsTest { + /** [lines] given to a decoder of [format]: it, after them */ private fun decode(format: HexRecords.Format, lines: List): HexRecords.Decoder = HexRecords.Decoder(format).apply { for (l in lines) line(l) } + /** Intel HEX encodes the spec's example exactly, and decodes back to its bytes at its address */ @Test fun intelHexAsItsSpecHasIt() { // (Intel's example: 3 bytes at 0030, then the end) @@ -38,6 +40,7 @@ class HexRecordsTest { assertContentEquals(byteArrayOf(0x02, 0x33, 0x7a), d.image()) } + /** the well-known S-record example decodes to its header, address and bytes */ @Test fun sRecordsAsTheirExampleHasThem() { // (the well-known S1 example: 16 bytes at 7AF0) @@ -48,6 +51,7 @@ class HexRecordsTest { assertContentEquals(byteArrayOf(0x0a, 0x0a, 0x0d) + ByteArray(13), d.image()) } + /** images of either format there and back at any base, across 64 KB, recognised as their own format only; S1, S2 or S3 by the end address */ @Test fun imagesThereAndBack() { val data = Random(7).nextBytes(70_000) @@ -68,6 +72,7 @@ class HexRecordsTest { assertTrue(HexRecords.encode(ByteArray(16), HexRecords.Format.SREC, 0x1000000)[1].startsWith("S3")) } + /** gaps between records are erased EPROM (0xff), and lines that aren't records are passed over */ @Test fun gapsAreErasedEpromAndOtherLinesPassedOver() { val d = decode( @@ -77,6 +82,7 @@ class HexRecordsTest { assertContentEquals(byteArrayOf(0x41, -1, -1, -1, 0x42), d.image()) } + /** a wrong checksum or length is an error */ @Test fun aWrongChecksumIsAnError() { assertFailsWith { decode(HexRecords.Format.INTEL, listOf(":0300300002337A1F")) } @@ -87,12 +93,15 @@ class HexRecordsTest { /** files in memory */ private class Memory : Incoming { val files = LinkedHashMap() + /** a new file [name] in memory: its stream and that name */ override fun create(name: String, size: Long): Pair = Bytes().let { b -> files[name] = b; b to name } } + /** [data] as a file [name] to send */ private fun outgoing(name: String, data: ByteArray) = Outgoing(name, data.size.toLong(), 0) { object : Source { var at = 0 + /** the next of [data], into [b]: how much, -1 at its end */ override fun read(b: ByteArray, off: Int, len: Int): Int { if (at >= data.size) return -1 val n = minOf(len, data.size - at) @@ -123,6 +132,7 @@ class HexRecordsTest { mem to text.toString() } + /** Intel HEX and S-records sent on a line arrive as the file, the line's text ending with the end record */ @Test fun sentAndReceivedOnALine() { val data = Random(11).nextBytes(5000) @@ -134,6 +144,7 @@ class HexRecordsTest { } } + /** a file that is records already is sent as it is, only its line ends made CR LF */ @Test fun aFileOfRecordsAlreadyIsSentAsItIs() { val records = ":0300300002337A1E\n:00000001FF\n" diff --git a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/transfer/TextTransferTest.kt b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/transfer/TextTransferTest.kt index d4da659..c84ae51 100644 --- a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/transfer/TextTransferTest.kt +++ b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/transfer/TextTransferTest.kt @@ -21,12 +21,15 @@ import kotlin.test.assertTrue class TextTransferTest { private class Memory : Incoming { val files = LinkedHashMap() + /** a new file [name] in memory: its stream and that name */ override fun create(name: String, size: Long): Pair = Bytes().let { b -> files[name] = b; b to name } } + /** [data] as a file [name] to send */ private fun outgoing(name: String, data: ByteArray) = Outgoing(name, data.size.toLong(), 0) { object : Source { var at = 0 + /** the next of [data], into [b]: how much, -1 at its end */ override fun read(b: ByteArray, off: Int, len: Int): Int { if (at >= data.size) return -1 val n = minOf(len, data.size - at) @@ -40,6 +43,7 @@ class TextTransferTest { private val text = ("line one\r\nline two\nline three\rtabbed\there\r\n" + "é ü — 東京\n").encodeToByteArray() + ByteArray(3000) { (it % 256).toByte() } + /** a file's bytes go on the line unchanged and are received unchanged until the line goes quiet */ @Test fun sentVerbatimAndReceivedUntilQuiet() = runBlocking { // the two ends of a line @@ -56,6 +60,7 @@ class TextTransferTest { assertContentEquals(text, mem.files["capture.txt"]!!.toByteArray()) } + /** through [Transfer] the text is sent as it is, and a cancel sends nothing */ @Test fun throughTransferWithNothingAddedOrSentOnCancel() = runBlocking { val wire = Bytes() diff --git a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/transfer/TransferLoopbackTest.kt b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/transfer/TransferLoopbackTest.kt index aa87aac..4e15588 100644 --- a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/transfer/TransferLoopbackTest.kt +++ b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/transfer/TransferLoopbackTest.kt @@ -23,15 +23,20 @@ class TransferLoopbackTest { private class Memory : Incoming { val files = LinkedHashMap() val times = HashMap() + /** a new file [name] in memory: its stream and that name */ override fun create(name: String, size: Long): Pair = Bytes().let { b -> files[name] = b; b to name } + /** file [name]'s time noted */ override fun done(name: String, mtime: Long) { times[name] = mtime } + /** file [name] forgotten */ override fun abandon(name: String) { files.remove(name) } } + /** [data] as a file [name] of time [mtime] to send */ private fun outgoing(name: String, data: ByteArray, mtime: Long = 1_700_000_000) = Outgoing(name, data.size.toLong(), mtime) { object : Source { var at = 0 + /** the next of [data], into [b]: how much, -1 at its end */ override fun read(b: ByteArray, off: Int, len: Int): Int { if (at >= data.size) return -1 val n = minOf(len, data.size - at) @@ -62,6 +67,7 @@ class TransferLoopbackTest { private val data = Random(7).nextBytes(40_000) private val small = "hello, modem\n".encodeToByteArray() + /** XMODEM-1K: what came starts with the file (the last block padded) */ @Test fun xmodem() { val m = Memory() @@ -70,6 +76,7 @@ class TransferLoopbackTest { assertContentEquals(data, m.files.getValue("x.bin").toByteArray().copyOf(data.size)) } + /** YMODEM: a batch of two, each file whole, with its time */ @Test fun ymodem() { val m = Memory() @@ -80,6 +87,7 @@ class TransferLoopbackTest { assertEquals(1_700_000_000, m.times["a.bin"]) } + /** ZMODEM: a batch of two, each file whole */ @Test fun zmodem() { val m = Memory() @@ -89,6 +97,7 @@ class TransferLoopbackTest { assertContentEquals(small, m.files.getValue("small.txt").toByteArray()) } + /** Kermit: a batch of two, each file whole, with its time there and back */ @Test fun kermit() { val m = Memory() @@ -99,6 +108,7 @@ class TransferLoopbackTest { assertEquals(1_700_000_000, m.times["k.bin"]) } + /** Kermit's dates: days to the calendar and back */ @Test fun kermitsCalendar() { assertEquals(Triple(1970, 1, 1), Kermit.civil(0)) diff --git a/shared/src/jvmMain/kotlin/com/neodesktop/dmodem/io/Io.jvm.kt b/shared/src/jvmMain/kotlin/com/neodesktop/dmodem/io/Io.jvm.kt index 188d4f1..637820f 100644 --- a/shared/src/jvmMain/kotlin/com/neodesktop/dmodem/io/Io.jvm.kt +++ b/shared/src/jvmMain/kotlin/com/neodesktop/dmodem/io/Io.jvm.kt @@ -8,30 +8,42 @@ import java.util.TimeZone actual typealias IOException = java.io.IOException +/** the default time zone's offset from UTC at [epochSec], in seconds */ actual fun localOffsetSeconds(epochSec: Long): Int = TimeZone.getDefault().getOffset(epochSec * 1000) / 1000 /** a JVM stream as a [Source] */ fun InputStream.asSource(): Source = object : Source { + /** the stream's read */ override fun read(b: ByteArray, off: Int, len: Int): Int = this@asSource.read(b, off, len) + /** the stream closed */ override fun close() = this@asSource.close() } /** a JVM stream as a [Sink] */ fun OutputStream.asSink(): Sink = object : Sink { + /** [len] bytes of [b] from [off] to the stream */ override fun write(b: ByteArray, off: Int, len: Int) = this@asSink.write(b, off, len) + /** a byte to the stream */ override fun write(b: Int) = this@asSink.write(b) + /** the stream flushed */ override fun flush() = this@asSink.flush() + /** the stream closed */ override fun close() = this@asSink.close() } /** a [Sink] as a JVM stream */ fun Sink.asOutputStream(): OutputStream = object : OutputStream() { + /** a byte to the sink */ override fun write(b: Int) = this@asOutputStream.write(b) + /** [len] bytes of [b] from [off] to the sink */ override fun write(b: ByteArray, off: Int, len: Int) = this@asOutputStream.write(b, off, len) + /** the sink flushed */ override fun flush() = this@asOutputStream.flush() + /** the sink closed */ override fun close() = this@asOutputStream.close() } private val secure = java.security.SecureRandom() +/** [n] bytes from SecureRandom */ actual fun secureRandomBytes(n: Int): ByteArray = ByteArray(n).also { secure.nextBytes(it) } diff --git a/shared/src/jvmMain/kotlin/com/neodesktop/dmodem/io/Net.jvm.kt b/shared/src/jvmMain/kotlin/com/neodesktop/dmodem/io/Net.jvm.kt index fd25cd7..0220f4d 100644 --- a/shared/src/jvmMain/kotlin/com/neodesktop/dmodem/io/Net.jvm.kt +++ b/shared/src/jvmMain/kotlin/com/neodesktop/dmodem/io/Net.jvm.kt @@ -6,6 +6,7 @@ import java.net.InetAddress actual typealias Inet4 = java.net.Inet4Address +/** the address of these four octets */ actual fun inet4(octets: ByteArray): Inet4 = InetAddress.getByAddress(octets) as java.net.Inet4Address actual val Inet4.octets: ByteArray get() = address diff --git a/shared/src/jvmMain/kotlin/com/neodesktop/dmodem/transfer/FolderIncoming.kt b/shared/src/jvmMain/kotlin/com/neodesktop/dmodem/transfer/FolderIncoming.kt index 1073721..94053dd 100644 --- a/shared/src/jvmMain/kotlin/com/neodesktop/dmodem/transfer/FolderIncoming.kt +++ b/shared/src/jvmMain/kotlin/com/neodesktop/dmodem/transfer/FolderIncoming.kt @@ -14,18 +14,21 @@ fun Outgoing.Companion.of(f: File) = Outgoing(f.name, f.length(), f.lastModified class FolderIncoming(private val dir: File) : Incoming { val received = ArrayList() + /** a new file in [dir] for [name], made safe and unique: its stream and the name it got */ override fun create(name: String, size: Long): Pair { dir.mkdirs() val f = unique(dir, safeName(name)) return f.outputStream().asSink() to f.name } + /** the file finished: its time set (if known) and it added to [received] */ override fun done(name: String, mtime: Long) { val f = File(dir, name) if (mtime > 0) f.setLastModified(mtime * 1000) received.add(f) } + /** the unfinished file deleted */ override fun abandon(name: String) { File(dir, name).delete() } diff --git a/shared/src/jvmTest/kotlin/com/neodesktop/dmodem/terminal/XtermFeaturesTest.kt b/shared/src/jvmTest/kotlin/com/neodesktop/dmodem/terminal/XtermFeaturesTest.kt index 38a4d27..2b915c1 100644 --- a/shared/src/jvmTest/kotlin/com/neodesktop/dmodem/terminal/XtermFeaturesTest.kt +++ b/shared/src/jvmTest/kotlin/com/neodesktop/dmodem/terminal/XtermFeaturesTest.kt @@ -21,15 +21,20 @@ import kotlin.math.abs class XtermFeaturesTest { private val replies = StringBuilder() + /** a terminal of this size whose replies go to [replies] as UTF-8 */ private fun term(cols: Int = 20, rows: Int = 6) = TerminalEmulator(cols, rows, 100) { replies.append(String(it, Charsets.UTF_8)) } + /** [s] fed in as UTF-8 */ private fun TerminalEmulator.send(s: String) = append(s.toByteArray(Charsets.UTF_8)) + /** row [r]'s text */ private fun TerminalEmulator.row(r: Int) = line(r).text() + /** the replies so far, cleared */ private fun takeReplies() = replies.toString().also { replies.setLength(0) } // characters ------------------------------------------------------ + /** wide characters take two cells, wrap whole to the next line, and half of one overwritten blanks the other half */ @Test fun wideCharactersTakeTwoCells() { val t = term(10, 3) @@ -50,6 +55,7 @@ class XtermFeaturesTest { assertEquals(3, t.cursorX) } + /** combining marks and ZWJ sequences join their character's cell, and wcwidth's widths */ @Test fun combiningMarksJoinTheirCharacter() { val t = term(10, 2) @@ -66,6 +72,7 @@ class XtermFeaturesTest { assertEquals(2, Wcwidth.width(0xAC00)) } + /** inserting and deleting characters moves their combining marks with them */ @Test fun insertAndDeleteMoveTheExtras() { val t = term(10, 1) @@ -77,6 +84,7 @@ class XtermFeaturesTest { // the rendition --------------------------------------------------- + /** underline styles, double underline and overline, and the underline's colour not taken for attributes */ @Test fun underlineStylesAndTheUnderlinesColourReadPast() { val t = term() @@ -93,6 +101,7 @@ class XtermFeaturesTest { // reports ----------------------------------------------------------- + /** DA, XTVERSION, XTWINOPS, XTSMGRAPHICS, DECRQM and DECRQSS answered as xterm would */ @Test fun theReportsProgramsAskFor() { val t = term(80, 24) @@ -116,6 +125,7 @@ class XtermFeaturesTest { assertEquals(5, t.cursorStyle) } + /** colours asked about (OSC 4, 10, 11) answered, set, and reset (OSC 104, 110) */ @Test fun coloursAskedAboutAndSet() { val t = term() @@ -135,11 +145,13 @@ class XtermFeaturesTest { assertNull(TerminalEmulator.parseColor("red")) } + /** OSC 52 copies to the clipboard but never says what's on it, and OSC 8's link covers its text */ @Test fun theClipboardAndHyperlinks() { val t = term() val copied = ArrayList() t.listener = object : TerminalEmulator.Listener { + /** the copied text noted */ override fun onClipboard(text: String) { copied.add(text) } } t.send("\u001b]52;c;" + java.util.Base64.getEncoder().encodeToString("héllo".toByteArray()) + "\u0007") @@ -156,6 +168,7 @@ class XtermFeaturesTest { // the mouse --------------------------------------------------------- + /** mouse reports in the X10, normal, SGR and urxvt encodings as asked, motion only when asked, and focus reports */ @Test fun mouseReportsInEachEncoding() { val t = term(300, 50) @@ -192,6 +205,7 @@ class XtermFeaturesTest { // sixel ------------------------------------------------------------ + /** a test image [name] from the app's test resources */ private fun resource(name: String): File = // (the app's test images: from this module, or the project's root) listOf(File("../app/src/test/resources/$name"), File("app/src/test/resources/$name")).first { it.exists() } @@ -230,6 +244,7 @@ class XtermFeaturesTest { assertEquals("the line after it, at its left", " z", t.row(3)) } + /** sixel colours by HLS and RGB, repeats, new lines, and a transparent background or register 0's behind */ @Test fun sixelsColoursRepeatsAndTransparency() { val t = term(20, 4) @@ -252,6 +267,7 @@ class XtermFeaturesTest { assertEquals(0xff000000.toInt(), img2.pixels[3]) } + /** a sixel image scrolls with the text into the history, and text written over a cell takes its tile */ @Test fun imagesScrollWithTheText() { val t = term(10, 3) @@ -271,6 +287,7 @@ class XtermFeaturesTest { assertNotNull(t.line(0).extra(1)?.image) } + /** a sixel cut short by CAN, or an unknown DCS (answered as unknown), leaves the terminal working */ @Test fun aDcsCutShortOrUnknownLeavesTheTerminalWorking() { val t = term(10, 2) diff --git a/shared/src/jvmTest/kotlin/com/neodesktop/dmodem/tones/CountryTonesSourceTest.kt b/shared/src/jvmTest/kotlin/com/neodesktop/dmodem/tones/CountryTonesSourceTest.kt index a7475b8..0a61f49 100644 --- a/shared/src/jvmTest/kotlin/com/neodesktop/dmodem/tones/CountryTonesSourceTest.kt +++ b/shared/src/jvmTest/kotlin/com/neodesktop/dmodem/tones/CountryTonesSourceTest.kt @@ -13,6 +13,7 @@ import kotlin.test.assertEquals * submodule and Python are here). */ class CountryTonesSourceTest { + /** tools/country_tones.py run on D-Modem-RE's tones.cpp gives the committed table (skipped without them or Python) */ @Test fun theTableIsD_ModemREs() { val root = generateSequence(File("").absoluteFile) { it.parentFile }.firstOrNull { File(it, "tools/country_tones.py").exists() } ?: return diff --git a/shared/src/nativeMain/kotlin/com/neodesktop/dmodem/io/Io.native.kt b/shared/src/nativeMain/kotlin/com/neodesktop/dmodem/io/Io.native.kt index 9608bfd..978502d 100644 --- a/shared/src/nativeMain/kotlin/com/neodesktop/dmodem/io/Io.native.kt +++ b/shared/src/nativeMain/kotlin/com/neodesktop/dmodem/io/Io.native.kt @@ -19,6 +19,7 @@ import platform.posix.tm actual open class IOException actual constructor(message: String?) : Exception(message) +/** the local time zone's offset from UTC at [epochSec], in seconds (localtime_r's; 0 if it fails) */ @OptIn(ExperimentalForeignApi::class) actual fun localOffsetSeconds(epochSec: Long): Int = memScoped { val t = alloc() diff --git a/shared/src/nativeMain/kotlin/com/neodesktop/dmodem/io/Net.native.kt b/shared/src/nativeMain/kotlin/com/neodesktop/dmodem/io/Net.native.kt index 19b8a63..68fb06c 100644 --- a/shared/src/nativeMain/kotlin/com/neodesktop/dmodem/io/Net.native.kt +++ b/shared/src/nativeMain/kotlin/com/neodesktop/dmodem/io/Net.native.kt @@ -3,11 +3,15 @@ package com.neodesktop.dmodem.io actual class Inet4(internal val bytes: ByteArray) { + /** the same four octets */ override fun equals(other: Any?) = other is Inet4 && bytes.contentEquals(other.bytes) + /** the octets' hash */ override fun hashCode() = bytes.contentHashCode() + /** "/" and the dotted address, as the JVM's has it */ override fun toString() = "/" + dotted } +/** the address of these four octets (a copy of them) */ actual fun inet4(octets: ByteArray): Inet4 { require(octets.size == 4) { "an IPv4 address is 4 octets" } return Inet4(octets.copyOf()) diff --git a/shared/src/nativeMain/kotlin/com/neodesktop/dmodem/peer/PeerHost.kt b/shared/src/nativeMain/kotlin/com/neodesktop/dmodem/peer/PeerHost.kt index 961475a..82a97a4 100644 --- a/shared/src/nativeMain/kotlin/com/neodesktop/dmodem/peer/PeerHost.kt +++ b/shared/src/nativeMain/kotlin/com/neodesktop/dmodem/peer/PeerHost.kt @@ -41,6 +41,7 @@ class PeerHost( "can't take calls: ${e.message ?: e}" } + /** the line stopped */ fun stop() = line.stop() /** the modem off hook: its line (the engine's socket), dialling [dial] if [caller] */ diff --git a/shared/src/nativeMain/kotlin/com/neodesktop/dmodem/peer/PosixPeer.kt b/shared/src/nativeMain/kotlin/com/neodesktop/dmodem/peer/PosixPeer.kt index 49e37b9..5a50a71 100644 --- a/shared/src/nativeMain/kotlin/com/neodesktop/dmodem/peer/PosixPeer.kt +++ b/shared/src/nativeMain/kotlin/com/neodesktop/dmodem/peer/PosixPeer.kt @@ -79,6 +79,7 @@ class FdDuplex(private val fd: Int, override val name: String = "modem") : Duple } override val input: Source = object : Source { + /** up to [len] bytes received into [b]: how many, -1 at the end (or once closed) */ override fun read(b: ByteArray, off: Int, len: Int): Int { if (len <= 0) return 0 while (true) { @@ -94,6 +95,7 @@ class FdDuplex(private val fd: Int, override val name: String = "modem") : Duple } override val output: Sink = object : Sink { + /** all of [len] bytes of [b] from [off] sent; an error if the connection ended */ override fun write(b: ByteArray, off: Int, len: Int) { var at = off var left = len @@ -107,6 +109,7 @@ class FdDuplex(private val fd: Int, override val name: String = "modem") : Duple } } + /** the socket shut down and closed (once) */ override fun close() { if (!closed.compareAndSet(false, true)) return shutdown(fd, SHUT_RDWR) @@ -139,6 +142,7 @@ class PosixTcpTransport(private val port: Int) : PeerTransport { } } + /** calls taken on [port] in the background until [close], each handed to [accept] */ override fun listen(accept: (Duplex) -> Unit) { val fd = bound(port) ?: throw IOException("can't take calls on port $port (errno $errno)") listenFd.value = fd @@ -162,6 +166,7 @@ class PosixTcpTransport(private val port: Int) : PeerTransport { } } + /** a TCP connection to [address] (host[:port]), trying each of its addresses in turn; an error saying why none answered */ override fun connect(address: String): Duplex { val (host, p) = parse(address, port) memScoped { @@ -192,6 +197,7 @@ class PosixTcpTransport(private val port: Int) : PeerTransport { } } + /** no more calls taken (the listening loop ends and closes its socket) */ override fun close() { running.value = false } @@ -242,6 +248,7 @@ class PosixTcpTransport(private val port: Int) : PeerTransport { err } + /** the numeric host of the socket's other end, "?" if unknown */ private fun peerName(fd: Int): String = memScoped { val sa = alloc() val len = alloc() diff --git a/shared/src/nativeMain/kotlin/com/neodesktop/dmodem/ppp/UdpPacketTunnel.kt b/shared/src/nativeMain/kotlin/com/neodesktop/dmodem/ppp/UdpPacketTunnel.kt index 4df4ee5..d336a10 100644 --- a/shared/src/nativeMain/kotlin/com/neodesktop/dmodem/ppp/UdpPacketTunnel.kt +++ b/shared/src/nativeMain/kotlin/com/neodesktop/dmodem/ppp/UdpPacketTunnel.kt @@ -37,6 +37,7 @@ interface TunnelStarter { /** the tunnel up with [address], [dns] (comma between), its packets to 127.0.0.1:[port]: whether it started */ fun start(address: String, dns: String, mtu: Int, port: Int): Boolean + /** the tunnel stopped */ fun stop() } @@ -76,6 +77,7 @@ class UdpPacketTunnel(private val job: DialUpJob, private val starter: TunnelSta background("tunnel") { receive() } } + /** the extension's datagrams until closed: where it is noted, each IPv4 packet passed on to the link; the socket closed at the end */ private fun receive() { val buf = ByteArray(65536) while (running.value) { @@ -106,6 +108,7 @@ class UdpPacketTunnel(private val job: DialUpJob, private val starter: TunnelSta platform.posix.close(fd) } + /** [p] from the link to the extension, once it has said where it is (else dropped) */ override fun packet(p: ByteArray) { val to = synchronized(lock) { peer } ?: return toTunnel.incrementAndGet() @@ -116,17 +119,21 @@ class UdpPacketTunnel(private val job: DialUpJob, private val starter: TunnelSta } } + /** the extension started with the link's [address], [dns] and [mtu], its packets to our port: whether it did */ override fun up(address: String, dns: List, mtu: Int): Boolean = starter.start(address, dns.joinToString(","), mtu, port) + /** no more packets taken, and the extension stopped (once) */ override fun close() { if (!running.compareAndSet(true, false)) return starter.stop() } + /** [v] in network order (big-endian) */ private fun htonl(v: UInt): UInt = if (bigEndian) v else ((v and 0xffu) shl 24) or ((v and 0xff00u) shl 8) or ((v shr 8) and 0xff00u) or (v shr 24) + /** [v] from network order */ private fun ntohs(v: UShort): UShort = if (bigEndian) v else (((v.toInt() and 0xff) shl 8) or (v.toInt() shr 8 and 0xff)).toUShort() diff --git a/shared/src/nativeMain/kotlin/com/neodesktop/dmodem/transfer/PosixFiles.kt b/shared/src/nativeMain/kotlin/com/neodesktop/dmodem/transfer/PosixFiles.kt index 056a882..d37364e 100644 --- a/shared/src/nativeMain/kotlin/com/neodesktop/dmodem/transfer/PosixFiles.kt +++ b/shared/src/nativeMain/kotlin/com/neodesktop/dmodem/transfer/PosixFiles.kt @@ -55,11 +55,13 @@ object PosixFiles { } } + /** the file at [path] to read; an error when it can't be opened */ fun source(path: String): Source { val f = fopen(path, "rb") ?: throw IOException("can't open $path") return FileSource(f) } + /** the file at [path] to write, made or emptied; an error when it can't be */ fun sink(path: String): Sink { val f = fopen(path, "wb") ?: throw IOException("can't write $path") return FileSink(f) @@ -85,6 +87,7 @@ object PosixFiles { } private class FileSource(private var f: CPointer?) : Source { + /** up to [len] bytes of the file into [b]: how many, -1 at its end or once closed */ override fun read(b: ByteArray, off: Int, len: Int): Int { val file = f ?: return -1 if (len <= 0) return 0 @@ -92,6 +95,7 @@ object PosixFiles { return if (n == 0) -1 else n } + /** the file closed (once) */ override fun close() { f?.let { fclose(it) } f = null @@ -99,6 +103,7 @@ object PosixFiles { } private class FileSink(private var f: CPointer?) : Sink { + /** all of [len] bytes of [b] from [off] to the file; an error when the disk is full or it's closed */ override fun write(b: ByteArray, off: Int, len: Int) { val file = f ?: throw IOException("closed") if (len <= 0) return @@ -106,6 +111,7 @@ object PosixFiles { if (n != len) throw IOException("the disk is full") } + /** the file closed (once); an error if what was written didn't all get there */ override fun close() { val file = f ?: return f = null @@ -120,12 +126,14 @@ class PosixFolderIncoming(private val dir: String) : Incoming { /** the names the files got, those finished */ val received = ArrayList() + /** a new file in [dir] (made if it isn't there) for [name], made safe and unique: its stream and the name it got */ override fun create(name: String, size: Long): Pair { mkdir(dir, 0x1edu.convert()) val actual = PosixFiles.unique(dir, PosixFiles.safeName(name)) return PosixFiles.sink("$dir/$actual") to actual } + /** the file finished: its time set (if known) and its name added to [received] */ override fun done(name: String, mtime: Long) { if (mtime > 0) memScoped { val t = alloc() @@ -136,6 +144,7 @@ class PosixFolderIncoming(private val dir: String) : Incoming { received.add(name) } + /** the unfinished file deleted */ override fun abandon(name: String) { unlink("$dir/$name") } diff --git a/shared/src/nativeTest/kotlin/com/neodesktop/dmodem/jobs/NativeJobsTest.kt b/shared/src/nativeTest/kotlin/com/neodesktop/dmodem/jobs/NativeJobsTest.kt index 8620c9b..4a9b270 100644 --- a/shared/src/nativeTest/kotlin/com/neodesktop/dmodem/jobs/NativeJobsTest.kt +++ b/shared/src/nativeTest/kotlin/com/neodesktop/dmodem/jobs/NativeJobsTest.kt @@ -40,6 +40,7 @@ import kotlin.test.assertTrue */ @OptIn(ExperimentalForeignApi::class) class NativeJobsTest { + /** files received into a folder get safe, unique names, are sent back by path, and an abandoned one is removed */ @Test fun filesInAFolder() { val dir = "/tmp/dmodem-files-${getpid()}" @@ -69,6 +70,7 @@ class NativeJobsTest { assertEquals(null, PosixFiles.outgoing("$dir/none")) } + /** the tunnel's port gets the link's settings, the extension's packet reaches the link, the link's reaches the extension, and closing stops it */ @Test fun packetsOverTheLoopback() { // the link's job (never connected: its packets only counted), the tunnel's "extension" a UDP socket @@ -76,10 +78,12 @@ class NativeJobsTest { var started = "" var stopped = false val t = UdpPacketTunnel(job, object : TunnelStarter { + /** the tunnel's settings noted: started */ override fun start(address: String, dns: String, mtu: Int, port: Int): Boolean { started = "$address $dns $mtu $port" return true } + /** the tunnel noted stopped */ override fun stop() { stopped = true } }) assertTrue(t.port > 0) diff --git a/shared/src/nativeTest/kotlin/com/neodesktop/dmodem/peer/PosixPeerTest.kt b/shared/src/nativeTest/kotlin/com/neodesktop/dmodem/peer/PosixPeerTest.kt index 817fe72..6a6b06d 100644 --- a/shared/src/nativeTest/kotlin/com/neodesktop/dmodem/peer/PosixPeerTest.kt +++ b/shared/src/nativeTest/kotlin/com/neodesktop/dmodem/peer/PosixPeerTest.kt @@ -40,6 +40,7 @@ class PosixPeerTest { assertEquals(null, host.start(listen)) } + /** what the phone was told so far, a copy */ fun events() = synchronized(lock) { events.toList() } /** the modem off hook: a socket pair, our end answering samples with [mark], the other to the line */ @@ -70,6 +71,7 @@ class PosixPeerTest { } } + /** waits up to [ms] for [cond], else fails for want of [what] */ private fun waitFor(what: String, ms: Long = 15_000, cond: () -> Boolean) { val end = monotonicMs() + ms while (!cond()) { @@ -78,6 +80,7 @@ class PosixPeerTest { } } + /** a call over TCP rung, answered and heard both ways, a third caller busy, and the hang-up leaving the far side ready again */ @Test fun aCallOverTcp() { val b = Phone("B", listen = true, mark = 2) @@ -107,6 +110,7 @@ class PosixPeerTest { } } + /** a wrong PIN over TCP is turned away without ringing, the right one rings */ @Test fun aPinOverTcp() { val b = Phone("B", listen = true, mark = 2, pin = "2468") @@ -124,6 +128,7 @@ class PosixPeerTest { } } + /** a call to a port nobody listens on fails with 480, saying it can't reach it */ @Test fun nobodyThere() { // a port nobody listens on: NO ANSWER's FAILED 480, why for the user @@ -137,6 +142,7 @@ class PosixPeerTest { } } + /** host[:port] and IPv6 addresses, bracketed or not, parsed with the default port when none */ @Test fun addresses() { assertEquals("host" to 5070, PosixTcpTransport.parse("host", 5070)) diff --git a/tools/country_tones.py b/tools/country_tones.py index c2568a4..534465e 100644 --- a/tools/country_tones.py +++ b/tools/country_tones.py @@ -27,6 +27,7 @@ ALIAS = re.compile(r'\{\s*"([A-Z0-9_]+)",\s*"([A-Z0-9_]+)"\s*\}') def tone(g, i): + """the Kotlin Tone() of the tone at i in the match g: its frequencies, modulation and cadence (its first n values)""" f1, f2, mod, n, cad = g[i:i + 5] vals = [v.strip().rstrip("f") for v in cad.split(",") if v.strip()][: int(n)] m = float(mod) @@ -35,6 +36,7 @@ def tone(g, i): def main(): + """tones.cpp's countries and aliases as CountryTonesTable.kt, to stdout""" text = open(SRC).read() countries_part, _, aliases_part = text.partition("const Alias ALIASES[]") countries = COUNTRY.findall(countries_part) diff --git a/tools/doc_check.py b/tools/doc_check.py index 4c35c63..40c0fc7 100644 --- a/tools/doc_check.py +++ b/tools/doc_check.py @@ -37,7 +37,8 @@ MODS = (r"(?:public|private|internal|protected|open|override|final|abstract|inli ANNOT = r"@[\w.]+(?:\([^()]*(?:\([^()]*\)[^()]*)*\))?" FUN = re.compile(r"^\s*(?:" + ANNOT + r"\s+)*(?:" + MODS + r"\s+)*(?:fun|func)\s+(?!interface\b)[\w`<]") INIT = re.compile(r"^\s*(?:" + ANNOT + r"\s+)*(?:" + MODS + r"\s+)*(?:init[?!]?\s*[(<]|deinit\b)") -SH_FUN = re.compile(r"^\s*(?:function\s+)?[A-Za-z_][\w-]*\s*\(\s*\)\s*\{?\s*$") +ANNOT_LINE = re.compile(r"^\s*(?:" + ANNOT + r"\s*)+$") +SH_FUN =re.compile(r"^\s*(?:function\s+)?[A-Za-z_][\w-]*\s*\(\s*\)\s*\{?\s*$") PY_DEF = re.compile(r"^(\s*)(?:async\s+)?def\s+\w+") @@ -73,9 +74,10 @@ def blank(text): def commented(lines, i, raw): - """a comment on the line above line i, past its annotations""" + """a comment on the line above line i, past its annotations (lines of + annotations alone: not an annotated property's, as @Volatile var)""" j = i - 1 - while j >= 0 and re.match(r"^\s*@", lines[j]): + while j >= 0 and ANNOT_LINE.match(lines[j]): j -= 1 if j < 0: return False diff --git a/tools/usb-serial-ids/generate.py b/tools/usb-serial-ids/generate.py index c03d1d0..2602659 100755 --- a/tools/usb-serial-ids/generate.py +++ b/tools/usb-serial-ids/generate.py @@ -33,6 +33,7 @@ SKIP = r"jtag|8u2232c|stmclite|TIRA|UIRT" def fetch(where, path): + """the file at path of Linux at the tag where (from GitHub), or by its name in the directory where""" if os.path.isdir(where): return open(os.path.join(where, os.path.basename(path)), encoding="utf-8", errors="replace").read() url = "https://raw.githubusercontent.com/torvalds/linux/%s/%s" % (where, path) @@ -49,6 +50,7 @@ def ids(texts): defs = dict(re.findall(r"^\s*#define\s+(\w+)\s+\(?\s*(0[xX][0-9a-fA-F]+|\d+|\w+)\s*\)?\s*$", text, flags=re.M)) def value(tok): + """a number, or a #define's name followed to the number it stands for""" seen = 0 while not re.fullmatch(r"0[xX][0-9a-fA-F]+|\d+", tok): tok = defs[tok] @@ -66,6 +68,7 @@ def ids(texts): def main(): + """each chip's IDs (each pair kept for the first chip that has it) into UsbSerialIds.kt and the XML's generated part""" where = sys.argv[1] if len(sys.argv) > 1 else "v6.12" tables, seen = [], {} for name, what, files in CHIPS: