Merge pull request #61 from D-Modem/claude/project-thread-g3spou

Add YMODEM-G, Skip file, ASCII Setup, Send break and Print screen
This commit is contained in:
Neo authored and GitHub committed 2026-11-20 15:52:20 -08:00
commit 1349fc673b
22 files changed
+609 -57

No files matched your search

@@ -64,6 +64,13 @@ data class TerminalSettings(
val answerback: String = "",
/** box drawing and block characters drawn to fill their cells (no gaps in ANSI art) */
val drawBoxes: Boolean = true,
/** a text file sent (Send Text File): the wait after each line, and after each character, in ms (HyperTerminal's ASCII Setup) */
val lineDelayMs: Int = 0,
val charDelayMs: Int = 0,
/** what comes (ASCII Setup): an LF added after each CR, 7-bit ASCII, lines wrapped at the right margin */
val addLineFeeds: Boolean = false,
val sevenBit: Boolean = false,
val wrapLines: Boolean = true,
) {
/** [terminalType]'s profile (the default for one not known) */
val profile: TerminalProfile get() = TerminalProfiles.byId(terminalType) ?: TerminalProfiles.DEFAULT
@@ -95,6 +102,11 @@ class TerminalSettingsStore(private val context: Context) {
val extraKeys = booleanPreferencesKey("extra_keys")
val answerback = stringPreferencesKey("answerback")
val drawBoxes = booleanPreferencesKey("draw_boxes")
val lineDelay = intPreferencesKey("line_delay_ms")
val charDelay = intPreferencesKey("char_delay_ms")
val addLineFeeds = booleanPreferencesKey("add_line_feeds")
val sevenBit = booleanPreferencesKey("seven_bit")
val wrapLines = booleanPreferencesKey("wrap_lines")
}
/** the [E] named [s], or [d] for none or one not known */
@@ -128,6 +140,11 @@ class TerminalSettingsStore(private val context: Context) {
extraKeys = p[K.extraKeys] ?: d.extraKeys,
answerback = p[K.answerback] ?: d.answerback,
drawBoxes = p[K.drawBoxes] ?: d.drawBoxes,
lineDelayMs = p[K.lineDelay] ?: d.lineDelayMs,
charDelayMs = p[K.charDelay] ?: d.charDelayMs,
addLineFeeds = p[K.addLineFeeds] ?: d.addLineFeeds,
sevenBit = p[K.sevenBit] ?: d.sevenBit,
wrapLines = p[K.wrapLines] ?: d.wrapLines,
)
}
@@ -167,6 +184,11 @@ class TerminalSettingsStore(private val context: Context) {
p[K.extraKeys] = s.extraKeys
p[K.answerback] = s.answerback
p[K.drawBoxes] = s.drawBoxes
p[K.lineDelay] = s.lineDelayMs
p[K.charDelay] = s.charDelayMs
p[K.addLineFeeds] = s.addLineFeeds
p[K.sevenBit] = s.sevenBit
p[K.wrapLines] = s.wrapLines
}
/** the font size [sp] stored alone (the pinch's) */
@@ -205,6 +205,13 @@ class TelnetLink(
}
}
/** IAC BRK, on a thread of its own (the caller's may be the UI's): false when not open */
override fun sendBreak(): Boolean {
if (_state.value !is TerminalLink.State.Open) return false
Thread({ send(IAC, BRK) }, "telnet-break").start()
return true
}
/** the new size kept, and sent on a thread of its own if NAWS is on */
override fun resize(cols: Int, rows: Int) {
this.cols = cols
@@ -236,6 +243,7 @@ class TelnetLink(
const val WILL = 251
const val SB = 250
const val SE = 240
const val BRK = 243
const val BINARY = 0
const val ECHO = 1
const val SGA = 3
@@ -33,6 +33,9 @@ interface TerminalLink {
/** octets to the far end: false if it can't take them (closed) */
fun write(data: ByteArray, offset: Int = 0, length: Int = data.size): Boolean
/** a break sent (Telnet's IAC BRK): false when the link has none to send */
fun sendBreak(): Boolean = false
/** the terminal's new size (SSH's window change, Telnet's NAWS) */
fun resize(cols: Int, rows: Int) {}
@@ -231,13 +231,27 @@ class TerminalSession(
}
/** [files] to the remote (which must be receiving: its rz, rb, rx, kermit -r) */
fun sendFiles(protocol: Protocol, files: List<Outgoing>): Boolean {
fun sendFiles(protocol: Protocol, files: List<Outgoing>, lineDelayMs: Int = 0, charDelayMs: Int = 0): Boolean {
if (files.isEmpty()) return false
val t = startTransfer(protocol, sending = true) ?: return false
t.send(files)
// (the waits: a text file's only, HyperTerminal's ASCII Setup)
t.send(files, lineDelayMs.toLong(), charDelayMs.toLong())
return true
}
/** the file being received skipped, the transfer on to the next (ZMODEM, Kermit) */
fun skipTransfer() {
transfer?.skip()
}
/** a break to the far end (Telnet's IAC BRK): false when this link can't send one */
fun sendBreak(): Boolean = link.sendBreak()
/** the screen's text (its lines, their trailing blanks gone), to print */
fun screenText(): String = synchronized(emulator) {
emulator.text(0, 0, emulator.rows - 1, emulator.cols - 1)
}.lines().joinToString("\n") { it.trimEnd() }.trimEnd('\n')
/** the running transfer, if any, cancelled */
fun cancelTransfer() {
transfer?.cancel()
@@ -167,6 +167,9 @@ class TerminalView @JvmOverloads constructor(
synchronized(it.emulator) {
it.emulator.historyMax = s.scrollback
it.emulator.answerback = s.answerback
if (it.emulator.addLineFeeds != s.addLineFeeds) it.emulator.addLineFeeds = s.addLineFeeds
it.emulator.sevenBit = s.sevenBit
it.emulator.wrapLines = s.wrapLines
}
}
if (sizeChanged || fontPx == 0f) measureFont()
@@ -133,7 +133,7 @@ fun TerminalScreen(
session.sendBytes((command + "\r").toByteArray())
delay(800)
}
if (!session.sendFiles(proto, files)) Toast.makeText(context, "A transfer is running already", Toast.LENGTH_SHORT).show()
if (!session.sendFiles(proto, files, s.lineDelayMs, s.charDelayMs)) Toast.makeText(context, "A transfer is running already", Toast.LENGTH_SHORT).show()
}
}
/** the app's PPP on the call the modem has now (logged in by hand), the phone's traffic through it; why not in a toast */
@@ -195,13 +195,23 @@ fun TerminalScreen(
}
}
// how long a connection (Telnet, SSH, rlogin) has been open
var linkSince by remember { mutableLongStateOf(0L) }
LaunchedEffect(linkState) {
linkSince = if (linkState == TerminalLink.State.Open && !session.isLocal) System.currentTimeMillis() else 0L
while (linkSince != 0L) {
now = System.currentTimeMillis()
delay(1000)
}
}
Column(modifier.fillMaxSize().imePadding()) {
if (!fullscreen && sessions.size > 1) {
SessionTabs(sessions, session)
}
if (!fullscreen) {
TopBar(
text = if (isModem) barText(run, status, onlineSince, now, title) else linkText(session, linkState, title),
text = if (isModem) barText(run, status, onlineSince, now, title) else linkText(session, linkState, title, linkSince, now),
isModem = isModem,
capturing = capture != null,
onKeyboard = { view?.toggleKeyboard() },
@@ -246,6 +256,15 @@ fun TerminalScreen(
if (ask != null) pppConsent.launch(ask) else startPpp()
}) else null,
onClear = { session.clear() },
onBreak = {
val sent = session.sendBreak()
Toast.makeText(
context,
if (sent) "Break sent" else "This connection can't send a break (Telnet only)",
Toast.LENGTH_SHORT,
).show()
},
onPrint = { printText(context, session.label, session.screenText()) },
onReset = { session.reset() },
onFullscreen = { onFullscreen(true) },
onAtReference = { showAtReference = true },
@@ -295,6 +314,7 @@ fun TerminalScreen(
TransferBanner(
t, DownloadsIncoming.where(context),
onCancel = { session.cancelTransfer() },
onSkip = { session.skipTransfer() },
onDismiss = { session.dismissTransfer() },
modifier = Modifier.align(Alignment.BottomCenter),
)
@@ -414,8 +434,29 @@ private fun SessionTabs(sessions: List<TerminalSession>, active: TerminalSession
}
}
/** a connection's state, for the bar */
private fun linkText(s: TerminalSession, st: TerminalLink.State, title: String): String {
/** the view of the page being printed, kept until the print job has it */
private var printing: android.webkit.WebView? = null
/** [text] printed (Android's print dialog: a printer or a PDF), as HyperTerminal's Print, in a monospaced font */
private fun printText(context: android.content.Context, name: String, text: String) {
val w = android.webkit.WebView(context)
printing = w
w.webViewClient = object : android.webkit.WebViewClient() {
/** the page ready: the print dialog opened on it */
override fun onPageFinished(view: android.webkit.WebView, url: String?) {
val pm = context.getSystemService(android.content.Context.PRINT_SERVICE) as android.print.PrintManager
val job = name.ifBlank { "Terminal" }
pm.print(job, view.createPrintDocumentAdapter(job), android.print.PrintAttributes.Builder().build())
printing = null
}
}
val html = "<html><body><pre style=\"font-family: monospace; font-size: 10pt\">" +
android.text.TextUtils.htmlEncode(text) + "</pre></body></html>"
w.loadDataWithBaseURL(null, html, "text/html", "UTF-8", null)
}
/** a connection's state, for the bar, with the time it has been open */
private fun linkText(s: TerminalSession, st: TerminalLink.State, title: String, since: Long = 0, now: Long = 0): String {
if (s.isLocal) {
val state = when (st) {
TerminalLink.State.Connecting -> "Starting…"
@@ -432,7 +473,12 @@ private fun linkText(s: TerminalSession, st: TerminalLink.State, title: String):
val where = s.entry?.address ?: s.label
val state = when (st) {
TerminalLink.State.Connecting -> "Connecting to $where…"
TerminalLink.State.Open -> "$what $where"
TerminalLink.State.Open -> "$what $where" + if (since > 0) {
val secs = ((now - since) / 1000).coerceAtLeast(0)
" · %d:%02d:%02d".format(secs / 3600, secs / 60 % 60, secs % 60)
} else {
""
}
is TerminalLink.State.Closed -> "Disconnected" + (st.reason?.let { ": $it" } ?: "")
}
return if (title.isNotBlank() && st == TerminalLink.State.Open) "$state — $title" else state
@@ -475,7 +521,7 @@ private fun barText(
return if (title.isNotBlank()) "$state — $title" else state
}
/** the terminal's bar: its line, the keyboard, snippets and capture buttons, and a menu of the rest (hang up, start PPP, paste, new shells, files, character set, clear, reset, full screen, the AT command reference) */
/** the terminal's bar: its line, the keyboard, snippets and capture buttons, and a menu of the rest (hang up, start PPP, paste, a break, print, new shells, files, character set, clear, reset, full screen, the AT command reference) */
@Composable
private fun TopBar(
text: String,
@@ -495,6 +541,10 @@ private fun TopBar(
/** PPP started on the modem's call (dialled and logged in by hand): null when the modem isn't online */
onStartPpp: (() -> Unit)?,
onClear: () -> Unit,
/** a break to the far end (Telnet) */
onBreak: () -> Unit,
/** the screen printed */
onPrint: () -> Unit,
onReset: () -> Unit,
onFullscreen: () -> Unit,
/** the AT command reference */
@@ -522,6 +572,8 @@ private fun TopBar(
DropdownMenuItem(text = { Text("Start PPP (the internet on this call)") }, onClick = { menu = false; onStartPpp() })
}
DropdownMenuItem(text = { Text("Paste") }, onClick = { menu = false; onPaste() })
DropdownMenuItem(text = { Text("Send break") }, onClick = { menu = false; onBreak() })
DropdownMenuItem(text = { Text("Print screen…") }, onClick = { menu = false; onPrint() })
DropdownMenuItem(text = { Text("New local shell") }, onClick = { menu = false; onNewShell() })
DropdownMenuItem(text = { Text("New Linux shell…") }, onClick = { menu = false; onNewLinux() })
if (onSsh != null) {
@@ -94,6 +94,10 @@ fun TerminalSettingsSection() {
Flag("iCE colours (blink as bright background)", s.iceColors) { set { t -> t.copy(iceColors = it) } }
Flag("Draw line and block characters (gapless ANSI art)", s.drawBoxes) { set { t -> t.copy(drawBoxes = it) } }
Flag("Local echo", s.localEcho) { set { t -> t.copy(localEcho = it) } }
// HyperTerminal's ASCII Setup, for what comes
Flag("Add line feeds to incoming line ends", s.addLineFeeds) { set { t -> t.copy(addLineFeeds = it) } }
Flag("Force incoming data to 7-bit ASCII", s.sevenBit) { set { t -> t.copy(sevenBit = it) } }
Flag("Wrap lines that exceed the terminal width", s.wrapLines) { set { t -> t.copy(wrapLines = it) } }
Flag("Extra keys bar", s.extraKeys) { set { t -> t.copy(extraKeys = it) } }
Flag("Keep the screen on", s.keepScreenOn) { set { t -> t.copy(keepScreenOn = it) } }
var scrollback by remember(s.scrollback) { mutableStateOf(s.scrollback.toString()) }
@@ -116,9 +120,36 @@ fun TerminalSettingsSection() {
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
// HyperTerminal's ASCII Setup: the waits when a text file is sent
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
DelayField("Line delay (ms)", s.lineDelayMs, Modifier.weight(1f)) { set { t -> t.copy(lineDelayMs = it) } }
DelayField("Character delay (ms)", s.charDelayMs, Modifier.weight(1f)) { set { t -> t.copy(charDelayMs = it) } }
}
Text(
"The waits when a text file is sent (Text protocol): after each line, and after each character. " +
"For a remote that loses characters when they come fast.",
style = MaterialTheme.typography.bodySmall,
)
}
}
/** a wait in ms, 0 to 9999 */
@Composable
private fun DelayField(label: String, value: Int, modifier: Modifier, onChange: (Int) -> Unit) {
var text by remember(value) { mutableStateOf(value.toString()) }
OutlinedTextField(
value = text,
onValueChange = { v ->
text = v.filter { it.isDigit() }.take(4)
onChange(text.toIntOrNull() ?: 0)
},
label = { Text(label) },
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
modifier = modifier,
)
}
/** a labelled switch */
@Composable
private fun Flag(label: String, value: Boolean, onChange: (Boolean) -> Unit) {
@@ -20,6 +20,9 @@ import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
@@ -29,6 +32,8 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay
import org.dmodem.app.io.monotonicMs
import org.dmodem.app.transfer.Protocol
import org.dmodem.app.transfer.TransferState
@@ -89,6 +94,14 @@ fun TransferDialog(
modifier = Modifier.padding(top = 4.dp),
)
}
if (protocol == Protocol.YMODEM_G) {
Text(
"YMODEM-G sends with no wait for each block's answer: fast, but for a line that corrects " +
"its errors (a V.42 connection). An error on the line ends the transfer.",
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(top = 4.dp),
)
}
if (protocol.hexFormat != null) {
Text(
if (sending) "The file goes as ${protocol.label}, a line each (a file of them already goes as it is), " +
@@ -108,9 +121,29 @@ fun TransferDialog(
)
}
/** a transfer as it goes (cancel it), or how it ended (dismissed) */
/**
* a transfer as it goes (cancel it; skip the file being received, where the protocol can), or
* how it ended (dismissed); its times and speed as HyperTerminal shows them (a tap on them:
* cps or bps)
*/
@Composable
fun TransferBanner(t: TransferState, savedTo: String, onCancel: () -> Unit, onDismiss: () -> Unit, modifier: Modifier = Modifier) {
fun TransferBanner(
t: TransferState,
savedTo: String,
onCancel: () -> Unit,
onSkip: () -> Unit,
onDismiss: () -> Unit,
modifier: Modifier = Modifier,
) {
var bps by rememberSaveable { mutableStateOf(false) }
// (the times go on while no bytes come: a tick each second)
var now by remember { mutableLongStateOf(monotonicMs()) }
LaunchedEffect(t.running) {
while (t.running) {
now = monotonicMs()
delay(1000)
}
}
Surface(modifier.fillMaxWidth().padding(12.dp), tonalElevation = 6.dp, shape = RoundedCornerShape(12.dp), shadowElevation = 6.dp) {
Column(Modifier.padding(start = 16.dp, end = 8.dp, top = 10.dp, bottom = 6.dp)) {
val p = t.progress
@@ -131,6 +164,14 @@ fun TransferBanner(t: TransferState, savedTo: String, onCancel: () -> Unit, onDi
LinearProgressIndicator(Modifier.fillMaxWidth().padding(end = 8.dp))
}
}
val timing = t.timing(bps, maxOf(now, if (t.running) monotonicMs() else 0))
if (timing.isNotEmpty()) {
Text(
timing,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(top = 4.dp).clickable { bps = !bps },
)
}
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
when {
@@ -141,6 +182,7 @@ fun TransferBanner(t: TransferState, savedTo: String, onCancel: () -> Unit, onDi
},
style = MaterialTheme.typography.bodySmall, modifier = Modifier.weight(1f),
)
if (t.running && !t.sending && t.protocol.canSkip && p.file.isNotEmpty()) TextButton(onClick = onSkip) { Text("Skip file") }
if (t.running) TextButton(onClick = onCancel) { Text("Cancel") } else TextButton(onClick = onDismiss) { Text("OK") }
}
}
+37 -3
View File
@@ -218,8 +218,20 @@
then goes through it, as with the dial of the internet screen
(`PppTakeoverTest`).
The terminal sends and receives files by ZMODEM, YMODEM, XMODEM(-1K) and
Kermit. It also sends and receives Intel HEX or Motorola S-records for
The terminal sends and receives files by ZMODEM, YMODEM, YMODEM-G,
XMODEM(-1K) and Kermit:
- YMODEM-G sends the blocks and does not wait for an ACK. Use it only on a
line that corrects its errors (a V.42 connection). An error on the line
stops the transfer, because YMODEM-G cannot send a block again. When the
receiver asks with C, the sender uses plain YMODEM.
- When you receive by ZMODEM or Kermit, **Skip file** stops the file that
comes now and deletes it. The sender then sends the next file (ZMODEM
sends ZSKIP, Kermit sends X in its ACK).
- The progress shows the elapsed time, the remaining time and the speed of
the file. Tap the speed to show it in cps (characters a second) or in bps
(10 bits a character).
It also sends and receives Intel HEX or Motorola S-records for
EPROM programmers, monitors and boot loaders:
- When it sends a file as records, it uses S1/S2/S3 by the size of the
image, and Intel extended addresses above 64 KB. If the file already
@@ -229,7 +241,29 @@
Plain text is also available. The app sends the bytes of a file without
change, as if you typed them (to an editor, a BBS, `cat > file`). It saves
the received data without change until the line is silent for 10 s.
the received data without change until the line is silent for 10 s. On
Android, the terminal settings have a line delay and a character delay (in
ms), as the ASCII Setup of HyperTerminal has. The app waits for this time
after each line end and after each character.
The terminal settings on Android also have the receive items of the ASCII
Setup of HyperTerminal:
- Add line feeds to incoming line ends: the terminal adds an LF after each
CR. When an LF follows the CR, the terminal does not use that LF, thus a
CR LF does not give two lines.
- Force incoming data to 7-bit ASCII: the terminal removes bit 8 of each
byte.
- Wrap lines that exceed the terminal width: when this is off, the
terminal writes each new character in the last column.
The menu of the Android terminal also has these items of HyperTerminal:
- Send break: on Telnet, the app sends IAC BRK. SSH and rlogin do not
have a break, thus the app shows a message.
- Print screen: the app prints the text of the screen through the print
dialog of Android (to a printer or to a PDF file).
On Telnet, SSH and rlogin, the bar of the terminal shows the time that the
connection is open (h:mm:ss), as the modem bar does for a call.
- **Dial**: the dialing directory. Each entry has the number of the system
(or the SIP user), the AT commands that are necessary before ATD, its
terminal type, its character set and its backspace. One tap starts the
+6
View File
@@ -307,6 +307,12 @@ final class JobsModel: ObservableObject {
/// the transfer cancelled
func cancelTransfer() { transferJob?.cancel() }
/// the file being received skipped, the transfer on to the next (ZMODEM, Kermit)
func skipTransfer() { transferJob?.skip() }
/// the transfer's times and speed, as HyperTerminal shows them ([bps]: bits a second)
func transferTiming(bps: Bool) -> String { transferJob?.timing(bps: bps) ?? transfer?.timing(bps: bps) ?? "" }
/// the last transfer's outcome cleared (not while one's going)
func dismissTransfer() { if transferJob == nil { transfer = nil } }
+12
View File
@@ -16,6 +16,7 @@ struct TransferView: View {
@State private var error: String?
@State private var received: [URL] = []
@State private var preview: URL?
@AppStorage("transferBps") private var bps = false
var body: some View {
NavigationStack {
@@ -70,6 +71,7 @@ struct TransferView: View {
switch proto {
case "ZMODEM": return "sz file (it sends), rz (it receives; ZMODEM starts by itself either way)"
case "YMODEM": return "sb file, rb"
case "YMODEM_G": return "sb file (YMODEM-G is for a V.42 line: an error ends it), rb"
case "XMODEM": return "sx file, rx -c file"
case "XMODEM_1K": return "sx -k file, rx -c file"
default: return "kermit -i -s file, kermit -i -r"
@@ -91,10 +93,20 @@ struct TransferView: View {
Text(bytes(p.bytes)).foregroundStyle(.secondary)
}
}
// (the times and the speed, a second at a time; a tap: cps or bps)
TimelineView(.periodic(from: .now, by: 1)) { _ in
let timing = jobs.transferTiming(bps: bps)
if !timing.isEmpty {
Text(timing).foregroundStyle(.secondary).onTapGesture { bps.toggle() }
}
}
if p.files > 0 { Text("\(p.files) file\(p.files == 1 ? "" : "s") done") }
if p.errors > 0 { Text("\(p.errors) block\(p.errors == 1 ? "" : "s") sent again").foregroundStyle(.secondary) }
if let r = t.result, !r.isEmpty { Text(r).foregroundStyle(.red) }
if t.running {
if !jobs.transferSending && !p.file.isEmpty && t.protocol.canSkip {
Button("Skip file") { jobs.skipTransfer() }
}
Button("Cancel", role: .destructive) { jobs.cancelTransfer() }
} else {
Button("Dismiss") { jobs.dismissTransfer() }
@@ -12,7 +12,7 @@ import kotlin.concurrent.Volatile
/**
* A file transfer on the modem's line (the Android app's terminal's, for
* iOS): files sent to the remote, or received from it, by [protocolName]'s
* name (ZMODEM, YMODEM, XMODEM, XMODEM_1K, KERMIT).
* name (ZMODEM, YMODEM, YMODEM_G, XMODEM, XMODEM_1K, KERMIT…).
*/
class TransferJob(protocolName: String, sending: Boolean, out: DteOut, log: LogOut, changed: Changed) : DteJob(out, log, changed) {
private val transfer = Transfer(
@@ -48,6 +48,12 @@ class TransferJob(protocolName: String, sending: Boolean, out: DteOut, log: LogO
/** the transfer stopped */
fun cancel() = transfer.cancel()
/** the file being received skipped, the transfer on to the next ([canSkip]'s protocols) */
fun skip() = transfer.skip()
/** the times and the speed as HyperTerminal shows them ([bps]: bits a second, else characters) */
fun timing(bps: Boolean): String = state.timing(bps)
companion object {
/** the protocols' names (what each is called: [label]) */
val protocols: List<String> = Protocol.entries.map { it.name }
@@ -55,6 +61,9 @@ class TransferJob(protocolName: String, sending: Boolean, out: DteOut, log: LogO
/** what the protocol [protocolName] is called */
fun label(protocolName: String): String = Protocol.valueOf(protocolName).label
/** whether the file being received can be skipped ([skip]) */
fun canSkip(protocolName: String): Boolean = Protocol.valueOf(protocolName).canSkip
/** whether it sends more than one file */
fun batch(protocolName: String): Boolean = Protocol.valueOf(protocolName).batch
@@ -248,8 +248,51 @@ class TerminalEmulator(
/** a tap at ([fx], [fy]) (fractions of the screen from its top left) as the terminal takes it: what to send (a RIP button's text), or null if it takes none */
fun tap(fx: Double, fy: Double): ByteArray? = interpreter.tap(fx, fy)
/** HyperTerminal's ASCII Setup, for what comes: an LF after each CR (a CR LF's own LF not doubled) */
var addLineFeeds = false
set(v) { field = v; asciiCr = false }
/** each octet that comes as 7-bit ASCII (its 8th bit cleared) */
var sevenBit = false
/** lines wrap at the right margin (false: each character past it written in the last column) */
var wrapLines = true
/** the last octet that came was a CR ([addLineFeeds]) */
private var asciiCr = false
/** [data]'s first [length] octets as [addLineFeeds] and [sevenBit] have them, and how many */
private fun ascii(data: ByteArray, length: Int): Pair<ByteArray, Int> {
val out = ByteArray(if (addLineFeeds) length * 2 else length)
var n = 0
for (i in 0 until length) {
var b = data[i].toInt() and 0xff
if (sevenBit) b = b and 0x7f
if (addLineFeeds) {
if (b == LF && asciiCr) {
asciiCr = false
continue
}
asciiCr = b == CR
}
out[n++] = b.toByte()
if (addLineFeeds && b == CR) out[n++] = LF.toByte()
}
return out to n
}
/** the remote's octets, decoded in [decoder]'s set (or as they are, to an interpreter that reads octets) */
fun append(data: ByteArray, length: Int = data.size) {
if (addLineFeeds || sevenBit) {
val (d, n) = ascii(data, length)
feed(d, n)
} else {
feed(data, length)
}
}
/** [length] octets of [data] to the interpreter */
private fun feed(data: ByteArray, length: Int) {
if (interpreter.readsOctets) {
for (i in 0 until length) interpreter.process(data[i].toInt() and 0xff)
} else {
@@ -449,7 +492,7 @@ class TerminalEmulator(
}
lastChar = cp
if (pendingWrap) {
if (autowrap) {
if (autowrap && wrapLines) {
screen[cursorY].wrapped = true
carriageReturn()
lineFeed()
@@ -461,7 +504,7 @@ class TerminalEmulator(
if (cursorX >= lc) cursorX = lc - 1
// a wide character with one column left: to the next line (the last cell left blank)
if (w == 2 && cursorX == lc - 1) {
if (!autowrap || lc < 2) return
if (!autowrap || !wrapLines || lc < 2) return
screen[cursorY].clear(cursorX, cols, style)
screen[cursorY].wrapped = true
carriageReturn()
@@ -973,6 +1016,8 @@ class TerminalEmulator(
const val NO_COLOR = 0
/** the largest sixel image (pixels a side) */
const val MAX_IMAGE = 2048
private const val CR = 13
private const val LF = 10
/** an ESC Fe (ESC [, ESC P, ST's ESC and backslash ...): what has a C1 form */
private val ESC_FE = Regex("\u001b([\\x40-\\x5f])")
@@ -529,6 +529,8 @@ class Kermit(
// (a name sent "converted", all capitals, as C-Kermit does: back in lower case)
if (n.any { it.isLetter() } && n.none { it.isLowerCase() }) n.lowercase() else n
}
// (a skip asked for before this file: not for it)
io.takeSkip()
val (o, actual) = into.create(name, -1)
out = o.buffered()
current = actual
@@ -560,6 +562,9 @@ class Kermit(
decode(r.data, counted)
got += counted.n
report { it.copy(bytes = got) }
// the user's skip: X in the ACK (the sender ends the file with Z D, and
// the file is dropped)
if (io.takeSkip()) reply = "X".encodeToByteArray()
}
'Z' -> {
val o = out
@@ -3,6 +3,7 @@
package org.dmodem.app.transfer
import org.dmodem.app.io.IOException
import org.dmodem.app.io.sleepMs
/**
* A file as plain text: no protocol at all. Sending: its bytes as they
@@ -17,8 +18,12 @@ class TextTransfer(
/** the quiet that ends a receive (the tests' shorter) */
private val quietMs: Long = QUIET_MS,
) {
/** [file] sent verbatim */
fun send(file: Outgoing) {
/**
* [file] sent verbatim; paced, as HyperTerminal's ASCII Setup does it, with a wait of
* [lineDelayMs] after each line end (CR, LF, or the LF of CR LF) and [charDelayMs] after
* each character
*/
fun send(file: Outgoing, lineDelayMs: Long = 0, charDelayMs: Long = 0) {
val buf = ByteArray(CHUNK)
var sent = 0L
file.open().use { src ->
@@ -27,8 +32,25 @@ class TextTransfer(
val n = src.read(buf, 0, buf.size)
if (n < 0) break
if (n == 0) continue
io.write(buf.copyOf(n))
sent += n
if (lineDelayMs <= 0 && charDelayMs <= 0) {
io.write(buf.copyOf(n))
sent += n
progress(Progress(file.name, sent, file.size))
continue
}
for (i in 0 until n) {
val c = buf[i].toInt() and 0xff
io.write(c)
sent++
// (the LF of a CR LF ends the line, not the CR)
val lineEnd = c == LF || (c == CR && (i + 1 >= n || buf[i + 1].toInt() != LF))
val ms = charDelayMs + if (lineEnd) lineDelayMs else 0
if (ms > 0) {
progress(Progress(file.name, sent, file.size))
sleepMs(ms)
if (io.isCancelled) throw TransferCancelled("cancelled")
}
}
progress(Progress(file.name, sent, file.size))
}
}
@@ -74,6 +96,8 @@ class TextTransfer(
companion object {
const val CHUNK = 1024
private const val CR = 13
private const val LF = 10
/** how long the first byte may take to come, and the quiet that ends it */
const val FIRST_MS = 60_000L
const val QUIET_MS = 10_000L
@@ -4,6 +4,7 @@ package org.dmodem.app.transfer
import org.dmodem.app.io.IOException
import org.dmodem.app.io.background
import org.dmodem.app.io.monotonicMs
import org.dmodem.app.io.sleepMs
import kotlin.concurrent.Volatile
@@ -11,6 +12,8 @@ import kotlin.concurrent.Volatile
enum class Protocol(val label: String, val batch: Boolean) {
ZMODEM("ZMODEM", true),
YMODEM("YMODEM", true),
/** YMODEM with no ACKs: for a line that corrects its errors (a modem's V.42); an error ends it */
YMODEM_G("YMODEM-G", true),
XMODEM("XMODEM", false),
XMODEM_1K("XMODEM-1K", false),
KERMIT("Kermit", true),
@@ -26,6 +29,8 @@ enum class Protocol(val label: String, val batch: Boolean) {
fun remoteCommand(remoteSends: Boolean): String = when (this) {
ZMODEM -> if (remoteSends) "sz -b " else "rz -b"
YMODEM -> if (remoteSends) "sb " else "rb"
// (sb sends YMODEM-G when asked with G; lrzsz's rb asks with C, and gets plain YMODEM)
YMODEM_G -> if (remoteSends) "sb " else "rb"
XMODEM -> if (remoteSends) "sx " else "rx -c "
XMODEM_1K -> if (remoteSends) "sx -k " else "rx -c "
KERMIT -> if (remoteSends) "kermit -i -s " else "kermit -i -r"
@@ -35,6 +40,9 @@ enum class Protocol(val label: String, val batch: Boolean) {
TEXT -> if (remoteSends) "cat " else ""
}
/** whether the file being received can be skipped (the protocol tells the sender) */
val canSkip: Boolean get() = this == ZMODEM || this == KERMIT
/** the hex records' format, for the two that are */
val hexFormat: HexRecords.Format?
get() = when (this) {
@@ -54,8 +62,56 @@ data class TransferState(
val result: String? = null,
/** the names the received files got */
val received: List<String> = emptyList(),
/** when it started ([monotonicMs]), and when it ended (0 while it runs) */
val startedMs: Long = 0,
val endedMs: Long = 0,
/** when the file now going started ([monotonicMs]) */
val fileStartedMs: Long = 0,
) {
val running: Boolean get() = result == null
/** how long it has taken, at [now] ([monotonicMs]) */
fun elapsedMs(now: Long = monotonicMs()): Long = if (startedMs == 0L) 0 else ((if (endedMs > 0) endedMs else now) - startedMs).coerceAtLeast(0)
/** the file's bytes a second (its throughput), at [now]; 0 before a second has gone */
fun cps(now: Long = monotonicMs()): Long {
if (fileStartedMs == 0L) return 0
val ms = (if (endedMs > 0) endedMs else now) - fileStartedMs
return if (ms < 1000) 0 else progress.bytes * 1000 / ms
}
/** the time the file still takes at its [cps], at [now]; -1 not known */
fun remainingMs(now: Long = monotonicMs()): Long {
val c = cps(now)
if (!running || c <= 0 || progress.size <= 0) return -1
return (progress.size - progress.bytes).coerceAtLeast(0) * 1000 / c
}
/**
* the times and the speed as HyperTerminal's progress shows them: "Elapsed 0:00:12,
* Remaining 0:01:00, 2340 cps" ([bps]: bits a second, 10 to a character, as its cps/bps button gives)
*/
fun timing(bps: Boolean): String = timing(bps, monotonicMs())
/** [timing] at [now] ([monotonicMs]) */
fun timing(bps: Boolean, now: Long): String {
if (startedMs == 0L) return ""
val parts = ArrayList<String>()
parts.add("Elapsed " + clock(elapsedMs(now)))
val left = remainingMs(now)
if (left >= 0) parts.add("Remaining " + clock(left))
val c = cps(now)
if (c > 0) parts.add(if (bps) "${c * 10} bps" else "$c cps")
return parts.joinToString(", ")
}
companion object {
/** [ms] as HyperTerminal shows a time: 0:01:05 */
fun clock(ms: Long): String {
val s = ms.coerceAtLeast(0) / 1000
return "${s / 3600}:" + "${s / 60 % 60}".padStart(2, '0') + ":" + "${s % 60}".padStart(2, '0')
}
}
}
/**
@@ -83,13 +139,18 @@ class Transfer(
onState(s)
}
private val progress: (Progress) -> Unit = { p -> update(state.copy(progress = p)) }
private val progress: (Progress) -> Unit = { p ->
// (a new file: its throughput from now)
val fileStarted = if (p.file != state.progress.file || state.fileStartedMs == 0L) monotonicMs() else state.fileStartedMs
update(state.copy(progress = p, fileStartedMs = fileStarted))
}
/** files received into [into] ([name]: XMODEM's, which sends none) */
fun receive(into: Incoming, name: String = "received.bin") = start {
when (protocol) {
Protocol.ZMODEM -> ZModem(io, progress).receive(into)
Protocol.YMODEM -> XYModem(io, progress).receiveY(into)
Protocol.YMODEM_G -> XYModem(io, progress).receiveY(into, g = true)
Protocol.XMODEM, Protocol.XMODEM_1K -> listOf(XYModem(io, progress).receiveX(into, name))
Protocol.KERMIT -> Kermit(io, progress).also { kermit = it }.receive(into)
Protocol.INTEL_HEX, Protocol.SREC -> HexTransfer(io, protocol.hexFormat!!, progress).receive(into, name)
@@ -97,23 +158,27 @@ class Transfer(
}
}
/** [files] sent ([files]' first only, for XMODEM) */
fun send(files: List<Outgoing>) = start {
/**
* [files] sent ([files]' first only, for XMODEM); plain text with a wait of [lineDelayMs]
* after each line and [charDelayMs] after each character (HyperTerminal's ASCII Setup)
*/
fun send(files: List<Outgoing>, lineDelayMs: Long = 0, charDelayMs: Long = 0) = start {
when (protocol) {
Protocol.ZMODEM -> ZModem(io, progress).send(files)
Protocol.YMODEM -> XYModem(io, progress).sendY(files)
Protocol.YMODEM_G -> XYModem(io, progress).sendY(files, g = true)
Protocol.XMODEM -> XYModem(io, progress).sendX(files.first(), oneK = false)
Protocol.XMODEM_1K -> XYModem(io, progress).sendX(files.first(), oneK = true)
Protocol.KERMIT -> Kermit(io, progress).also { kermit = it }.send(files)
Protocol.INTEL_HEX, Protocol.SREC -> HexTransfer(io, protocol.hexFormat!!, progress).send(files.first())
Protocol.TEXT -> TextTransfer(io, progress).send(files.first())
Protocol.TEXT -> TextTransfer(io, progress).send(files.first(), lineDelayMs, charDelayMs)
}
emptyList()
}
/** [body] run on a thread of its own: its end (the files' names, or why it failed) the state's, then [onEnd] with what was left unread */
private fun start(body: () -> List<String>) {
update(state)
update(state.copy(startedMs = monotonicMs()))
background("transfer-${protocol.name.lowercase()}") {
val end = try {
val names = body()
@@ -127,11 +192,17 @@ class Transfer(
}
// (what the other side still sends of the protocol settles first)
if (end.result != "") sleepMs(300)
update(end)
onEnd(end, io.leftover())
val done = end.copy(endedMs = monotonicMs())
update(done)
onEnd(done, io.leftover())
}
}
/** the file being received skipped, and the transfer on to the next (ZMODEM's ZSKIP, Kermit's X) */
fun skip() {
if (state.running && !sending && protocol.canSkip) io.requestSkip()
}
/** stopped: the other side told (CANs; Kermit's E packet), the thread ends at its next read */
fun cancel() {
if (!state.running) return
@@ -80,6 +80,23 @@ class TransferIo(private val send: (ByteArray) -> Unit) {
return out.toByteArray()
}
@kotlin.concurrent.Volatile private var skip = false
/** the user's Skip file: the protocol takes it at its next look ([takeSkip]) */
fun requestSkip() {
skip = true
}
/** whether the user asked to skip the file now (once) */
fun takeSkip(): Boolean {
if (!skip) return false
skip = false
return true
}
/** whether a skip waits to be taken (it is not taken) */
val skipWanted: Boolean get() = skip
/** cancelled for [why]: reads and writes throw TransferCancelled from now on */
fun cancel(why: String) {
cancelled = why
@@ -10,6 +10,12 @@ import org.dmodem.app.io.*
* blocks, CRC, a batch of files each named and sized in block 0), both
* ways. Errors are repeated (NAK) up to [MAX_ERRORS] times; CAN CAN
* from the other side ends it.
*
* YMODEM-G ([receiveY], [sendY] with g): the receiver asks with G, and
* the sender sends the blocks with no wait for an ACK (for a line that
* corrects its errors, a modem's V.42). An error ends it, as no block can
* be sent again; each file's EOT is still acknowledged. A sender asked
* with C does plain YMODEM.
*/
class XYModem(
private val io: TransferIo,
@@ -54,12 +60,18 @@ class XYModem(
}
}
/** a YMODEM batch received: the names the files got */
fun receiveY(into: Incoming): List<String> {
/** YMODEM-G: no ACKs, no blocks again */
private var g = false
/** a YMODEM batch received (YMODEM-G if [g]): the names the files got */
fun receiveY(into: Incoming, g: Boolean = false): List<String> {
this.g = g
val names = ArrayList<String>()
while (true) {
// block 0: the file's name and size, or an empty one (the batch over)
val b0 = startAndRead(ymodem = true) ?: throw IOException("the sender didn't start")
// (lrzsz's sb in YMODEM-G ends with no empty block 0: the batch over when none comes)
val b0 = startAndRead(ymodem = true, tries = if (g && names.isNotEmpty()) 2 else 10)
?: if (g && names.isNotEmpty()) return names else throw IOException("the sender didn't start")
if (b0.number != 0) throw IOException("no YMODEM header block")
val data = b0.data
if (data[0] == 0.toByte()) {
@@ -71,12 +83,13 @@ class XYModem(
val meta = latin1String(data, nul + 1, data.size - nul - 1).trimEnd('\u0000').split(' ')
val size = meta.getOrNull(0)?.toLongOrNull() ?: -1
val mtime = meta.getOrNull(1)?.toLongOrNull(8) ?: 0
io.write(ACK)
// (YMODEM-G: block 0 not acknowledged, G asks for the data)
if (!g) io.write(ACK)
val (out, actual) = into.create(name, size)
report { it.copy(file = actual, bytes = 0, size = size) }
try {
out.use { o ->
io.write(C)
io.write(if (g) G else C)
receiveFile(o, size, ymodem = true, first = null, holdLast = null)
}
into.done(actual, mtime)
@@ -92,11 +105,14 @@ class XYModem(
private class Block(val number: Int, val data: ByteArray)
/** the first block, asked for with C (CRC) and, for XMODEM, NAK (a checksum) when C isn't answered */
private fun startAndRead(ymodem: Boolean): Block? {
private fun startAndRead(ymodem: Boolean, tries: Int = 10): Block? {
var crc = true
for (attempt in 0 until 10) {
bad = false
for (attempt in 0 until tries) {
if (attempt == 4 && !ymodem) crc = false
io.write(if (crc) C else NAK)
// (a damaged block 0 asked for again with NAK: a C could be taken for its ACK and a
// request for the data)
io.write(if (g) G else if (crc && !(ymodem && bad)) C else NAK)
val b = readBlock(crc, 3000) ?: continue
this.crc = crc
return b
@@ -109,6 +125,9 @@ class XYModem(
/** the sender's EOT came instead of a block ([readBlock]) */
private var eot = false
/** a damaged block came ([readBlock]) */
private var bad = false
/**
* a block within [waitMs], its CRC or checksum checked: (number, data);
* null on a timeout, a bad block (the line purged) or EOT (which sets
@@ -116,6 +135,7 @@ class XYModem(
*/
private fun readBlock(useCrc: Boolean, waitMs: Long): Block? {
eot = false
bad = false
// (what isn't a block's start let go by: the sender's own messages, line noise)
val deadline = monotonicMs() + waitMs
var size = 0
@@ -155,6 +175,7 @@ class XYModem(
private fun badBlock(): Block? {
// (what's left of the bad block: let it go by)
while (io.read(200) >= 0) { /* drop */ }
bad = true
return null
}
@@ -174,15 +195,17 @@ class XYModem(
block = readBlock(crc, timeoutMs)
if (block == null) {
if (eot) {
// YMODEM: the first EOT answered NAK, the second ACK (to be sure it was one)
// YMODEM: the first EOT answered NAK, the second ACK (to be sure it was
// one); YMODEM-G: ACK
eots++
if (ymodem && eots == 1) {
if (ymodem && eots == 1 && !g) {
io.write(NAK)
continue
}
io.write(ACK)
break
}
if (g) gFail()
if (++errors > MAX_ERRORS) throw IOException("too many errors on the line")
report { it.copy(errors = it.errors + 1) }
io.write(NAK)
@@ -204,7 +227,7 @@ class XYModem(
written += data.size
expect++
errors = 0
io.write(ACK)
if (!g) io.write(ACK)
report { it.copy(bytes = written) }
}
(expect - 1) and 0xff -> io.write(ACK) // a repeat of one already had (our ACK lost)
@@ -217,34 +240,43 @@ class XYModem(
held?.let { holdLast?.write(it) }
}
/** YMODEM-G's end on an error: no block can come again */
private fun gFail(): Nothing {
io.write(CAN, CAN, CAN, CAN, CAN)
throw IOException("an error on the line (YMODEM-G cannot send a block again)")
}
// ------------------------------------------------------------------
// sending
/** one file by XMODEM (1K blocks if [oneK]) */
fun sendX(file: Outgoing, oneK: Boolean) {
val useCrc = waitForStart() ?: throw IOException("the receiver didn't start")
val start = waitForStart(g = false) ?: throw IOException("the receiver didn't start")
report { it.copy(file = file.name, bytes = 0, size = file.size) }
file.open().use { sendData(it, if (oneK) 1024 else 128, useCrc, ymodem = false) }
file.open().use { sendData(it, if (oneK) 1024 else 128, start == START_CRC, ymodem = false, streaming = false) }
report { it.copy(files = it.files + 1) }
}
/** a YMODEM batch */
fun sendY(files: List<Outgoing>) {
/** a YMODEM batch (YMODEM-G if [g] and the receiver asks with G; asked with C, plain YMODEM) */
fun sendY(files: List<Outgoing>, g: Boolean = false) {
for (f in files) {
if (waitForStart() != true) throw IOException("the receiver didn't start")
val start = waitForStart(g)
if (start == null || start == START_CHECKSUM) throw IOException("the receiver didn't start")
val streaming = start == START_G
val head = ByteArray(128)
val meta = (f.name.substringAfterLast('/').encodeToByteArray() + 0) +
("${if (f.size >= 0) f.size else 0} ${(f.mtime.coerceAtLeast(0)).toString(8)} 0").encodeToByteArray()
val block0 = if (meta.size > 128) ByteArray(1024) else head
meta.copyInto(block0, 0, 0, minOf(meta.size, block0.size))
sendBlock(0, block0, true)
if (streaming) io.write(blockBytes(0, block0, true)) else sendBlock(0, block0, true)
report { it.copy(file = f.name, bytes = 0, size = f.size) }
if (waitForStart() != true) throw IOException("the receiver didn't ask for the data")
f.open().use { sendData(it, 1024, useCrc = true, ymodem = true) }
if (waitForStart(g) != start) throw IOException("the receiver didn't ask for the data")
f.open().use { sendData(it, 1024, useCrc = true, ymodem = true, streaming = streaming) }
report { it.copy(files = it.files + 1) }
}
// the batch over: an empty block 0
if (waitForStart() != true) throw IOException("the receiver didn't ask for the end")
val end0 = waitForStart(g)
if (end0 == null || end0 == START_CHECKSUM) throw IOException("the receiver didn't ask for the end")
// (rb exits as it takes it: its ACK can be lost with it, and every file is in)
val end = blockBytes(0, ByteArray(128), true)
for (attempt in 0 until 3) {
@@ -253,21 +285,25 @@ class XYModem(
}
}
/** C (CRC: true) or NAK (checksum: false) from the receiver; null if neither came */
private fun waitForStart(): Boolean? {
/** C ([START_CRC]), NAK ([START_CHECKSUM]) or, when [g], G ([START_G]) from the receiver; null if none came */
private fun waitForStart(g: Boolean): Int? {
val end = monotonicMs() + 60_000
while (monotonicMs() < end) {
when (io.read(timeoutMs)) {
C -> return true
NAK -> return false
G -> if (g) return START_G
C -> return START_CRC
NAK -> return START_CHECKSUM
CAN -> if (io.read(1000) == CAN) throw TransferCancelled("cancelled by the receiver")
}
}
return null
}
/** the file's data sent in blocks of [blockSize] (a short last one in 128, padded with SUB), then EOT until acknowledged */
private fun sendData(input: Source, blockSize: Int, useCrc: Boolean, ymodem: Boolean) {
/**
* the file's data sent in blocks of [blockSize] (a short last one in 128, padded with SUB),
* then EOT until acknowledged; [streaming]: the blocks with no wait for an ACK (YMODEM-G)
*/
private fun sendData(input: Source, blockSize: Int, useCrc: Boolean, ymodem: Boolean, streaming: Boolean) {
var n = 1
var sent = 0L
val buf = ByteArray(blockSize)
@@ -283,7 +319,12 @@ class XYModem(
val size = if (len <= 128) 128 else blockSize
val data = buf.copyOf(size)
for (i in len until size) data[i] = SUB.toByte()
sendBlock(n, data, useCrc)
if (streaming) {
io.write(blockBytes(n, data, true))
gCheck()
} else {
sendBlock(n, data, useCrc)
}
sent += len
n++
report { it.copy(bytes = sent) }
@@ -298,6 +339,13 @@ class XYModem(
}
}
/** YMODEM-G: the receiver's CAN CAN, if it sent them (no wait) */
private fun gCheck() {
while (io.available()) {
if (io.read(0) == CAN && io.read(1000) == CAN) throw TransferCancelled("cancelled by the receiver")
}
}
/** a block sent until it's acknowledged */
private fun sendBlock(n: Int, data: ByteArray, useCrc: Boolean) {
val bytes = blockBytes(n, data, useCrc)
@@ -357,6 +405,10 @@ class XYModem(
const val CAN = 0x18
const val SUB = 0x1a
const val C = 'C'.code
const val G = 'G'.code
const val START_CHECKSUM = 0
const val START_CRC = 1
const val START_G = 2
const val MAX_ERRORS = 10
}
}
@@ -285,6 +285,8 @@ class ZModem(
fun zrinit() = sendHex(Header.flags(ZRINIT, CANFDX or CANOVIO or CANFC32))
zrinit()
var lastHeaderAt = monotonicMs()
// (the last file skipped: its stream's ZEOF, if our ZSKIP was lost, answered again)
var skipped = false
while (true) {
val h = try {
readHeader()
@@ -313,7 +315,11 @@ class ZModem(
sendHex(Header(ZNAK))
continue
}
val name = receiveFile(d.first, into) ?: continue
// (a skip asked for before this file: not for it)
io.takeSkip()
val name = receiveFile(d.first, into)
skipped = name == null
if (name == null) continue
names.add(name)
report { it.copy(files = it.files + 1) }
zrinit()
@@ -331,6 +337,7 @@ class ZModem(
sendHex(Header.pos(ZCOMPL, 0))
}
ZFREECNT -> sendHex(Header.pos(ZACK, 0))
ZEOF -> if (skipped) sendHex(Header.pos(ZSKIP, 0))
else -> {}
}
}
@@ -363,6 +370,12 @@ class ZModem(
out.use { o ->
rpos()
loop@ while (true) {
// the user's skip: ZSKIP, and the file dropped (the sender goes on to its next)
if (io.takeSkip()) {
sendHex(Header.pos(ZSKIP, 0))
io.purge()
break@loop
}
// (8 KB of a stream with no header in it: ours, at pos, lost; asked for again)
val h = readHeader(garbageMax = 8 * 1024, nullOnGarbage = true)
if (h == null) {
@@ -399,6 +412,7 @@ class ZModem(
ZCRCE -> continue@loop
// ZCRCG: more follows
}
if (io.skipWanted) continue@loop
}
}
ZEOF -> {
@@ -627,6 +641,7 @@ class ZModem(
if (end == ZCRCQ) {
sinceAck = 0
val to = waitForAck(r.pos)
if (to == SKIPPED) return
if (to != null) {
back(to)
continue@resend
@@ -652,13 +667,15 @@ class ZModem(
}
}
/** a ZCRCQ's answer: null for its ACK, else the position a ZRPOS asks for */
/** a ZCRCQ's answer: null for its ACK, [SKIPPED] for a ZSKIP, else the position a ZRPOS asks for */
private fun waitForAck(pos: Long): Long? {
repeat(MAX_ERRORS) {
val h = readHeaderOrNull() ?: return@repeat
when (h.type) {
ZACK -> return null
ZRPOS -> return h.pos
// (the receiver skipped the file)
ZSKIP -> return SKIPPED
ZCAN, ZABORT -> throw TransferCancelled("cancelled by the receiver")
}
}
@@ -712,6 +729,8 @@ class ZModem(
/** bytes between the sender's ZCRCQs (its window) */
const val WINDOW = 16 * 1024
const val MAX_ERRORS = 10
/** [waitForAck]'s answer to a ZSKIP */
const val SKIPPED = -2L
/** after a ZRPOS, the time the sender's stream from before it may still take to stop coming */
const val RPOS_GRACE_MS = 1000L
@@ -20,6 +20,28 @@ class TerminalEmulatorTest {
/** [s] fed in as Latin-1 octets */
private fun TerminalEmulator.send(s: String) = append(s.latin1())
/** ASCII Setup: an LF after a CR (a CR LF's own, in the next chunk, not doubled), 7 bits, no wrap */
@Test
fun asciiSetup() {
val t = term(10, 5)
t.addLineFeeds = true
t.send("one\rtwo\r")
t.send("\nthree")
assertEquals("one", t.row(0))
assertEquals("two", t.row(1))
assertEquals("three", t.row(2))
assertEquals(2, t.cursorY)
val s = term(10, 5)
s.sevenBit = true
s.send("\u00c1\u00e2")
assertEquals("Ab", s.row(0))
val w = term(10, 5)
w.wrapLines = false
w.send("0123456789XY")
assertEquals("012345678Y", w.row(0))
assertEquals("", w.row(1))
}
/** text wraps at the width, and what scrolls off the top goes into the history, still joined to its next line */
@Test
fun textWrapsAndScrollsIntoTheHistory() {
@@ -77,4 +77,18 @@ class TextTransferTest {
assertEquals(0, raw.size)
assertTrue(!Protocol.TEXT.batch)
}
/** the line and character delays: the bytes as they were, and the waits they add */
@Test
fun pacedByTheDelays() = runBlocking {
val wire = Bytes()
val a = TransferIo { bytes -> wire.write(bytes, 0, bytes.size) }
// 4 line ends (CR LF, LF, CR, CR LF) in 14 characters: 4 × 40 + 14 × 5 = 230 ms at the least
val paced = "ab\r\ncd\nef\rgh\r\n".encodeToByteArray()
val t0 = org.dmodem.app.io.monotonicMs()
TextTransfer(a, {}).send(outgoing("p.txt", paced), lineDelayMs = 40, charDelayMs = 5)
val took = org.dmodem.app.io.monotonicMs() - t0
assertContentEquals(paced, wire.toByteArray())
assertTrue(took >= 4 * 40 + paced.size * 5 - 20, "took $took ms")
}
}
@@ -12,11 +12,13 @@ import kotlin.random.Random
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertTrue
/**
* The transfers both ways in memory, the sender's line the receiver's
* (common Kotlin: the JVM, and natively as iOS has it): XMODEM, YMODEM,
* ZMODEM and Kermit, each file as it was sent; Kermit's dates.
* YMODEM-G, ZMODEM and Kermit, each file as it was sent; a file skipped
* (ZMODEM, Kermit); Kermit's dates.
*/
class TransferLoopbackTest {
/** files in memory, and what came */
@@ -97,6 +99,51 @@ class TransferLoopbackTest {
assertContentEquals(small, m.files.getValue("small.txt").toByteArray())
}
/** YMODEM-G: a batch of two streamed with no ACKs, each file whole */
@Test
fun ymodemG() {
val m = Memory()
val names = both({ XYModem(it).sendY(listOf(outgoing("g.bin", data), outgoing("g.txt", small)), g = true) }, { XYModem(it).receiveY(m, g = true) })
assertEquals(listOf("g.bin", "g.txt"), names)
assertContentEquals(data, m.files.getValue("g.bin").toByteArray())
assertContentEquals(small, m.files.getValue("g.txt").toByteArray())
}
/** a YMODEM-G sender asked with C (plain YMODEM): plain YMODEM, each file whole */
@Test
fun ymodemGSenderToYmodem() {
val m = Memory()
val names = both({ XYModem(it).sendY(listOf(outgoing("a.bin", data)), g = true) }, { XYModem(it).receiveY(m) })
assertEquals(listOf("a.bin"), names)
assertContentEquals(data, m.files.getValue("a.bin").toByteArray())
}
/** ZMODEM: the first file skipped part way (ZSKIP), the second whole */
@Test
fun zmodemSkip() {
val m = Memory()
val names = both({ ZModem(it).send(listOf(outgoing("a.bin", data), outgoing("b.txt", small))) }, { io ->
var asked = false
ZModem(io, { p -> if (!asked && p.file == "a.bin" && p.bytes > 8000) { asked = true; io.requestSkip() } }).receive(m)
})
assertEquals(listOf("b.txt"), names)
assertTrue("a.bin" !in m.files)
assertContentEquals(small, m.files.getValue("b.txt").toByteArray())
}
/** Kermit: the first file skipped part way (X in the ACK), the second whole */
@Test
fun kermitSkip() {
val m = Memory()
val names = both({ Kermit(it).send(listOf(outgoing("a.bin", data), outgoing("b.txt", small))) }, { io ->
var asked = false
Kermit(io, { p -> if (!asked && p.file == "a.bin" && p.bytes > 8000) { asked = true; io.requestSkip() } }).receive(m)
})
assertEquals(listOf("b.txt"), names)
assertTrue("a.bin" !in m.files)
assertContentEquals(small, m.files.getValue("b.txt").toByteArray())
}
/** Kermit: a batch of two, each file whole, with its time there and back */
@Test
fun kermit() {