mirror of
https://github.com/D-Modem/app.git
synced 2026-11-28 17:38:05 -08:00
Comments for every function: the shared code, batch 7 of 8
Comment lines only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0172Hejd12i4aYikYW9vgpZs
This commit is contained in:
29 files changed
+227
No files matched your search
@@ -19,15 +19,21 @@ expect open class IOException(message: String?) : Exception
|
||||
|
||||
/** bytes coming in: up to [len] of them into [b] at [off], how many (-1 at the end) */
|
||||
interface Source : AutoCloseable {
|
||||
/** up to [len] bytes into [b] at [off]: how many, -1 at the end */
|
||||
fun read(b: ByteArray, off: Int = 0, len: Int = b.size - off): Int
|
||||
/** the source let go of (nothing, unless it holds something) */
|
||||
override fun close() {}
|
||||
}
|
||||
|
||||
/** bytes going out */
|
||||
interface Sink : AutoCloseable {
|
||||
/** [len] bytes of [b] from [off] sent on */
|
||||
fun write(b: ByteArray, off: Int = 0, len: Int = b.size - off)
|
||||
/** the one byte [b] sent on */
|
||||
fun write(b: Int) = write(byteArrayOf(b.toByte()), 0, 1)
|
||||
/** what is held back sent on (nothing, unless it holds some) */
|
||||
fun flush() {}
|
||||
/** the sink let go of (nothing, unless it holds something) */
|
||||
override fun close() {}
|
||||
}
|
||||
|
||||
@@ -37,23 +43,28 @@ class Bytes(capacity: Int = 64) : Sink {
|
||||
var size = 0
|
||||
private set
|
||||
|
||||
/** the buffer grown, doubling, to fit [n] more */
|
||||
private fun room(n: Int) {
|
||||
if (size + n > buf.size) buf = buf.copyOf(maxOf(buf.size * 2, size + n))
|
||||
}
|
||||
|
||||
/** the byte [b] appended */
|
||||
override fun write(b: Int) {
|
||||
room(1)
|
||||
buf[size++] = b.toByte()
|
||||
}
|
||||
|
||||
/** [len] bytes of [b] from [off] appended */
|
||||
override fun write(b: ByteArray, off: Int, len: Int) {
|
||||
room(len)
|
||||
b.copyInto(buf, size, off, off + len)
|
||||
size += len
|
||||
}
|
||||
|
||||
/** a copy of the bytes so far */
|
||||
fun toByteArray(): ByteArray = buf.copyOf(size)
|
||||
|
||||
/** emptied, keeping its room */
|
||||
fun reset() {
|
||||
size = 0
|
||||
}
|
||||
@@ -92,6 +103,7 @@ class ByteQueue {
|
||||
return head != null
|
||||
}
|
||||
|
||||
/** every waiting chunk dropped */
|
||||
fun clear() {
|
||||
head = null
|
||||
while (ch.tryReceive().isSuccess) Unit
|
||||
@@ -147,6 +159,7 @@ fun Sink.buffered(size: Int = 8192): Sink {
|
||||
private val buf = ByteArray(size)
|
||||
private var n = 0
|
||||
|
||||
/** [len] bytes of [b] gathered, or written straight through when as big as the buffer */
|
||||
override fun write(b: ByteArray, off: Int, len: Int) {
|
||||
if (len >= size) {
|
||||
flushBuf()
|
||||
@@ -158,21 +171,25 @@ fun Sink.buffered(size: Int = 8192): Sink {
|
||||
n += len
|
||||
}
|
||||
|
||||
/** the byte [b] gathered */
|
||||
override fun write(b: Int) {
|
||||
if (n == size) flushBuf()
|
||||
buf[n++] = b.toByte()
|
||||
}
|
||||
|
||||
/** what is gathered written to the sink underneath */
|
||||
private fun flushBuf() {
|
||||
if (n > 0) to.write(buf, 0, n)
|
||||
n = 0
|
||||
}
|
||||
|
||||
/** what is gathered written, and the sink underneath flushed */
|
||||
override fun flush() {
|
||||
flushBuf()
|
||||
to.flush()
|
||||
}
|
||||
|
||||
/** flushed, and the sink underneath closed */
|
||||
override fun close() {
|
||||
flush()
|
||||
to.close()
|
||||
|
||||
@@ -14,6 +14,7 @@ object Md5 {
|
||||
(kotlin.math.abs(kotlin.math.sin((i + 1).toDouble())) * 4294967296.0).toLong().toInt()
|
||||
}
|
||||
|
||||
/** the 16-byte MD5 digest of [data] */
|
||||
fun digest(data: ByteArray): ByteArray {
|
||||
val bitLen = data.size.toLong() * 8
|
||||
val padded = ByteArray(((data.size + 8) / 64 + 1) * 64)
|
||||
|
||||
@@ -36,6 +36,7 @@ class Timer {
|
||||
f()
|
||||
}
|
||||
|
||||
/** [f] as soon as the jobs before it are done */
|
||||
fun execute(f: () -> Unit): Job = schedule(0, f)
|
||||
|
||||
/** nothing more run */
|
||||
|
||||
@@ -26,9 +26,11 @@ fun background(@Suppress("UNUSED_PARAMETER") name: String, f: () -> Unit): Job =
|
||||
/** waited for until counted down, once (the JVM's CountDownLatch(1)) */
|
||||
class Latch {
|
||||
private val done = CompletableDeferred<Unit>()
|
||||
/** counted down: every await() returns */
|
||||
fun countDown() {
|
||||
done.complete(Unit)
|
||||
}
|
||||
/** waited for until counted down */
|
||||
fun await() = runBlocking { done.await() }
|
||||
|
||||
/** waited for up to [ms]: whether it was counted down */
|
||||
|
||||
@@ -58,11 +58,13 @@ class DialUpJob(out: DteOut, log: LogOut, changed: Changed) : DteJob(out, log, c
|
||||
@Volatile private var ppp: Ppp? = null
|
||||
@Volatile private var stopping = false
|
||||
|
||||
/** the state changed by [f], and said so */
|
||||
private fun set(f: (State) -> State) {
|
||||
state = f(state)
|
||||
changed()
|
||||
}
|
||||
|
||||
/** the modem's octets: to PPP once it runs, else to the AT commands' reader */
|
||||
override fun feed(latin1: String) {
|
||||
// (the AT commands' answers until CONNECT, then PPP's)
|
||||
val p = ppp
|
||||
@@ -105,6 +107,7 @@ class DialUpJob(out: DteOut, log: LogOut, changed: Changed) : DteJob(out, log, c
|
||||
user = user,
|
||||
password = password,
|
||||
events = object : Ppp.Events {
|
||||
/** PPP has an address: the tunnel brought up with it (PPP stopped if it can't be) */
|
||||
override fun up(config: Ppp.IpConfig) {
|
||||
val address = config.address.dotted
|
||||
val dns = config.dns.map { it.dotted }
|
||||
@@ -117,13 +120,16 @@ class DialUpJob(out: DteOut, log: LogOut, changed: Changed) : DteJob(out, log, c
|
||||
set { it.copy(phase = "", address = address, dns = dns, since = monotonicMs()) }
|
||||
}
|
||||
|
||||
/** a packet from the link, to the phone's tunnel */
|
||||
override fun ip(packet: ByteArray) = tunnel.packet(packet)
|
||||
|
||||
/** PPP down: its [reason] kept (unless there was one already) and the wait ended */
|
||||
override fun down(reason: String) {
|
||||
if (why == null) why = reason
|
||||
done.countDown()
|
||||
}
|
||||
|
||||
/** PPP's [line], to the job's log */
|
||||
override fun log(line: String) = this@DialUpJob.log("ppp: $line")
|
||||
},
|
||||
)
|
||||
@@ -168,6 +174,7 @@ class DialUpJob(out: DteOut, log: LogOut, changed: Changed) : DteJob(out, log, c
|
||||
/** the carrier gone (the modem on hook, or stopped): the link down */
|
||||
fun lineDropped() = stop("the line dropped")
|
||||
|
||||
/** the link stopped with [why] (once): PPP if it runs, else the dialling cancelled */
|
||||
private fun stop(why: String) {
|
||||
if (stopping) return
|
||||
stopping = true
|
||||
|
||||
@@ -17,22 +17,27 @@ import kotlin.concurrent.Volatile
|
||||
|
||||
/** octets to the modem: false once it has gone */
|
||||
fun interface DteOut {
|
||||
/** [latin1]'s octets to the modem: false once it has gone */
|
||||
fun write(latin1: String): Boolean
|
||||
}
|
||||
|
||||
/** a line for the log */
|
||||
fun interface LogOut {
|
||||
/** [line] logged */
|
||||
fun log(line: String)
|
||||
}
|
||||
|
||||
/** the job's state changed (read it); on the job's thread */
|
||||
fun interface Changed {
|
||||
/** the job's state changed */
|
||||
fun changed()
|
||||
}
|
||||
|
||||
/** octets as Latin-1 text and back, for Swift */
|
||||
object Latin1 {
|
||||
/** [s]'s characters as octets, one each */
|
||||
fun bytes(s: String): ByteArray = ByteArray(s.length) { s[it].code.toByte() }
|
||||
/** [b]'s octets as characters, one each */
|
||||
fun string(b: ByteArray): String = latin1String(b, 0, b.size)
|
||||
}
|
||||
|
||||
@@ -62,8 +67,10 @@ abstract class DteJob(private val out: DteOut, protected val logOut: LogOut, pri
|
||||
}
|
||||
}
|
||||
|
||||
/** the job's state changed, said to [changed] */
|
||||
protected fun changed() = changed.changed()
|
||||
|
||||
/** [line] to the log */
|
||||
protected fun log(line: String) = logOut.log(line)
|
||||
|
||||
/** the modem's answer to ATD, as the user reads it */
|
||||
|
||||
@@ -36,6 +36,7 @@ class FaxJob(out: DteOut, log: LogOut, changed: Changed) : DteJob(out, log, chan
|
||||
@Volatile var state: State? = null
|
||||
private set
|
||||
|
||||
/** the progress shown as [p], and said so */
|
||||
private fun update(p: FaxProgress) {
|
||||
state = state?.copy(progress = p)
|
||||
changed()
|
||||
@@ -73,6 +74,7 @@ class FaxJob(out: DteOut, log: LogOut, changed: Changed) : DteJob(out, log, chan
|
||||
/** the call stopped (hung up) */
|
||||
fun cancel() = io.cancel("cancelled")
|
||||
|
||||
/** [pages] written into [into] as a PDF named [name]: the name it got (abandoned if it fails) */
|
||||
private fun save(into: Incoming, name: String, pages: List<FaxPage>): String {
|
||||
val (out, actual) = into.create(name, -1)
|
||||
try {
|
||||
@@ -85,6 +87,7 @@ class FaxJob(out: DteOut, log: LogOut, changed: Changed) : DteJob(out, log, chan
|
||||
return actual
|
||||
}
|
||||
|
||||
/** the fax call run in the background: the modem put in fax mode, [body] run, the call hung up and the result kept */
|
||||
private fun start(sending: Boolean, number: String, maxBps: Int, body: (Class1, List<T30.Rate>) -> Pair<FaxProgress, String>) {
|
||||
state = State(sending, FaxProgress("Starting"), number = number)
|
||||
changed()
|
||||
|
||||
@@ -34,6 +34,7 @@ class TransferJob(protocolName: String, sending: Boolean, out: DteOut, log: LogO
|
||||
@Volatile var state: TransferState = transfer.state
|
||||
private set
|
||||
|
||||
/** the modem's octets, to the transfer */
|
||||
override fun feed(latin1: String) {
|
||||
if (latin1.isNotEmpty()) transfer.io.feed(Latin1.bytes(latin1))
|
||||
}
|
||||
@@ -44,12 +45,14 @@ class TransferJob(protocolName: String, sending: Boolean, out: DteOut, log: LogO
|
||||
/** [files] sent ([files]' first only, for XMODEM) */
|
||||
fun send(files: List<Outgoing>) = transfer.send(files)
|
||||
|
||||
/** the transfer stopped */
|
||||
fun cancel() = transfer.cancel()
|
||||
|
||||
companion object {
|
||||
/** the protocols' names, and what each is called */
|
||||
val protocols: List<String> = Protocol.entries.map { it.name }
|
||||
|
||||
/** what the protocol [protocolName] is called */
|
||||
fun label(protocolName: String): String = Protocol.valueOf(protocolName).label
|
||||
|
||||
/** whether it sends more than one file */
|
||||
|
||||
@@ -88,6 +88,7 @@ class PeerLine(
|
||||
private var failures = 0
|
||||
private var blockedUntil = 0L
|
||||
|
||||
/** the line on: listening for calls if [listen], ready for the modem's */
|
||||
fun start(listen: Boolean) {
|
||||
running = true
|
||||
listening = false
|
||||
@@ -98,6 +99,7 @@ class PeerLine(
|
||||
_state.value = State.Ready(listening)
|
||||
}
|
||||
|
||||
/** the line off: its calls ended, the transport closed */
|
||||
fun stop() {
|
||||
running = false
|
||||
val calls = synchronized(lock) { listOfNotNull(pending, call) }
|
||||
@@ -130,6 +132,7 @@ class PeerLine(
|
||||
val dialled = Latch()
|
||||
@kotlin.concurrent.Volatile var ringing = false
|
||||
|
||||
/** the call over (once): its connection and line closed, a ringing call's RING cancelled, the line ready again */
|
||||
fun end(why: String) {
|
||||
if (!ended.compareAndSet(false, true)) return
|
||||
log("call ${if (caller) "to" else "from"} $who over: $why")
|
||||
@@ -252,6 +255,7 @@ class PeerLine(
|
||||
|
||||
/** the tone at sample [n]: dial tone (350 + 440 Hz), quiet, ringback (440 + 480 Hz, 2 s in 6) once ringing */
|
||||
private var ringFrom = -1L
|
||||
/** that tone's sample [n], as above */
|
||||
private fun tone(n: Long): Short {
|
||||
val t = n.toDouble() / RATE
|
||||
val a = when {
|
||||
@@ -265,6 +269,7 @@ class PeerLine(
|
||||
return a.toInt().toShort()
|
||||
}
|
||||
|
||||
/** two sines of [f1] and [f2] Hz added, at [t] seconds, [TONE] loud */
|
||||
private fun sin2(f1: Double, f2: Double, t: Double) =
|
||||
TONE * (kotlin.math.sin(2 * kotlin.math.PI * f1 * t) + kotlin.math.sin(2 * kotlin.math.PI * f2 * t))
|
||||
}
|
||||
@@ -374,6 +379,7 @@ class PeerLine(
|
||||
background("peer") { dialOut(c, dial) }
|
||||
}
|
||||
|
||||
/** our call placed: the tones played, the other phone connected and rung (with our PIN if it asks), then the call answered or failed */
|
||||
private fun dialOut(c: Call, dial: String) {
|
||||
// the dial tone and the dialling first, as an exchange has them
|
||||
c.feedTones()
|
||||
@@ -462,8 +468,10 @@ class PeerLine(
|
||||
fun pinProof(nonce: String, pin: String): String =
|
||||
Md5.digest("DMODEM/1:$nonce:$pin".encodeToByteArray()).toHex()
|
||||
|
||||
/** the bytes in lower-case hex */
|
||||
private fun ByteArray.toHex() = joinToString("") { (it.toInt() and 0xff).toString(16).padStart(2, '0') }
|
||||
|
||||
/** whether [a] and [b] are equal, in a time that doesn't tell where they differ */
|
||||
private fun constantTimeEquals(a: String, b: String): Boolean {
|
||||
if (a.length != b.length) return false
|
||||
var d = 0
|
||||
|
||||
@@ -125,10 +125,12 @@ class ChatScript(private val script: String, private val user: String, private v
|
||||
}
|
||||
}
|
||||
|
||||
/** [tok] sent, its escapes undone, waiting where its \d and \p say (a CR after unless \c) */
|
||||
private fun send(io: TransferIo, tok: String, log: (String) -> Unit) {
|
||||
val (text, cr) = unescape(tok, true)
|
||||
log("send \"" + (if (tok.contains("\\P")) "(the password)" else text.replace("\r", "\\r")) + "\"")
|
||||
val sb = StringBuilder()
|
||||
/** what is gathered sent */
|
||||
fun flush() {
|
||||
if (sb.isNotEmpty()) io.write(sb.toString().let { t -> ByteArray(t.length) { t[it].code.toByte() } })
|
||||
sb.setLength(0)
|
||||
|
||||
@@ -20,6 +20,7 @@ object Hdlc {
|
||||
v
|
||||
}
|
||||
|
||||
/** the FCS-16 of [len] octets at [off], from [start] (not complemented) */
|
||||
fun fcs(data: ByteArray, off: Int = 0, len: Int = data.size - off, start: Int = 0xffff): Int {
|
||||
var f = start
|
||||
for (i in off until off + len) f = (f ushr 8) xor FCS_TABLE[(f xor data[i].toInt()) and 0xff]
|
||||
@@ -34,6 +35,7 @@ object Hdlc {
|
||||
val f = fcs(frame) xor 0xffff
|
||||
val o = Bytes(frame.size + frame.size / 4 + 8)
|
||||
o.write(FLAG)
|
||||
/** [b] to the frame, escaped if it is a flag, the escape or a control character [accm] asks for */
|
||||
fun put(b: Int) {
|
||||
if (b == FLAG || b == ESC || (b < 0x20 && (accm ushr b) and 1 != 0)) {
|
||||
o.write(ESC)
|
||||
@@ -56,6 +58,7 @@ object Hdlc {
|
||||
var bad = 0
|
||||
private set
|
||||
|
||||
/** [len] octets of [data] from [off] decoded, each frame they end passed on */
|
||||
fun feed(data: ByteArray, off: Int = 0, len: Int = data.size - off) {
|
||||
for (i in off until off + len) {
|
||||
val c = data[i].toInt() and 0xff
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.neodesktop.dmodem.io.*
|
||||
|
||||
/** IPv4 and UDP packets, as far as the link's checks need them. */
|
||||
object Ip {
|
||||
/** the Internet checksum (RFC 1071) of [len] bytes at [off], [start] added in */
|
||||
fun checksum(b: ByteArray, off: Int, len: Int, start: Long = 0): Int {
|
||||
var s = start
|
||||
var i = off
|
||||
|
||||
@@ -35,9 +35,13 @@ class Ppp(
|
||||
data class IpConfig(val address: Inet4, val peer: Inet4?, val dns: List<Inet4>, val mtu: Int)
|
||||
|
||||
interface Events {
|
||||
/** the link open with [config]'s address */
|
||||
fun up(config: IpConfig)
|
||||
/** an IPv4 packet from the link */
|
||||
fun ip(packet: ByteArray)
|
||||
/** the link down, and why */
|
||||
fun down(reason: String)
|
||||
/** a line for the log (by default, none kept) */
|
||||
fun log(line: String) {}
|
||||
}
|
||||
|
||||
@@ -98,6 +102,7 @@ class Ppp(
|
||||
@kotlin.concurrent.Volatile var bytesOut = 0L
|
||||
private set
|
||||
|
||||
/** [s] to the events' log */
|
||||
private fun log(s: String) = events.log(s)
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -132,6 +137,7 @@ class Ppp(
|
||||
timer.schedule(if (phase == Phase.TERMINATE) 500 else 0) { down(reason) }
|
||||
}
|
||||
|
||||
/** the link dead (once): its retries cancelled, [Events.down] told, the timer shut down */
|
||||
private fun down(reason: String) {
|
||||
synchronized(lock) {
|
||||
if (phase == Phase.DEAD) return
|
||||
@@ -148,6 +154,7 @@ class Ppp(
|
||||
// ------------------------------------------------------------------
|
||||
// frames
|
||||
|
||||
/** [info] sent in a frame of protocol [proto] (LCP's with every control character escaped) */
|
||||
private fun out(proto: Int, info: ByteArray) {
|
||||
val f = ByteArray(4 + info.size)
|
||||
f[0] = 0xff.toByte()
|
||||
@@ -159,6 +166,7 @@ class Ppp(
|
||||
send(Hdlc.encode(f, if (proto == PROTO_LCP) -1 else sendAccm))
|
||||
}
|
||||
|
||||
/** an LCP-style packet: [code], [id], its length, [data] */
|
||||
private fun packet(code: Int, id: Int, data: ByteArray): ByteArray {
|
||||
val p = ByteArray(4 + data.size)
|
||||
p[0] = code.toByte()
|
||||
@@ -169,6 +177,7 @@ class Ppp(
|
||||
return p
|
||||
}
|
||||
|
||||
/** a frame from the line, by its protocol to LCP, PAP, CHAP, IPCP or the tunnel; others rejected once past LCP */
|
||||
private fun frame(f: ByteArray) {
|
||||
// address and control (or not, with ACFC), the protocol (one octet with PFC)
|
||||
var i = 0
|
||||
@@ -213,22 +222,28 @@ class Ppp(
|
||||
return out
|
||||
}
|
||||
|
||||
/** a packet's length field (0 if too short to have one) */
|
||||
private fun len(p: ByteArray) = if (p.size >= 4) ((p[2].toInt() and 0xff) shl 8) or (p[3].toInt() and 0xff) else 0
|
||||
|
||||
/** (type, data) options as a packet's option bytes */
|
||||
private fun opts(list: List<Pair<Int, ByteArray>>): ByteArray {
|
||||
val o = Bytes()
|
||||
for ((t, d) in list) { o.write(t); o.write(d.size + 2); o.write(d) }
|
||||
return o.toByteArray()
|
||||
}
|
||||
|
||||
/** [v] as four octets, big-endian */
|
||||
private fun int32(v: Int) = byteArrayOf((v ushr 24).toByte(), (v ushr 16).toByte(), (v ushr 8).toByte(), v.toByte())
|
||||
/** the big-endian int of [d]'s first four octets */
|
||||
private fun int32(d: ByteArray) = ((d[0].toInt() and 0xff) shl 24) or ((d[1].toInt() and 0xff) shl 16) or
|
||||
((d[2].toInt() and 0xff) shl 8) or (d[3].toInt() and 0xff)
|
||||
/** the big-endian int of [d]'s first two octets */
|
||||
private fun int16(d: ByteArray) = ((d[0].toInt() and 0xff) shl 8) or (d[1].toInt() and 0xff)
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// LCP
|
||||
|
||||
/** our LCP Configure-Request (MRU, ACCM, magic number as still asked) out, retried until acked or given up */
|
||||
private fun sendLcpConfReq() {
|
||||
val o = ArrayList<Pair<Int, ByteArray>>()
|
||||
if (lcpMru != 1500) o.add(1 to byteArrayOf((lcpMru ushr 8).toByte(), lcpMru.toByte()))
|
||||
@@ -246,6 +261,7 @@ class Ppp(
|
||||
}
|
||||
}
|
||||
|
||||
/** an LCP packet: the peer's request Ack'd, Nak'd or rejected, our own request's answer taken, terminate and echo answered */
|
||||
private fun lcp(p: ByteArray) {
|
||||
if (p.size < 4) return
|
||||
val code = p[0].toInt() and 0xff
|
||||
@@ -325,6 +341,7 @@ class Ppp(
|
||||
}
|
||||
}
|
||||
|
||||
/** LCP negotiated again from the start (the peer renegotiating), IPCP with it */
|
||||
private fun restartLcp() {
|
||||
log("LCP again")
|
||||
phase = Phase.ESTABLISH
|
||||
@@ -337,6 +354,7 @@ class Ppp(
|
||||
sendLcpConfReq()
|
||||
}
|
||||
|
||||
/** both sides' LCP options acked: on to PAP, CHAP's challenge, or IPCP if no login is asked */
|
||||
private fun lcpMaybeUp() {
|
||||
if (!(lcpOurAcked && lcpTheirAcked) || phase != Phase.ESTABLISH) return
|
||||
log("LCP up (mru $peerMru, accm ${hex(sendAccm, 8)}, auth ${hex(authProto, 4)})")
|
||||
@@ -351,6 +369,7 @@ class Ppp(
|
||||
// ------------------------------------------------------------------
|
||||
// authentication
|
||||
|
||||
/** our PAP login out, retried until answered or given up */
|
||||
private fun sendPap() {
|
||||
val u = user.encodeToByteArray()
|
||||
val pw = password.encodeToByteArray()
|
||||
@@ -365,10 +384,12 @@ class Ppp(
|
||||
}
|
||||
}
|
||||
|
||||
/** the link stopped with [why], off the lock (on the timer's thread) */
|
||||
private fun stopLocked(why: String) {
|
||||
timer.execute { stop(why) }
|
||||
}
|
||||
|
||||
/** a PAP answer: on to IPCP if logged in, else the link stopped with the server's message */
|
||||
private fun pap(p: ByteArray) {
|
||||
if (p.size < 4 || phase != Phase.AUTHENTICATE) return
|
||||
when (p[0].toInt()) {
|
||||
@@ -381,6 +402,7 @@ class Ppp(
|
||||
}
|
||||
}
|
||||
|
||||
/** a CHAP packet: a challenge answered with MD5 of the id, the password and it; success on to IPCP; failure stops the link */
|
||||
private fun chap(p: ByteArray) {
|
||||
if (p.size < 4) return
|
||||
val id = p[1].toInt() and 0xff
|
||||
@@ -401,12 +423,14 @@ class Ppp(
|
||||
// ------------------------------------------------------------------
|
||||
// IPCP
|
||||
|
||||
/** IPCP begun: the network phase, our request out */
|
||||
private fun startIpcp() {
|
||||
phase = Phase.NETWORK
|
||||
ipcpRetries = 0
|
||||
sendIpcpConfReq()
|
||||
}
|
||||
|
||||
/** our IPCP Configure-Request (our address, the DNS servers still asked) out, retried until acked or given up */
|
||||
private fun sendIpcpConfReq() {
|
||||
val o = ArrayList<Pair<Int, ByteArray>>()
|
||||
o.add(3 to ourAddr)
|
||||
@@ -423,6 +447,7 @@ class Ppp(
|
||||
}
|
||||
}
|
||||
|
||||
/** an IPCP packet: the peer's request answered (as a server, or taking its address), the address and DNS from its Nak, our request's answer taken */
|
||||
private fun ipcp(p: ByteArray) {
|
||||
if (p.size < 4) return
|
||||
if (phase.ordinal < Phase.NETWORK.ordinal || phase == Phase.TERMINATE) {
|
||||
@@ -488,6 +513,7 @@ class Ppp(
|
||||
ipcpMaybeUp()
|
||||
}
|
||||
|
||||
/** both sides' IPCP acked: the link open, its address, DNS and MTU to [Events.up] (stopped if no address came) */
|
||||
private fun ipcpMaybeUp() {
|
||||
if (!(ipcpOurAcked && ipcpTheirAcked) || phase != Phase.NETWORK) return
|
||||
if (ourAddr.all { it.toInt() == 0 }) { stopLocked("no address came"); return }
|
||||
|
||||
@@ -43,6 +43,7 @@ object Cp437 {
|
||||
HIGH.mapIndexed { i, c -> c.code to (0x80 + i) }.toMap()
|
||||
}
|
||||
|
||||
/** a CP437 octet as its code point */
|
||||
fun decode(b: Int): Int = if (b < 0x80) b else HIGH[b - 0x80].code
|
||||
|
||||
/** a code point as its CP437 octet: '?' if it has none */
|
||||
@@ -52,6 +53,7 @@ object Cp437 {
|
||||
/** octets to code points, in a set, across reads */
|
||||
class TermDecoder(var charset: TermCharset) {
|
||||
fun interface Sink {
|
||||
/** a code point decoded */
|
||||
fun codePoint(cp: Int)
|
||||
}
|
||||
|
||||
@@ -59,6 +61,7 @@ class TermDecoder(var charset: TermCharset) {
|
||||
private var cp = 0
|
||||
private var min = 0
|
||||
|
||||
/** a UTF-8 sequence half read dropped */
|
||||
fun reset() {
|
||||
need = 0
|
||||
}
|
||||
@@ -68,6 +71,7 @@ class TermDecoder(var charset: TermCharset) {
|
||||
for (i in 0 until length) feed(data[i].toInt() and 0xff, out)
|
||||
}
|
||||
|
||||
/** one octet decoded in the charset, its code point (if it completes one) to [out] */
|
||||
fun feed(b: Int, out: Sink) {
|
||||
when (charset) {
|
||||
TermCharset.LATIN1 -> out.codePoint(b)
|
||||
@@ -76,6 +80,7 @@ class TermDecoder(var charset: TermCharset) {
|
||||
}
|
||||
}
|
||||
|
||||
/** one UTF-8 octet: a code point to [out] when its sequence completes, U+FFFD for a bad or overlong one */
|
||||
private fun utf8(b: Int, out: Sink) {
|
||||
if (need > 0) {
|
||||
if (b and 0xc0 == 0x80) {
|
||||
|
||||
@@ -32,14 +32,18 @@ class KeyEncoder {
|
||||
private fun mod(shift: Boolean, alt: Boolean, ctrl: Boolean): Int =
|
||||
1 + (if (shift) 1 else 0) + (if (alt) 2 else 0) + (if (ctrl) 4 else 0)
|
||||
|
||||
/** what [k] sends, with its modifiers ([appCursor]: the cursor keys in application mode) */
|
||||
fun key(k: Key, appCursor: Boolean, shift: Boolean = false, alt: Boolean = false, ctrl: Boolean = false): String {
|
||||
val m = mod(shift, alt, ctrl)
|
||||
/** a cursor key's: CSI with the modifiers, SS3 in application mode, else CSI */
|
||||
fun cursor(c: Char) = when {
|
||||
m > 1 -> "\u001b[1;$m$c"
|
||||
appCursor -> "\u001bO$c"
|
||||
else -> "\u001b[$c"
|
||||
}
|
||||
/** a CSI n ~ key's, with the modifiers */
|
||||
fun tilde(n: Int) = if (m > 1) "\u001b[$n;$m~" else "\u001b[$n~"
|
||||
/** an SS3 function key's (CSI 1;m with modifiers) */
|
||||
fun ss3(c: Char) = if (m > 1) "\u001b[1;$m$c" else "\u001bO$c"
|
||||
val prefix = if (alt && k in setOf(Key.TAB, Key.ENTER, Key.BACKSPACE, Key.ESCAPE)) "\u001b" else ""
|
||||
return when (k) {
|
||||
@@ -115,8 +119,10 @@ object UrlFinder {
|
||||
return null
|
||||
}
|
||||
|
||||
/** every link in [text], trailing punctuation dropped */
|
||||
fun all(text: String): List<String> = URL.findAll(text).map { trim(it.value) }.toList()
|
||||
|
||||
/** [u] without trailing punctuation, nor closing brackets it didn't open */
|
||||
private fun trim(u: String): String {
|
||||
var s = u.trimEnd('.', ',', ';', ':', '!', '?', '\'', '"')
|
||||
// a closing bracket the link didn't open
|
||||
|
||||
@@ -34,17 +34,24 @@ object Style {
|
||||
|
||||
val NORMAL: Long = of(DEFAULT_FG, DEFAULT_BG, 0)
|
||||
|
||||
/** the look of colours [fg] and [bg] with attributes [attrs] */
|
||||
fun of(fg: Int, bg: Int, attrs: Int): Long =
|
||||
(fg.toLong() and COLOR_MASK) or
|
||||
((bg.toLong() and COLOR_MASK) shl 25) or
|
||||
(attrs.toLong() shl 50)
|
||||
|
||||
/** a look's foreground colour */
|
||||
fun fg(s: Long): Int = (s and COLOR_MASK).toInt()
|
||||
/** a look's background colour */
|
||||
fun bg(s: Long): Int = ((s ushr 25) and COLOR_MASK).toInt()
|
||||
/** a look's attributes */
|
||||
fun attrs(s: Long): Int = (s ushr 50).toInt()
|
||||
|
||||
/** [s] with foreground [fg] */
|
||||
fun withFg(s: Long, fg: Int) = of(fg, bg(s), attrs(s))
|
||||
/** [s] with background [bg] */
|
||||
fun withBg(s: Long, bg: Int) = of(fg(s), bg, attrs(s))
|
||||
/** [s] with attributes [a] */
|
||||
fun withAttrs(s: Long, a: Int) = of(fg(s), bg(s), a)
|
||||
|
||||
/** the look of erased cells: only the background stays (xterm's BCE) */
|
||||
@@ -69,6 +76,7 @@ class CellExtra(
|
||||
var image: ImageTile? = null,
|
||||
var link: String? = null,
|
||||
) {
|
||||
/** a copy of its own (the combining marks copied, the tile and link shared) */
|
||||
fun copy() = CellExtra(combining?.copyOf(), image, link)
|
||||
val isEmpty get() = combining == null && image == null && link == null
|
||||
}
|
||||
@@ -89,6 +97,7 @@ class Line(cols: Int, style: Long = Style.NORMAL) {
|
||||
|
||||
val cols: Int get() = chars.size
|
||||
|
||||
/** cell [i]'s extras, or null if it has none */
|
||||
fun extra(i: Int): CellExtra? = extras?.getOrNull(i)
|
||||
|
||||
/** the cell's extras, made if it has none */
|
||||
@@ -104,6 +113,7 @@ class Line(cols: Int, style: Long = Style.NORMAL) {
|
||||
extras?.let { it[i] = null }
|
||||
}
|
||||
|
||||
/** cells [from] until [to] blanked in [style], their extras gone */
|
||||
fun clear(from: Int, to: Int, style: Long) {
|
||||
val f = from.coerceAtLeast(0)
|
||||
val t = to.coerceAtMost(cols)
|
||||
@@ -134,6 +144,7 @@ class Line(cols: Int, style: Long = Style.NORMAL) {
|
||||
clear(cols - k, cols, style)
|
||||
}
|
||||
|
||||
/** [n] columns wide: cut or padded with blank cells (a wide character cut at the edge gone) */
|
||||
fun resize(n: Int) {
|
||||
if (n == cols) return
|
||||
val c = IntArray(n)
|
||||
@@ -147,6 +158,7 @@ class Line(cols: Int, style: Long = Style.NORMAL) {
|
||||
if (n > 0 && chars[n - 1] > 0 && Wcwidth.width(chars[n - 1]) == 2) chars[n - 1] = 0
|
||||
}
|
||||
|
||||
/** [o]'s cells (as many as fit), extras and wrap copied into this one */
|
||||
fun copyFrom(o: Line) {
|
||||
val n = minOf(cols, o.cols)
|
||||
o.chars.copyInto(chars, 0, 0, n)
|
||||
|
||||
@@ -39,6 +39,7 @@ class Sixel(
|
||||
private val params = IntArray(5)
|
||||
private var nParams = 0
|
||||
|
||||
/** one code point of the image's data: a command's parameters gathered, else a sixel, a command begun, a carriage return or new line */
|
||||
fun feed(cp: Int) {
|
||||
if (command != 0) {
|
||||
when (cp) {
|
||||
@@ -64,12 +65,14 @@ class Sixel(
|
||||
}
|
||||
}
|
||||
|
||||
/** command [c] (#, ! or ") begun, its parameters cleared */
|
||||
private fun startCommand(c: Int) {
|
||||
command = c
|
||||
nParams = 0
|
||||
params.fill(0)
|
||||
}
|
||||
|
||||
/** the command read applied: a repeat count, a colour register set or chosen, or the raster attributes' size */
|
||||
private fun endCommand() {
|
||||
when (command.toChar()) {
|
||||
'!' -> repeat = params[0].coerceAtLeast(1)
|
||||
@@ -95,6 +98,7 @@ class Sixel(
|
||||
command = 0
|
||||
}
|
||||
|
||||
/** a sixel's six pixels drawn in the colour at x (repeated as !Pn said), x past them */
|
||||
private fun sixel(bits: Int) {
|
||||
val n = repeat
|
||||
repeat = 1
|
||||
@@ -146,8 +150,10 @@ class Sixel(
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** a percentage as 0-255 */
|
||||
private fun pct(v: Int) = (v.coerceIn(0, 100) * 255 + 50) / 100
|
||||
|
||||
/** opaque ARGB of [r], [g], [b] */
|
||||
private fun rgb(r: Int, g: Int, b: Int) = (0xff shl 24) or (r shl 16) or (g shl 8) or b
|
||||
|
||||
/** DEC's HLS: hue in degrees with blue at 0 (red at 120), lightness and saturation in percent */
|
||||
@@ -162,6 +168,7 @@ class Sixel(
|
||||
}
|
||||
val q = if (l < 0.5) l * (1 + s) else l + s - l * s
|
||||
val p = 2 * l - q
|
||||
/** one channel (0-255) from the hue fraction [t0], HSL's way */
|
||||
fun hue(t0: Double): Int {
|
||||
var t = t0
|
||||
if (t < 0) t += 1.0
|
||||
|
||||
@@ -24,6 +24,7 @@ class TerminalBridge(cols: Int, rows: Int) {
|
||||
|
||||
init {
|
||||
emulator.listener = object : TerminalEmulator.Listener {
|
||||
/** the remote's title kept */
|
||||
override fun onTitle(title: String) { this@TerminalBridge.title = title }
|
||||
}
|
||||
}
|
||||
@@ -54,6 +55,7 @@ class TerminalBridge(cols: Int, rows: Int) {
|
||||
val background: Int get() = look.theme.bgArgb
|
||||
val cursorColor: Int get() = look.theme.cursorArgb
|
||||
|
||||
/** the screen made [cols] x [rows] */
|
||||
fun resize(cols: Int, rows: Int) = emulator.resize(cols, rows)
|
||||
|
||||
/** the theme ([TermTheme.ALL]'s ids), bold as bright, and the character set (UTF8, CP437, LATIN1) */
|
||||
@@ -94,6 +96,7 @@ class TerminalBridge(cols: Int, rows: Int) {
|
||||
/** the screen's text from (row, col) to (row2, col2), for copying */
|
||||
fun text(row: Int, col: Int, row2: Int, col2: Int): String = emulator.text(row, col, row2, col2)
|
||||
|
||||
/** [s] in the character set, as Latin-1 text (one character an octet) */
|
||||
private fun octets(s: String): String {
|
||||
val b = emulator.decoder.charset.encode(s)
|
||||
return CharArray(b.size) { (b[it].toInt() and 0xff).toChar() }.concatToString()
|
||||
|
||||
@@ -25,7 +25,9 @@ class TerminalEmulator(
|
||||
private val output: (ByteArray) -> Unit = {},
|
||||
) {
|
||||
interface Listener {
|
||||
/** OSC 0/2: the remote set the window's title */
|
||||
fun onTitle(title: String) {}
|
||||
/** BEL: the remote rang the bell */
|
||||
fun onBell() {}
|
||||
/** OSC 52: the remote puts text on the clipboard */
|
||||
fun onClipboard(text: String) {}
|
||||
@@ -99,6 +101,7 @@ class TerminalEmulator(
|
||||
var cellPixelHeight = 20
|
||||
private set
|
||||
|
||||
/** a cell's size in pixels as the view draws it (at least 1 each way) */
|
||||
fun setCellPixels(w: Int, h: Int) {
|
||||
cellPixelWidth = w.coerceAtLeast(1)
|
||||
cellPixelHeight = h.coerceAtLeast(1)
|
||||
@@ -186,6 +189,7 @@ class TerminalEmulator(
|
||||
// ------------------------------------------------------------------
|
||||
// the parser
|
||||
|
||||
/** one code point through the parser, by the state it is in (text, ESC, CSI, OSC, a string, a DCS) */
|
||||
private fun process(cp: Int) {
|
||||
when (state) {
|
||||
State.GROUND -> ground(cp)
|
||||
@@ -233,6 +237,7 @@ class TerminalEmulator(
|
||||
}
|
||||
}
|
||||
|
||||
/** a code point outside any sequence: a control, a C1 control as its ESC form, else printed */
|
||||
private fun ground(cp: Int) {
|
||||
if (cp < 0x20 || cp == 0x7f) {
|
||||
control(cp)
|
||||
@@ -255,6 +260,7 @@ class TerminalEmulator(
|
||||
print(cp)
|
||||
}
|
||||
|
||||
/** a C0 control: ENQ's answerback, the bell, BS, HT, LF/VT/FF, CR, SO/SI, CAN/SUB, ESC */
|
||||
private fun control(cp: Int) {
|
||||
when (cp) {
|
||||
0x05 -> if (answerback.isNotEmpty()) reply(answerback)
|
||||
@@ -270,6 +276,7 @@ class TerminalEmulator(
|
||||
}
|
||||
}
|
||||
|
||||
/** the character after ESC: a sequence begun, or its one-character command done */
|
||||
private fun esc(cp: Int) {
|
||||
state = State.GROUND
|
||||
when (cp.toChar()) {
|
||||
@@ -292,6 +299,7 @@ class TerminalEmulator(
|
||||
}
|
||||
}
|
||||
|
||||
/** the character after ESC and an intermediate: G0/G1's DEC graphics on or off, DECALN */
|
||||
private fun escInter(cp: Int) {
|
||||
state = State.GROUND
|
||||
val graphics = cp == '0'.code
|
||||
@@ -302,6 +310,7 @@ class TerminalEmulator(
|
||||
}
|
||||
}
|
||||
|
||||
/** a CSI begun: its parameters, private marker and intermediate cleared */
|
||||
private fun startCsi() {
|
||||
state = State.CSI
|
||||
nParams = 0
|
||||
@@ -312,6 +321,7 @@ class TerminalEmulator(
|
||||
colon.fill(false)
|
||||
}
|
||||
|
||||
/** a CSI's character: a parameter's digit, a separator, a marker or intermediate, or its final (dispatched) */
|
||||
private fun csi(cp: Int) {
|
||||
when (cp) {
|
||||
in '0'.code..'9'.code -> {
|
||||
@@ -341,9 +351,11 @@ class TerminalEmulator(
|
||||
}
|
||||
}
|
||||
|
||||
/** parameter [i], or [default] when it is missing or 0 */
|
||||
private fun p(i: Int, default: Int): Int =
|
||||
if (i < nParams && params[i] != 0) params[i] else default
|
||||
|
||||
/** a CSI ended by [final] carried out: DEC private modes and questions, DA2/DA3, DECSTR, DECSCUSR, then the ANSI ones */
|
||||
private fun dispatchCsi(final: Int) {
|
||||
val c = final.toChar()
|
||||
if (privateMarker == '?'.code) {
|
||||
@@ -431,6 +443,7 @@ class TerminalEmulator(
|
||||
}
|
||||
}
|
||||
|
||||
/** DEC private mode [m] set or reset (DECSET/DECRST) */
|
||||
private fun decMode(m: Int, on: Boolean) {
|
||||
when (m) {
|
||||
1 -> appCursorKeys = on
|
||||
@@ -459,6 +472,7 @@ class TerminalEmulator(
|
||||
|
||||
/** DECRQM's answer for a DEC mode: 1 set, 2 reset, 0 not one known */
|
||||
private fun decModeState(m: Int): Int {
|
||||
/** DECRQM's 1 for set, 2 for reset */
|
||||
fun b(v: Boolean) = if (v) 1 else 2
|
||||
return when (m) {
|
||||
1 -> b(appCursorKeys)
|
||||
@@ -482,6 +496,7 @@ class TerminalEmulator(
|
||||
}
|
||||
}
|
||||
|
||||
/** DECRQM's answer for an ANSI mode (IRM 4, LNM 20): 1 set, 2 reset, 0 not one known */
|
||||
private fun ansiModeState(m: Int): Int = when (m) {
|
||||
4 -> if (insertMode) 1 else 2
|
||||
20 -> if (newlineMode) 1 else 2
|
||||
@@ -552,6 +567,7 @@ class TerminalEmulator(
|
||||
fun focusReport(focused: Boolean): ByteArray? =
|
||||
if (focusEvents) (if (focused) "\u001b[I" else "\u001b[O").encodeToByteArray() else null
|
||||
|
||||
/** ANSI mode [m] set or reset: insert (4), newline (20) */
|
||||
private fun ansiMode(m: Int, on: Boolean) {
|
||||
when (m) {
|
||||
4 -> insertMode = on
|
||||
@@ -559,6 +575,7 @@ class TerminalEmulator(
|
||||
}
|
||||
}
|
||||
|
||||
/** SGR: the CSI's parameters applied to the current rendition (none: back to normal) */
|
||||
private fun sgr() {
|
||||
if (nParams == 0) {
|
||||
style = Style.NORMAL
|
||||
@@ -644,6 +661,7 @@ class TerminalEmulator(
|
||||
style = s
|
||||
}
|
||||
|
||||
/** an OSC ended: the title, colours set, asked or reset, the clipboard, a hyperlink */
|
||||
private fun osc() {
|
||||
val s = osc.toString()
|
||||
val semi = s.indexOf(';')
|
||||
@@ -695,6 +713,7 @@ class TerminalEmulator(
|
||||
private fun colorSpec(i: Int, spec: String, prefix: String) {
|
||||
if (spec == "?") {
|
||||
val c = colorOverrides[i].takeIf { it != -1 } ?: defaultColor(i)
|
||||
/** a colour channel (0-255) as X's four hex digits */
|
||||
fun h(v: Int) = (v * 0x101).toString(16).padStart(4, '0')
|
||||
val end = if (oscBel) "\u0007" else "\u001b\\"
|
||||
reply("\u001b]$prefix" + "rgb:${h((c shr 16) and 0xff)}/${h((c shr 8) and 0xff)}/${h(c and 0xff)}$end")
|
||||
@@ -703,6 +722,7 @@ class TerminalEmulator(
|
||||
parseColor(spec)?.let { colorOverrides[i] = it }
|
||||
}
|
||||
|
||||
/** [s] to the remote, as Latin-1 octets */
|
||||
private fun reply(s: String) {
|
||||
output(s.latin1())
|
||||
}
|
||||
@@ -710,6 +730,7 @@ class TerminalEmulator(
|
||||
// ------------------------------------------------------------------
|
||||
// DCS: sixel images, and requests (DECRQSS)
|
||||
|
||||
/** a DCS begun: its parameters read as a CSI's */
|
||||
private fun startDcs() {
|
||||
startCsi()
|
||||
state = State.DCS
|
||||
@@ -730,6 +751,7 @@ class TerminalEmulator(
|
||||
}
|
||||
}
|
||||
|
||||
/** a DCS's final [final]: a sixel image begun, or DECRQSS's or XTGETTCAP's text collected */
|
||||
private fun dcsStart(final: Int) {
|
||||
sixel = null
|
||||
dcsText = null
|
||||
@@ -749,16 +771,19 @@ class TerminalEmulator(
|
||||
}
|
||||
}
|
||||
|
||||
/** a DCS's data character: to the sixel image, or to the request's text */
|
||||
private fun dcsPut(cp: Int) {
|
||||
sixel?.let { it.feed(cp); return }
|
||||
dcsText?.let { if (it.length < 1024) it.appendCp(cp) }
|
||||
}
|
||||
|
||||
/** the DCS cancelled: its image or text dropped */
|
||||
private fun dcsAbort() {
|
||||
sixel = null
|
||||
dcsText = null
|
||||
}
|
||||
|
||||
/** the DCS ended: its sixel image placed, or its request answered */
|
||||
private fun dcsEnd() {
|
||||
sixel?.let { sx ->
|
||||
sixel = null
|
||||
@@ -797,6 +822,7 @@ class TerminalEmulator(
|
||||
if (a and Style.INVISIBLE != 0) sb.append(";8")
|
||||
if (a and Style.STRIKE != 0) sb.append(";9")
|
||||
if (a and Style.OVERLINE != 0) sb.append(";53")
|
||||
/** colour [c]'s parameters appended: [base] + n for 0-7, [bright] + n - 8 for 8-15, else 5;n or 2;r;g;b */
|
||||
fun color(c: Int, base: Int, bright: Int) {
|
||||
when {
|
||||
c == Style.DEFAULT_FG || c == Style.DEFAULT_BG -> {}
|
||||
@@ -820,6 +846,7 @@ class TerminalEmulator(
|
||||
private fun placeImage(img: TermImage) {
|
||||
val tilesW = (img.width + img.cellWidth - 1) / img.cellWidth
|
||||
val tilesH = (img.height + img.cellHeight - 1) / img.cellHeight
|
||||
/** cell [x] of [line] made the image's tile ([tx], [ty]) */
|
||||
fun tile(line: Line, x: Int, tx: Int, ty: Int) {
|
||||
line.set(x, 0, Style.erased(style))
|
||||
line.extraFor(x).image = ImageTile(img, tx, ty)
|
||||
@@ -851,6 +878,7 @@ class TerminalEmulator(
|
||||
// ------------------------------------------------------------------
|
||||
// the screen
|
||||
|
||||
/** a character written at the cursor: DEC graphics, combining, wrapping, insert mode and wide characters as they come, the cursor moved past it */
|
||||
private fun print(c: Int) {
|
||||
var cp = c
|
||||
if (if (shiftOut) g1Graphics else g0Graphics) cp = decGraphics(cp)
|
||||
@@ -916,11 +944,13 @@ class TerminalEmulator(
|
||||
if (cp == 0x200D) joinNext = true
|
||||
}
|
||||
|
||||
/** the cursor to the line's start */
|
||||
private fun carriageReturn() {
|
||||
cursorX = 0
|
||||
pendingWrap = false
|
||||
}
|
||||
|
||||
/** the cursor back one (a wrap pending: only that undone) */
|
||||
private fun backspace() {
|
||||
if (pendingWrap) {
|
||||
pendingWrap = false
|
||||
@@ -929,10 +959,12 @@ class TerminalEmulator(
|
||||
}
|
||||
}
|
||||
|
||||
/** LF: as [index] */
|
||||
private fun lineFeed() {
|
||||
index()
|
||||
}
|
||||
|
||||
/** the cursor down a line, the region scrolled up at its bottom */
|
||||
private fun index() {
|
||||
pendingWrap = false
|
||||
if (cursorY == bottom) {
|
||||
@@ -942,6 +974,7 @@ class TerminalEmulator(
|
||||
}
|
||||
}
|
||||
|
||||
/** the cursor up a line, the region scrolled down at its top */
|
||||
private fun reverseIndex() {
|
||||
pendingWrap = false
|
||||
if (cursorY == top) {
|
||||
@@ -966,6 +999,7 @@ class TerminalEmulator(
|
||||
screen[b] = gone
|
||||
}
|
||||
|
||||
/** lines [t] to [b] down one, a blank one at the top (the bottom one gone) */
|
||||
private fun scrollDown(t: Int, b: Int) {
|
||||
val gone = screen[b]
|
||||
for (y in b downTo t + 1) screen[y] = screen[y - 1]
|
||||
@@ -974,6 +1008,7 @@ class TerminalEmulator(
|
||||
screen[t] = gone
|
||||
}
|
||||
|
||||
/** the cursor to ([x], [y]) on the screen, or within the scrolling region if [clampToRegion] and it is in it */
|
||||
private fun moveCursor(x: Int, y: Int, clampToRegion: Boolean = false) {
|
||||
val (lo, hi) = if (clampToRegion && cursorY in top..bottom) top to bottom else 0 to rows - 1
|
||||
cursorX = x.coerceIn(0, cols - 1)
|
||||
@@ -981,6 +1016,7 @@ class TerminalEmulator(
|
||||
pendingWrap = false
|
||||
}
|
||||
|
||||
/** CUP: the cursor to ([x], [y]), from the region's top in origin mode */
|
||||
private fun cursorPosition(x: Int, y: Int) {
|
||||
if (originMode) {
|
||||
cursorX = x.coerceIn(0, cols - 1)
|
||||
@@ -992,6 +1028,7 @@ class TerminalEmulator(
|
||||
pendingWrap = false
|
||||
}
|
||||
|
||||
/** DECSTBM: the scrolling region lines [t] to [b] (ignored unless top < bottom), the cursor home */
|
||||
private fun setRegion(t: Int, b: Int) {
|
||||
val tt = t.coerceIn(0, rows - 1)
|
||||
val bb = b.coerceIn(0, rows - 1)
|
||||
@@ -1001,6 +1038,7 @@ class TerminalEmulator(
|
||||
cursorPosition(0, 0)
|
||||
}
|
||||
|
||||
/** the cursor on [n] tab stops (the last column at most) */
|
||||
private fun tab(n: Int) {
|
||||
repeat(n) {
|
||||
var x = cursorX + 1
|
||||
@@ -1010,6 +1048,7 @@ class TerminalEmulator(
|
||||
pendingWrap = false
|
||||
}
|
||||
|
||||
/** the cursor back [n] tab stops (the first column at least) */
|
||||
private fun backTab(n: Int) {
|
||||
repeat(n) {
|
||||
var x = cursorX - 1
|
||||
@@ -1019,10 +1058,12 @@ class TerminalEmulator(
|
||||
pendingWrap = false
|
||||
}
|
||||
|
||||
/** HTS: a tab stop at the cursor's column */
|
||||
private fun setTab() {
|
||||
if (cursorX < cols) tabs[cursorX] = true
|
||||
}
|
||||
|
||||
/** ED: the screen erased below the cursor (0), above it (1), all of it (2), or the scrollback (3) */
|
||||
private fun eraseDisplay(mode: Int) {
|
||||
val e = Style.erased(style)
|
||||
when (mode) {
|
||||
@@ -1047,6 +1088,7 @@ class TerminalEmulator(
|
||||
/** ESC[2J homes the cursor as ANSI.SYS did (BBS screens expect it) */
|
||||
var homeOnClear = true
|
||||
|
||||
/** EL: the line erased right of the cursor (0), left of it (1), or all of it (2) */
|
||||
private fun eraseLine(mode: Int) {
|
||||
val e = Style.erased(style)
|
||||
val l = screen[cursorY]
|
||||
@@ -1059,21 +1101,25 @@ class TerminalEmulator(
|
||||
pendingWrap = false
|
||||
}
|
||||
|
||||
/** ECH: [n] cells erased from the cursor */
|
||||
private fun eraseChars(n: Int) {
|
||||
screen[cursorY].clear(cursorX, cursorX + n, Style.erased(style))
|
||||
pendingWrap = false
|
||||
}
|
||||
|
||||
/** ICH: [n] blank cells inserted at the cursor */
|
||||
private fun insertChars(n: Int) {
|
||||
screen[cursorY].insertCells(cursorX, n, Style.erased(style))
|
||||
pendingWrap = false
|
||||
}
|
||||
|
||||
/** DCH: [n] cells deleted at the cursor */
|
||||
private fun deleteChars(n: Int) {
|
||||
screen[cursorY].deleteCells(cursorX, n, Style.erased(style))
|
||||
pendingWrap = false
|
||||
}
|
||||
|
||||
/** IL: [n] blank lines inserted at the cursor's, within the region */
|
||||
private fun insertLines(n: Int) {
|
||||
if (cursorY !in top..bottom) return
|
||||
repeat(n.coerceAtMost(bottom - cursorY + 1)) { scrollDown(cursorY, bottom) }
|
||||
@@ -1081,6 +1127,7 @@ class TerminalEmulator(
|
||||
pendingWrap = false
|
||||
}
|
||||
|
||||
/** DL: [n] lines deleted at the cursor's, blank ones in at the region's bottom */
|
||||
private fun deleteLines(n: Int) {
|
||||
if (cursorY !in top..bottom) return
|
||||
repeat(n.coerceAtMost(bottom - cursorY + 1)) {
|
||||
@@ -1095,17 +1142,20 @@ class TerminalEmulator(
|
||||
pendingWrap = false
|
||||
}
|
||||
|
||||
/** the alternate screen on or off (cleared first if [clear]) */
|
||||
private fun setAltScreen(on: Boolean, clear: Boolean) {
|
||||
if (on == altScreen) return
|
||||
screen = if (on) alt else main
|
||||
if (on && clear) for (l in alt) { l.clear(0, cols, Style.NORMAL); l.wrapped = false }
|
||||
}
|
||||
|
||||
/** DECSC: the cursor, rendition, origin mode and character sets saved, the screen's own */
|
||||
private fun saveCursor() {
|
||||
val s = Saved(cursorX, cursorY, style, pendingWrap, originMode, g0Graphics, g1Graphics, shiftOut)
|
||||
if (altScreen) savedAlt = s else savedMain = s
|
||||
}
|
||||
|
||||
/** DECRC: what [saveCursor] saved for this screen back (none: the cursor home) */
|
||||
private fun restoreCursor() {
|
||||
val s = (if (altScreen) savedAlt else savedMain)
|
||||
if (s == null) {
|
||||
@@ -1122,11 +1172,13 @@ class TerminalEmulator(
|
||||
shiftOut = s.so
|
||||
}
|
||||
|
||||
/** DECALN: the screen filled with E, the cursor home */
|
||||
private fun alignmentTest() {
|
||||
for (l in screen) for (x in 0 until cols) l.set(x, 'E'.code, Style.NORMAL)
|
||||
cursorPosition(0, 0)
|
||||
}
|
||||
|
||||
/** DECSTR: the modes, region, rendition, character sets and saved cursors back to their defaults */
|
||||
private fun softReset() {
|
||||
cursorVisible = true
|
||||
appCursorKeys = false
|
||||
@@ -1207,6 +1259,7 @@ class TerminalEmulator(
|
||||
revision++
|
||||
}
|
||||
|
||||
/** a screen's lines at the new size: excess lines dropped from the bottom (blank ones) then the top (to the scrollback, the main's), more taken back from it; the cursor kept on its line when [active] */
|
||||
private fun resizeScreen(old: Array<Line>, newCols: Int, newRows: Int, isMain: Boolean, active: Boolean): Array<Line> {
|
||||
for (l in old) l.resize(newCols)
|
||||
val list = ArrayList<Line>(old.toList())
|
||||
@@ -1283,6 +1336,7 @@ class TerminalEmulator(
|
||||
/** an X colour spec: rgb:r/g/b (1 to 4 hex digits each), #rgb, #rrggbb, #rrrrggggbbbb */
|
||||
fun parseColor(spec: String): Int? {
|
||||
val s = spec.trim()
|
||||
/** a spec's 1 to 4 hex digits as 0-255, or null */
|
||||
fun scale(h: String): Int? {
|
||||
val v = h.toIntOrNull(16) ?: return null
|
||||
return when (h.length) {
|
||||
@@ -1312,6 +1366,7 @@ class TerminalEmulator(
|
||||
private const val DEC_GRAPHICS =
|
||||
" ◆▒␉␌␍␊°±␋┘┐┌└┼⎺⎻─⎼⎽├┤┴┬│≤≥π≠£·"
|
||||
|
||||
/** [cp] in DEC special graphics: 0x5f..0x7e as line drawing, the rest as they are */
|
||||
fun decGraphics(cp: Int): Int =
|
||||
if (cp in 0x5f..0x7e) DEC_GRAPHICS[cp - 0x5f].code else cp
|
||||
}
|
||||
|
||||
@@ -38,6 +38,7 @@ fun TerminalEmulator.runs(row: Int, look: RunLook = RunLook()): List<StyledRun>
|
||||
val out = ArrayList<StyledRun>()
|
||||
val text = StringBuilder()
|
||||
|
||||
/** colour [c] as ARGB: the remote's override of it if it set one, else the theme's */
|
||||
fun color(c: Int, isFg: Boolean): Int {
|
||||
val i = when {
|
||||
c == Style.DEFAULT_FG -> 256
|
||||
|
||||
@@ -47,6 +47,7 @@ class TermTheme(
|
||||
companion object {
|
||||
private const val OPAQUE = 0xff000000.toInt()
|
||||
|
||||
/** the ints as an array */
|
||||
private fun ints(vararg v: Int) = v
|
||||
|
||||
val VGA = TermTheme(
|
||||
@@ -129,6 +130,7 @@ class TermTheme(
|
||||
|
||||
val ALL = listOf(VGA, XTERM, SOLARIZED_DARK, SOLARIZED_LIGHT, DRACULA, MONOKAI, GRUVBOX, NORD, TANGO_LIGHT, GREEN, AMBER)
|
||||
|
||||
/** the theme with [id], VGA if none has it */
|
||||
fun byId(id: String): TermTheme = ALL.firstOrNull { it.id == id } ?: VGA
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ package com.neodesktop.dmodem.terminal
|
||||
*/
|
||||
object Wcwidth {
|
||||
|
||||
/** the cells [cp] takes: 0, 1 or 2 */
|
||||
fun width(cp: Int): Int = when {
|
||||
cp < 0x300 -> 1
|
||||
inRanges(cp, ZERO) -> 0
|
||||
@@ -17,6 +18,7 @@ object Wcwidth {
|
||||
else -> 1
|
||||
}
|
||||
|
||||
/** whether [cp] is in one of [r]'s (first, last) pairs, sorted (a binary search) */
|
||||
private fun inRanges(cp: Int, r: IntArray): Boolean {
|
||||
var lo = 0
|
||||
var hi = r.size / 2 - 1
|
||||
|
||||
@@ -54,6 +54,7 @@ class Tone(val f1: Int, val f2: Int, val mod: Float, val cadence: FloatArray) {
|
||||
}
|
||||
}
|
||||
|
||||
/** [v] without ".0" when it is whole */
|
||||
private fun fmt(v: Float): String = if (v == v.toInt().toFloat()) v.toInt().toString() else v.toString()
|
||||
}
|
||||
|
||||
@@ -94,6 +95,7 @@ class CountryTones(
|
||||
return all.firstOrNull { it.name == real }
|
||||
}
|
||||
|
||||
/** [s] as the table's names are: upper case, spaces, '-' and '.' as '_' */
|
||||
private fun norm(s: String) = s.trim().uppercase().map { if (it == ' ' || it == '-' || it == '.') '_' else it }.joinToString("")
|
||||
|
||||
private val small = setOf("OF", "AND", "THE", "DA", "DU", "DE")
|
||||
|
||||
@@ -12,8 +12,10 @@ object Crc {
|
||||
c and 0xffff
|
||||
}
|
||||
|
||||
/** CRC-16 [crc] with the octet [b] added */
|
||||
fun crc16(crc: Int, b: Int): Int = ((crc shl 8) xor table16[((crc ushr 8) xor b) and 0xff]) and 0xffff
|
||||
|
||||
/** the CRC-16 of [len] bytes at [off], from [start] */
|
||||
fun crc16(data: ByteArray, off: Int = 0, len: Int = data.size, start: Int = 0): Int {
|
||||
var c = start
|
||||
for (i in off until off + len) c = crc16(c, data[i].toInt() and 0xff)
|
||||
@@ -29,6 +31,7 @@ object Crc {
|
||||
/** CRC-32 kept inverted as ZMODEM keeps it: start at 0xffffffff, invert at the end */
|
||||
fun crc32(crc: Int, b: Int): Int = table32[(crc xor b) and 0xff] xor (crc ushr 8)
|
||||
|
||||
/** the CRC-32 of [len] bytes at [off], from [start], kept inverted (not inverted at the end) */
|
||||
fun crc32(data: ByteArray, off: Int = 0, len: Int = data.size, start: Int = -1): Int {
|
||||
var c = start
|
||||
for (i in off until off + len) c = crc32(c, data[i].toInt() and 0xff)
|
||||
|
||||
@@ -32,6 +32,7 @@ object HexRecords {
|
||||
Format.SREC -> srec(data, base, name)
|
||||
}
|
||||
|
||||
/** [data] at [base] as Intel HEX: an extended linear address at each 64 KB, data records not crossing one, the end record */
|
||||
private fun intel(data: ByteArray, base: Long): List<String> {
|
||||
val out = ArrayList<String>()
|
||||
var upper = -1L
|
||||
@@ -52,12 +53,14 @@ object HexRecords {
|
||||
return out
|
||||
}
|
||||
|
||||
/** an Intel HEX record of [type] at [addr], its checksum after */
|
||||
private fun intelRecord(addr: Int, type: Int, data: ByteArray): String {
|
||||
val bytes = byteArrayOf(data.size.toByte(), (addr ushr 8).toByte(), addr.toByte(), type.toByte()) + data
|
||||
val sum = bytes.sumOf { it.toInt() and 0xff }
|
||||
return ":" + hex(bytes) + hex(byteArrayOf((-sum).toByte()))
|
||||
}
|
||||
|
||||
/** [data] at [base] as S-records: the header, data records (S1, S2 or S3, the smallest that holds it), the count, the end */
|
||||
private fun srec(data: ByteArray, base: Long, name: String): List<String> {
|
||||
val last = base + maxOf(data.size, 1) - 1
|
||||
// (the smallest addresses that hold the image: S1 16 bits, S2 24, S3 32)
|
||||
@@ -81,6 +84,7 @@ object HexRecords {
|
||||
return out
|
||||
}
|
||||
|
||||
/** an S-record of [type] with an address of [addrBytes] bytes, its count first and checksum after */
|
||||
private fun srecRecord(type: Int, addrBytes: Int, addr: Long, data: ByteArray): String {
|
||||
val a = ByteArray(addrBytes) { k -> (addr ushr (8 * (addrBytes - 1 - k))).toByte() }
|
||||
val body = byteArrayOf((addrBytes + data.size + 1).toByte()) + a + data
|
||||
@@ -90,6 +94,7 @@ object HexRecords {
|
||||
|
||||
private val DIGITS = "0123456789ABCDEF"
|
||||
|
||||
/** [b] in upper-case hex */
|
||||
private fun hex(b: ByteArray): String = buildString(b.size * 2) {
|
||||
for (x in b) {
|
||||
append(DIGITS[(x.toInt() ushr 4) and 15])
|
||||
@@ -141,6 +146,7 @@ object HexRecords {
|
||||
}
|
||||
}
|
||||
|
||||
/** the bytes the hex [digits] spell (an error, naming [what], if they aren't hex) */
|
||||
private fun bytesOf(digits: String, what: String): ByteArray {
|
||||
if (digits.length % 2 != 0 || digits.any { it !in '0'..'9' && it !in 'A'..'F' && it !in 'a'..'f' }) {
|
||||
throw IOException("$what: not hex digits")
|
||||
@@ -148,6 +154,7 @@ object HexRecords {
|
||||
return ByteArray(digits.length / 2) { k -> digits.substring(2 * k, 2 * k + 2).toInt(16).toByte() }
|
||||
}
|
||||
|
||||
/** an Intel HEX line: false if it isn't a record; its data, the end or an extended address taken */
|
||||
private fun intel(l: String): Boolean {
|
||||
if (!l.startsWith(":")) return false
|
||||
val b = bytesOf(l.substring(1), "Intel HEX record ${records + 1}")
|
||||
@@ -167,6 +174,7 @@ object HexRecords {
|
||||
return true
|
||||
}
|
||||
|
||||
/** an S-record line: false if it isn't a record; its header, data or the end taken */
|
||||
private fun srec(l: String): Boolean {
|
||||
if (l.length < 2 || (l[0] != 'S' && l[0] != 's') || !l[1].isDigit()) return false
|
||||
val type = l[1] - '0'
|
||||
@@ -192,6 +200,7 @@ object HexRecords {
|
||||
return true
|
||||
}
|
||||
|
||||
/** [data] at [addr] kept, and counted */
|
||||
private fun put(addr: Long, data: ByteArray) {
|
||||
chunks.add(addr to data)
|
||||
records++
|
||||
@@ -288,8 +297,10 @@ class HexTransfer(
|
||||
return listOf(got)
|
||||
}
|
||||
|
||||
/** the format's name, for messages */
|
||||
private fun label() = if (format == HexRecords.Format.INTEL) "Intel HEX" else "S-record"
|
||||
|
||||
/** [file]'s bytes, all of them (an error past [HexRecords.MAX_IMAGE]) */
|
||||
private fun readAll(file: Outgoing): ByteArray {
|
||||
val out = com.neodesktop.dmodem.io.Bytes()
|
||||
file.open().use { src ->
|
||||
|
||||
@@ -23,6 +23,7 @@ class Kermit(
|
||||
) {
|
||||
private var p = Progress()
|
||||
|
||||
/** the progress changed by [f], and reported */
|
||||
private fun report(f: (Progress) -> Progress) {
|
||||
p = f(p)
|
||||
progress(p)
|
||||
@@ -45,17 +46,20 @@ class Kermit(
|
||||
private var seq = 0
|
||||
|
||||
class Packet(val seq: Int, val type: Char, val data: ByteArray) {
|
||||
/** its type, sequence number and data's size, for the log */
|
||||
override fun toString() = "Packet($type $seq, ${data.size})"
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// packets
|
||||
|
||||
/** the check type a packet of [type] goes with: 1 for S, I and R (and during the S/Y exchange), else the agreed one */
|
||||
private fun checkLen(type: Char) = if (type == 'S' || type == 'I' || type == 'R') 1 else if (forceCheck1) 1 else check
|
||||
|
||||
/** (during the S/Y exchange, both sides on type 1) */
|
||||
private var forceCheck1 = true
|
||||
|
||||
/** a packet sent: padding, MARK, its header (an extended one for long data), [data], its check and EOL */
|
||||
private fun sendPacket(seq: Int, type: Char, data: ByteArray) {
|
||||
val ct = checkLen(type)
|
||||
val out = Bytes()
|
||||
@@ -84,6 +88,7 @@ class Kermit(
|
||||
io.write(out.toByteArray())
|
||||
}
|
||||
|
||||
/** the block check of [type] (1, 2 or 3: CRC) over [len] bytes at [off], as printable characters */
|
||||
private fun checkChars(type: Int, b: ByteArray, off: Int, len: Int): ByteArray {
|
||||
var s = 0
|
||||
for (i in off until off + len) s += b[i].toInt() and 0xff
|
||||
@@ -97,6 +102,7 @@ class Kermit(
|
||||
}
|
||||
}
|
||||
|
||||
/** the type 1 check of [len] bytes at [off] */
|
||||
private fun check1(b: ByteArray, off: Int, len: Int): Int = checkChars(1, b, off, len)[0].toInt()
|
||||
|
||||
/**
|
||||
@@ -105,6 +111,7 @@ class Kermit(
|
||||
*/
|
||||
private fun readPacket(wait: Long = timeoutMs): Packet? {
|
||||
val deadline = monotonicMs() + wait
|
||||
/** the next byte before the deadline, or -1 */
|
||||
fun next(): Int {
|
||||
val left = deadline - monotonicMs()
|
||||
if (left <= 0) return -1
|
||||
@@ -117,6 +124,7 @@ class Kermit(
|
||||
c = next()
|
||||
}
|
||||
val buf = Bytes()
|
||||
/** the next byte, kept in the packet's buffer too */
|
||||
fun take(): Int {
|
||||
val v = next()
|
||||
if (v >= 0) buf.write(v)
|
||||
@@ -182,6 +190,7 @@ class Kermit(
|
||||
|
||||
private var lastSentType = ' '
|
||||
|
||||
/** an E packet with [why] sent (if it can be), and the transfer failed with it */
|
||||
private fun error(why: String): Nothing {
|
||||
runCatching { sendPacket(seq, 'E', encodeText(why)) }
|
||||
throw IOException(why)
|
||||
@@ -202,6 +211,7 @@ class Kermit(
|
||||
// ------------------------------------------------------------------
|
||||
// the S/Y exchange
|
||||
|
||||
/** our Send-Init parameters: MAXL, TIME, NPAD, PADC, EOL, QCTL, QBIN, CHKT, REPT, CAPAS, WINDO, MAXLX1, MAXLX2 */
|
||||
private fun ourParams(): ByteArray {
|
||||
val b = Bytes()
|
||||
b.write(tochar(94)) // MAXL
|
||||
@@ -223,6 +233,7 @@ class Kermit(
|
||||
/** their parameters, agreed with ours ([sender]: we're the one that sent the S) */
|
||||
@Suppress("UNUSED_PARAMETER")
|
||||
private fun agree(d: ByteArray, sender: Boolean) {
|
||||
/** their parameter [i], or -1 if they didn't send it */
|
||||
fun at(i: Int): Int = if (i < d.size) d[i].toInt() and 0xff else -1
|
||||
at(0).takeIf { it > 32 }?.let { sendMax = unchar(it).coerceIn(10, 94) }
|
||||
npad = at(2).takeIf { it > 32 }?.let { unchar(it) } ?: 0
|
||||
@@ -260,6 +271,7 @@ class Kermit(
|
||||
if (qbin != 0 && qbin == rept) rept = 0
|
||||
}
|
||||
|
||||
/** whether [c] can be a prefix character (33-62, 96-126) */
|
||||
private fun isPrefix(c: Int) = c in 33..62 || c in 96..126
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -271,6 +283,7 @@ class Kermit(
|
||||
return if (sendLong > 0) sendLong - 5 - ct - 2 else sendMax - 2 - ct
|
||||
}
|
||||
|
||||
/** one byte encoded into [out]: its 8th bit prefixed (when agreed), control characters and the prefixes themselves quoted */
|
||||
private fun encodeByte(out: Bytes, v: Int) {
|
||||
var b = v
|
||||
if (qbin != 0 && b and 0x80 != 0) {
|
||||
@@ -317,6 +330,7 @@ class Kermit(
|
||||
return out.toByteArray() to (i - off)
|
||||
}
|
||||
|
||||
/** [s]'s UTF-8 encoded for a packet, all of it */
|
||||
private fun encodeText(s: String): ByteArray {
|
||||
val b = s.encodeToByteArray()
|
||||
return encode(b, 0, b.size, Int.MAX_VALUE).first
|
||||
@@ -348,6 +362,7 @@ class Kermit(
|
||||
}
|
||||
}
|
||||
|
||||
/** a packet's data decoded, as UTF-8 text */
|
||||
private fun decodeText(d: ByteArray): String = Bytes().also { decode(d, it) }.toByteArray().decodeToString()
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -391,12 +406,14 @@ class Kermit(
|
||||
exchange('B', ByteArray(0))
|
||||
}
|
||||
|
||||
/** [f] sent: F, its attributes if agreed (A), D packets, Z (the file skipped if the receiver refuses or stops it) */
|
||||
private fun sendFile(f: Outgoing) {
|
||||
report { it.copy(file = f.name, bytes = 0, size = f.size) }
|
||||
val nameAck = exchange('F', encodeText(f.name))
|
||||
if (nameAck.isNotEmpty()) decodeText(nameAck)
|
||||
if (attributes) {
|
||||
val a = Bytes()
|
||||
/** an attribute: [tag], its length, [v] */
|
||||
fun attr(tag: Char, v: String) {
|
||||
a.write(tag.code)
|
||||
a.write(tochar(v.length))
|
||||
@@ -447,11 +464,13 @@ class Kermit(
|
||||
// ------------------------------------------------------------------
|
||||
// receiving
|
||||
|
||||
/** an ACK (Y) of [seq] sent, with [data] */
|
||||
private fun ack(seq: Int, data: ByteArray = ByteArray(0)) {
|
||||
lastSentType = 'Y'
|
||||
sendPacket(seq, 'Y', data)
|
||||
}
|
||||
|
||||
/** a NAK (N) of [seq] sent */
|
||||
private fun nak(seq: Int) {
|
||||
lastSentType = 'N'
|
||||
sendPacket(seq, 'N', ByteArray(0))
|
||||
@@ -582,7 +601,9 @@ class Kermit(
|
||||
|
||||
private class CountingStream(private val o: Sink) : Sink {
|
||||
var n = 0L
|
||||
/** the byte [b] written on, and counted */
|
||||
override fun write(b: Int) { o.write(b); n++ }
|
||||
/** [len] bytes of [b] written on, and counted */
|
||||
override fun write(b: ByteArray, off: Int, len: Int) { o.write(b, off, len); n += len }
|
||||
}
|
||||
|
||||
@@ -597,8 +618,11 @@ class Kermit(
|
||||
const val OUR_LONG = 4000
|
||||
const val MAX_RETRIES = 10
|
||||
|
||||
/** [x] as a printable character (+32) */
|
||||
fun tochar(x: Int) = x + 32
|
||||
/** a printable character back to its value (-32) */
|
||||
fun unchar(x: Int) = x - 32
|
||||
/** [x] with its control bit flipped (xor 64) */
|
||||
fun ctl(x: Int) = x xor 64
|
||||
|
||||
/** CRC-16/KERMIT (CCITT, bits reflected, from 0) */
|
||||
@@ -622,10 +646,12 @@ class Kermit(
|
||||
return false
|
||||
}
|
||||
|
||||
/** [sec] as an attribute's date in local time: yyyymmdd hh:mm:ss */
|
||||
private fun formatDate(sec: Long): String {
|
||||
val local = sec + localOffsetSeconds(sec)
|
||||
val (y, mo, d) = civil(local.floorDiv(86400L))
|
||||
val t = local.mod(86400L).toInt()
|
||||
/** [v] in two digits */
|
||||
fun two(v: Int) = v.toString().padStart(2, '0')
|
||||
return "${y.toString().padStart(4, '0')}${two(mo)}${two(d)} ${two(t / 3600)}:${two(t / 60 % 60)}:${two(t % 60)}"
|
||||
}
|
||||
|
||||
@@ -77,6 +77,7 @@ class Transfer(
|
||||
private set
|
||||
private var kermit: Kermit? = null
|
||||
|
||||
/** the state now [s], and said so */
|
||||
private fun update(s: TransferState) {
|
||||
state = s
|
||||
onState(s)
|
||||
@@ -110,6 +111,7 @@ class Transfer(
|
||||
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)
|
||||
background("transfer-${protocol.name.lowercase()}") {
|
||||
@@ -162,6 +164,7 @@ class Transfer(
|
||||
return null
|
||||
}
|
||||
|
||||
/** where [pat] first is in [b]'s first [len] bytes, or -1 */
|
||||
private fun indexOf(b: ByteArray, len: Int, pat: ByteArray): Int {
|
||||
outer@ for (i in 0..len - pat.size) {
|
||||
for (j in pat.indices) if (b[i + j] != pat[j]) continue@outer
|
||||
|
||||
@@ -27,12 +27,14 @@ class TransferIo(private val send: (ByteArray) -> Unit) {
|
||||
if (len > 0) queue.put(data.copyOfRange(off, off + len).also { b -> trace?.invoke(true, b) })
|
||||
}
|
||||
|
||||
/** bytes to the remote (refused, TransferCancelled, once cancelled) */
|
||||
fun write(b: ByteArray) {
|
||||
if (cancelled != null) throw TransferCancelled(cancelled!!)
|
||||
trace?.invoke(false, b)
|
||||
send(b)
|
||||
}
|
||||
|
||||
/** the bytes [b] (each 0-255) to the remote */
|
||||
fun write(vararg b: Int) = write(ByteArray(b.size) { b[it].toByte() })
|
||||
|
||||
/** a byte (0-255), or -1 when none came within [timeoutMs] (the cancel looked at every quarter second) */
|
||||
@@ -78,6 +80,7 @@ class TransferIo(private val send: (ByteArray) -> Unit) {
|
||||
return out.toByteArray()
|
||||
}
|
||||
|
||||
/** cancelled for [why]: reads and writes throw TransferCancelled from now on */
|
||||
fun cancel(why: String) {
|
||||
cancelled = why
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ class XYModem(
|
||||
) {
|
||||
private var p = Progress()
|
||||
|
||||
/** the progress changed by [f], and reported */
|
||||
private fun report(f: (Progress) -> Progress) {
|
||||
p = f(p)
|
||||
progress(p)
|
||||
@@ -111,6 +112,7 @@ class XYModem(
|
||||
*/
|
||||
private var eot = false
|
||||
|
||||
/** a block within [waitMs], its CRC or checksum checked (as above): EOT sets [eot] */
|
||||
private fun readBlock(useCrc: Boolean, waitMs: Long): Block? {
|
||||
eot = false
|
||||
// (what isn't a block's start let go by: the sender's own messages, line noise)
|
||||
@@ -148,6 +150,7 @@ class XYModem(
|
||||
return Block(n, data)
|
||||
}
|
||||
|
||||
/** the rest of a bad block let go by: null */
|
||||
private fun badBlock(): Block? {
|
||||
// (what's left of the bad block: let it go by)
|
||||
while (io.read(200) >= 0) { /* drop */ }
|
||||
@@ -262,6 +265,7 @@ class XYModem(
|
||||
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) {
|
||||
var n = 1
|
||||
var sent = 0L
|
||||
@@ -305,6 +309,7 @@ class XYModem(
|
||||
}
|
||||
}
|
||||
|
||||
/** block [n]'s bytes: SOH or STX, its number and complement, [data], its CRC-16 or checksum */
|
||||
private fun blockBytes(n: Int, data: ByteArray, useCrc: Boolean): ByteArray {
|
||||
val out = Bytes()
|
||||
out.write(if (data.size == 1024) STX else SOH)
|
||||
|
||||
Reference in new issue
Block a user