mirror of
https://github.com/D-Modem/app.git
synced 2026-11-28 17:38:05 -08:00
Comments for every function: the app's code and tests, batch 3 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:
35 files changed
+232
No files matched your search
@@ -80,14 +80,17 @@ class SshLink(
|
||||
@Volatile var agentForwarded = false
|
||||
private set
|
||||
|
||||
/** [s] added to [events], the oldest dropped past [MAX_EVENTS] */
|
||||
private fun event(s: String) {
|
||||
_events.value = (_events.value + s).takeLast(MAX_EVENTS)
|
||||
}
|
||||
|
||||
/** [l] told the shell's output from now on */
|
||||
override fun addListener(l: TerminalLink.Listener) {
|
||||
listeners.add(l)
|
||||
}
|
||||
|
||||
/** [l] told no more */
|
||||
override fun removeListener(l: TerminalLink.Listener) {
|
||||
listeners.remove(l)
|
||||
}
|
||||
@@ -97,6 +100,7 @@ class SshLink(
|
||||
Thread({ run() }, "ssh-$host").apply { isDaemon = true }.start()
|
||||
}
|
||||
|
||||
/** the connection's life on its thread: connect, log in, start forwards and the agent, open the shell and read it until it ends */
|
||||
private fun run() {
|
||||
try {
|
||||
SshSecurity.ensure()
|
||||
@@ -104,9 +108,11 @@ class SshLink(
|
||||
client = c
|
||||
// (the host key's question asked as this link's: cancelled if it closes)
|
||||
c.addHostKeyVerifier(object : net.schmizz.sshj.transport.verification.HostKeyVerifier {
|
||||
/** the host's key checked against [knownHosts], the user asked of a new or changed one */
|
||||
override fun verify(hostname: String, port: Int, key: java.security.PublicKey) =
|
||||
knownHosts.verify(hostname, port, key, this@SshLink)
|
||||
|
||||
/** the key algorithms [knownHosts] already has for the host, preferred in the handshake */
|
||||
override fun findExistingAlgorithms(hostname: String, port: Int): List<String> =
|
||||
knownHosts.findExistingAlgorithms(hostname, port)
|
||||
})
|
||||
@@ -149,6 +155,7 @@ class SshLink(
|
||||
}
|
||||
}
|
||||
|
||||
/** the user logged in: by [key] if there is one, else by password (the saved one first) or the server's questions */
|
||||
private fun authenticate(c: SSHClient) {
|
||||
if (key != null) {
|
||||
c.authPublickey(user, key)
|
||||
@@ -157,6 +164,7 @@ class SshLink(
|
||||
var tries = 0
|
||||
var saved = savedPassword
|
||||
val finder = object : PasswordFinder {
|
||||
/** the password: the saved one first, then the user's, kept if they asked; null if they cancelled */
|
||||
override fun reqPassword(resource: Resource<*>?): CharArray? {
|
||||
tries++
|
||||
saved?.let { saved = null; return it.toCharArray() }
|
||||
@@ -166,19 +174,23 @@ class SshLink(
|
||||
return p.toCharArray()
|
||||
}
|
||||
|
||||
/** another password asked for while under [MAX_TRIES] tries */
|
||||
override fun shouldRetry(resource: Resource<*>?) = tries < MAX_TRIES
|
||||
}
|
||||
val questions = object : ChallengeResponseProvider {
|
||||
private var name = ""
|
||||
private var instruction = ""
|
||||
private var answered = false
|
||||
/** no particular submethods asked for */
|
||||
override fun getSubmethods(): List<String> = emptyList()
|
||||
/** a new round of questions: its name and instruction kept for the dialogs */
|
||||
override fun init(resource: Resource<*>?, name: String?, instruction: String?) {
|
||||
this.name = name ?: ""
|
||||
this.instruction = instruction ?: ""
|
||||
answered = false
|
||||
}
|
||||
|
||||
/** the user's answer to the server's one question, or null if they cancelled */
|
||||
override fun getResponse(prompt: String?, echo: Boolean): CharArray? {
|
||||
// (one question at a time from sshj: each its own dialog)
|
||||
val a = ask(
|
||||
@@ -191,12 +203,14 @@ class SshLink(
|
||||
return a.texts?.firstOrNull()?.toCharArray()
|
||||
}
|
||||
|
||||
/** asked again only if the user didn't answer, and under [MAX_TRIES] tries */
|
||||
override fun shouldRetry(): Boolean = !answered && tries++ < MAX_TRIES
|
||||
}
|
||||
val methods: List<AuthMethod> = listOf(AuthPassword(finder), AuthKeyboardInteractive(questions))
|
||||
c.auth(user, methods)
|
||||
}
|
||||
|
||||
/** [s] read to the listeners: on a thread of its own when [name]d (stderr), else on this one */
|
||||
private fun pump(s: InputStream, name: String?) {
|
||||
if (name != null) {
|
||||
Thread({ read(s) }, "ssh-$host-$name").apply { isDaemon = true }.start()
|
||||
@@ -205,6 +219,7 @@ class SshLink(
|
||||
}
|
||||
}
|
||||
|
||||
/** [s] to the listeners until it ends or fails */
|
||||
private fun read(s: InputStream) {
|
||||
val buf = ByteArray(8192)
|
||||
try {
|
||||
@@ -220,6 +235,7 @@ class SshLink(
|
||||
/** a forward started on the open connection; false if it couldn't be (its error in [forwards]) */
|
||||
fun addForward(spec: ForwardSpec): Boolean = fwd?.start(spec) ?: false
|
||||
|
||||
/** the forward for [spec] stopped */
|
||||
fun removeForward(spec: ForwardSpec) {
|
||||
fwd?.stop(spec)
|
||||
}
|
||||
@@ -243,6 +259,7 @@ class SshLink(
|
||||
}
|
||||
}
|
||||
|
||||
/** the link closed, with [reason] (null: the user's doing): its questions cancelled, forwards and connection closed; once */
|
||||
private fun closed(reason: String?) {
|
||||
if (_state.value is TerminalLink.State.Closed) return
|
||||
_state.value = TerminalLink.State.Closed(reason)
|
||||
@@ -255,6 +272,7 @@ class SshLink(
|
||||
io.shutdown()
|
||||
}
|
||||
|
||||
/** [length] bytes of [data] queued to the shell, off the caller's thread; false if it isn't open */
|
||||
override fun write(data: ByteArray, offset: Int, length: Int): Boolean {
|
||||
val o = out ?: return false
|
||||
if (_state.value !is TerminalLink.State.Open) return false
|
||||
@@ -276,6 +294,7 @@ class SshLink(
|
||||
}
|
||||
}
|
||||
|
||||
/** the new size kept for the pty and sent to the server's window if the shell is open */
|
||||
override fun resize(cols: Int, rows: Int) {
|
||||
this.cols = cols
|
||||
this.rows = rows
|
||||
@@ -291,6 +310,7 @@ class SshLink(
|
||||
}
|
||||
}
|
||||
|
||||
/** the shell closed and the link with it, on a thread of its own; no reason given */
|
||||
override fun close() {
|
||||
closing = true
|
||||
cancelAsks(this)
|
||||
|
||||
@@ -41,18 +41,22 @@ class TelnetLink(
|
||||
private val local = BooleanArray(256)
|
||||
@Volatile private var nawsOn = false
|
||||
|
||||
/** [l] told the server's data from now on */
|
||||
override fun addListener(l: TerminalLink.Listener) {
|
||||
listeners.add(l)
|
||||
}
|
||||
|
||||
/** [l] told no more */
|
||||
override fun removeListener(l: TerminalLink.Listener) {
|
||||
listeners.remove(l)
|
||||
}
|
||||
|
||||
/** the connection made, in a thread of its own */
|
||||
fun connect() {
|
||||
Thread({ run() }, "telnet-$host").apply { isDaemon = true }.start()
|
||||
}
|
||||
|
||||
/** the connection's life on its thread: connect, then read until it ends */
|
||||
private fun run() {
|
||||
try {
|
||||
val s = Socket()
|
||||
@@ -72,6 +76,7 @@ class TelnetLink(
|
||||
|
||||
private enum class In { DATA, IAC, OPT, SB, SB_IAC }
|
||||
|
||||
/** the server's bytes until it closes: data (CR NUL a CR, IAC IAC an 0xff) to the listeners, its commands answered */
|
||||
private fun read(s: Socket) {
|
||||
val inp = s.getInputStream()
|
||||
val buf = ByteArray(8192)
|
||||
@@ -146,6 +151,7 @@ class TelnetLink(
|
||||
}
|
||||
}
|
||||
|
||||
/** the server's subnegotiation answered: TERMINAL-TYPE SEND with IS [termType] */
|
||||
private fun subnegotiation(sb: ByteArray) {
|
||||
// TERMINAL-TYPE SEND: IS <type>
|
||||
if (sb.size >= 2 && (sb[0].toInt() and 0xff) == TTYPE && sb[1].toInt() == 1) {
|
||||
@@ -154,6 +160,7 @@ class TelnetLink(
|
||||
}
|
||||
}
|
||||
|
||||
/** the window's size sent to the server (NAWS) */
|
||||
private fun sendNaws() {
|
||||
val c = cols.coerceIn(0, 65535)
|
||||
val r = rows.coerceIn(0, 65535)
|
||||
@@ -163,6 +170,7 @@ class TelnetLink(
|
||||
send(*(intArrayOf(IAC, SB, NAWS) + body + intArrayOf(IAC, SE)))
|
||||
}
|
||||
|
||||
/** the bytes [v] sent as they are, ignoring a failure */
|
||||
private fun send(vararg v: Int) {
|
||||
val o = out ?: return
|
||||
try {
|
||||
@@ -174,6 +182,7 @@ class TelnetLink(
|
||||
}
|
||||
}
|
||||
|
||||
/** [length] bytes of [data] sent with IAC doubled and a lone CR as CR NUL outside binary; false if not open or it failed */
|
||||
override fun write(data: ByteArray, offset: Int, length: Int): Boolean {
|
||||
val o = out ?: return false
|
||||
if (_state.value !is TerminalLink.State.Open) return false
|
||||
@@ -196,12 +205,14 @@ class TelnetLink(
|
||||
}
|
||||
}
|
||||
|
||||
/** 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
|
||||
this.rows = rows
|
||||
if (nawsOn) Thread({ sendNaws() }, "telnet-naws").start()
|
||||
}
|
||||
|
||||
/** the link closed, with [reason] (null: the user's doing), and its socket; once */
|
||||
private fun closed(reason: String?) {
|
||||
if (_state.value is TerminalLink.State.Closed) return
|
||||
_state.value = TerminalLink.State.Closed(reason)
|
||||
@@ -211,6 +222,7 @@ class TelnetLink(
|
||||
}
|
||||
}
|
||||
|
||||
/** the link closed by the user: no reason given */
|
||||
override fun close() {
|
||||
closing = true
|
||||
closed(null)
|
||||
|
||||
@@ -15,6 +15,7 @@ object BoxDrawing {
|
||||
// each line character: its arms (up, right, down, left), 0 none, 1 light, 2 double, 3 heavy
|
||||
private val arms = HashMap<Int, Int>()
|
||||
|
||||
/** each of [chars] given these arms, packed two bits each in [arms] */
|
||||
private fun put(chars: String, up: Int, right: Int, down: Int, left: Int) {
|
||||
for (c in chars) arms[c.code] = (up shl 6) or (right shl 4) or (down shl 2) or left
|
||||
}
|
||||
@@ -36,6 +37,7 @@ object BoxDrawing {
|
||||
put("╪", 1, 2, 1, 2); put("╫", 2, 1, 2, 1)
|
||||
}
|
||||
|
||||
/** whether [cp] is one this draws: a block element or a line character */
|
||||
fun handles(cp: Int): Boolean = cp in 0x2580..0x259f || arms.containsKey(cp)
|
||||
|
||||
/** cp in the cell (x, y, w, h) in paint's colour; false if it isn't one of ours */
|
||||
@@ -57,12 +59,14 @@ object BoxDrawing {
|
||||
val top = yc - kotlin.math.floor(t / 2)
|
||||
c.drawRect(x0, top, x1, top + t, paint)
|
||||
}
|
||||
// a vertical line of thickness t centred on xc from y0 to y1
|
||||
fun v(y0: Float, y1: Float, xc: Float, t: Float) {
|
||||
val left = xc - kotlin.math.floor(t / 2)
|
||||
c.drawRect(left, y0, left + t, y1, paint)
|
||||
}
|
||||
// a line of thickness t centred on c covers lo(c, t) until hi(c, t)
|
||||
fun lo(c0: Float, t: Float) = c0 - kotlin.math.floor(t / 2)
|
||||
// where a line of thickness t centred on c0 ends
|
||||
fun hi(c0: Float, t: Float) = lo(c0, t) + t
|
||||
// where a line of a double arm meets the arm across its side: none, the
|
||||
// outer corner (-gap); single or heavy, the centre line; double, the inner corner (+gap)
|
||||
@@ -113,6 +117,7 @@ object BoxDrawing {
|
||||
return true
|
||||
}
|
||||
|
||||
/** a block element (U+2580..259F) filling its part of the cell, the shades in paint's alpha; false if not one */
|
||||
private fun block(c: Canvas, cp: Int, x: Float, y: Float, w: Float, h: Float, paint: Paint): Boolean {
|
||||
val alpha = paint.alpha
|
||||
when (cp) {
|
||||
|
||||
@@ -50,8 +50,10 @@ class ConnectionService : Service() {
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
|
||||
|
||||
/** not bound to: started and stopped only */
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
/** in the foreground with the notification, kept up to date as sessions change; stopped when no network session is open */
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
@@ -75,6 +77,7 @@ class ConnectionService : Service() {
|
||||
}
|
||||
}
|
||||
|
||||
/** "Disconnect all": every network session closed; not restarted if killed */
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
if (intent?.action == ACTION_CLOSE_ALL) {
|
||||
Terminal.sessions.value.filter { it.kind != TerminalSession.Kind.MODEM }.forEach { Terminal.close(it) }
|
||||
@@ -82,11 +85,13 @@ class ConnectionService : Service() {
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
/** the session watch cancelled */
|
||||
override fun onDestroy() {
|
||||
scope.cancel()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
/** the notification: the open network sessions, a tap to the app, and "Disconnect all" */
|
||||
private fun notification(): Notification {
|
||||
val open = Terminal.sessions.value.filter {
|
||||
it.kind != TerminalSession.Kind.MODEM && it.link.state.value !is TerminalLink.State.Closed
|
||||
|
||||
@@ -63,6 +63,7 @@ data class DialEntry(
|
||||
EntryKind.TELNET -> host.isNotBlank()
|
||||
}
|
||||
|
||||
/** the entry as stored in directory.json */
|
||||
fun toJson(): JSONObject = JSONObject()
|
||||
.put("id", id).put("name", name).put("kind", kind.name).put("number", number)
|
||||
.put("host", host).put("port", port).put("user", user).put("auth", auth.name).put("keyId", keyId)
|
||||
@@ -72,6 +73,7 @@ data class DialEntry(
|
||||
.put("forwards", org.json.JSONArray(forwards)).put("agent", agentForwarding).put("agentConfirm", agentConfirm)
|
||||
|
||||
companion object {
|
||||
/** an entry from its JSON, defaults for what's missing or unknown (a new id if it has none) */
|
||||
fun fromJson(o: JSONObject) = DialEntry(
|
||||
id = o.optString("id").ifEmpty { UUID.randomUUID().toString() },
|
||||
name = o.optString("name"),
|
||||
@@ -104,9 +106,11 @@ data class Snippet(
|
||||
/** with escapes: \r \n \t \e \\ \xHH, ^A..^_ as ^A */
|
||||
val text: String = "",
|
||||
) {
|
||||
/** the snippet as stored in snippets.json */
|
||||
fun toJson(): JSONObject = JSONObject().put("id", id).put("name", name).put("text", text)
|
||||
|
||||
companion object {
|
||||
/** a snippet from its JSON (a new id if it has none) */
|
||||
fun fromJson(o: JSONObject) = Snippet(
|
||||
id = o.optString("id").ifEmpty { UUID.randomUUID().toString() },
|
||||
name = o.optString("name"),
|
||||
@@ -180,6 +184,7 @@ class JsonListStore<T>(
|
||||
_items.value = load() ?: defaults.also { save(it) }
|
||||
}
|
||||
|
||||
/** the list in [file], or null if there is none or it can't be read */
|
||||
private fun load(): List<T>? = try {
|
||||
if (!file.exists()) {
|
||||
null
|
||||
@@ -191,6 +196,7 @@ class JsonListStore<T>(
|
||||
null
|
||||
}
|
||||
|
||||
/** [list] written to [file] (by way of a .tmp, renamed) and made the items */
|
||||
@Synchronized
|
||||
private fun save(list: List<T>) {
|
||||
val a = JSONArray()
|
||||
@@ -209,10 +215,12 @@ class JsonListStore<T>(
|
||||
save(l)
|
||||
}
|
||||
|
||||
/** the one with [item]'s id taken out */
|
||||
fun remove(item: T) {
|
||||
save(_items.value.filter { id(it) != id(item) })
|
||||
}
|
||||
|
||||
/** the item at [from] moved to [to]; nothing if either is out of range */
|
||||
fun move(from: Int, to: Int) {
|
||||
val l = _items.value.toMutableList()
|
||||
if (from !in l.indices || to !in l.indices) return
|
||||
|
||||
@@ -65,6 +65,7 @@ object Terminal {
|
||||
@android.annotation.SuppressLint("StaticFieldLeak")
|
||||
private lateinit var app: Context
|
||||
|
||||
/** the stores and the modem's session set up, from [context]'s application; once, at start */
|
||||
fun init(context: Context, box: SecretBox = KeystoreBox()) {
|
||||
app = context.applicationContext
|
||||
session = TerminalSession(ModemState.dte) { app.getExternalFilesDir("captures") }
|
||||
@@ -85,6 +86,7 @@ object Terminal {
|
||||
/** where files a remote sends go */
|
||||
fun downloads(): com.neodesktop.dmodem.transfer.Incoming = com.neodesktop.dmodem.transfer.DownloadsIncoming(app)
|
||||
|
||||
/** [s] put on the screen, if it is one of the sessions */
|
||||
fun select(s: TerminalSession) {
|
||||
if (s in _sessions.value) _active.value = s
|
||||
}
|
||||
|
||||
@@ -38,6 +38,7 @@ enum class TerminalFont(
|
||||
val hasBold: Boolean get() = variable || asset == null
|
||||
|
||||
companion object {
|
||||
/** the font of that enum name, or [SYSTEM] if none is */
|
||||
fun byName(name: String?): TerminalFont = entries.firstOrNull { it.name == name } ?: SYSTEM
|
||||
}
|
||||
}
|
||||
@@ -46,10 +47,12 @@ enum class TerminalFont(
|
||||
object FontCache {
|
||||
private val cache = HashMap<Pair<TerminalFont, Boolean>, Typeface>()
|
||||
|
||||
/** [font]'s typeface, bold or not; made the first time */
|
||||
@Synchronized
|
||||
fun typeface(context: Context, font: TerminalFont, bold: Boolean): Typeface =
|
||||
cache.getOrPut(font to bold) { load(context.assets, font, bold) }
|
||||
|
||||
/** [font]'s typeface from its asset (a variable one at weight 700 or 400), the monospace one if it has none or it fails */
|
||||
private fun load(assets: AssetManager, font: TerminalFont, bold: Boolean): Typeface {
|
||||
val path = font.asset ?: return Typeface.create(Typeface.MONOSPACE, if (bold) Typeface.BOLD else Typeface.NORMAL)
|
||||
return try {
|
||||
|
||||
@@ -25,7 +25,9 @@ interface TerminalLink {
|
||||
|
||||
val state: StateFlow<State>
|
||||
|
||||
/** [l] told the octets from the far end from now on */
|
||||
fun addListener(l: Listener)
|
||||
/** [l] told no more */
|
||||
fun removeListener(l: Listener)
|
||||
|
||||
/** octets to the far end: false if it can't take them (closed) */
|
||||
|
||||
@@ -141,6 +141,7 @@ class TerminalSession(
|
||||
onChange?.invoke()
|
||||
}
|
||||
|
||||
/** a transfer made the running one, over the link: null if one already is */
|
||||
private fun startTransfer(protocol: Protocol, sending: Boolean): Transfer? = synchronized(transferLock) {
|
||||
if (transfer != null) return null
|
||||
val t = Transfer(
|
||||
@@ -154,6 +155,7 @@ class TerminalSession(
|
||||
t
|
||||
}
|
||||
|
||||
/** the transfer's end: it no longer running, its outcome on the screen and the bytes after it to the emulator */
|
||||
private fun endTransfer(s: TransferState, rest: ByteArray) {
|
||||
synchronized(transferLock) { transfer = null }
|
||||
val what = s.protocol.label
|
||||
@@ -184,6 +186,7 @@ class TerminalSession(
|
||||
return true
|
||||
}
|
||||
|
||||
/** the running transfer, if any, cancelled */
|
||||
fun cancelTransfer() {
|
||||
transfer?.cancel()
|
||||
}
|
||||
@@ -195,14 +198,17 @@ class TerminalSession(
|
||||
|
||||
init {
|
||||
emulator.listener = object : TerminalEmulator.Listener {
|
||||
/** the window's title (OSC 0/2) for [title] */
|
||||
override fun onTitle(title: String) {
|
||||
_title.value = title
|
||||
}
|
||||
|
||||
/** the bell to [onBell] */
|
||||
override fun onBell() {
|
||||
onBell?.invoke()
|
||||
}
|
||||
|
||||
/** the remote's clipboard text to [onClipboard] */
|
||||
override fun onClipboard(text: String) {
|
||||
onClipboard?.invoke(text)
|
||||
}
|
||||
@@ -255,6 +261,7 @@ class TerminalSession(
|
||||
}
|
||||
}
|
||||
|
||||
/** the latched Ctrl and Alt let go */
|
||||
private fun releaseLatches() {
|
||||
ctrl.value = false
|
||||
alt.value = false
|
||||
@@ -301,11 +308,13 @@ class TerminalSession(
|
||||
if (kind != Kind.MODEM) link.close()
|
||||
}
|
||||
|
||||
/** the emulator reset (RIS, the scrollback kept) and the view redrawn */
|
||||
fun reset() {
|
||||
synchronized(emulator) { emulator.reset() }
|
||||
onChange?.invoke()
|
||||
}
|
||||
|
||||
/** the screen and the scrollback cleared and the view redrawn */
|
||||
fun clear() {
|
||||
synchronized(emulator) { emulator.clearAll() }
|
||||
onChange?.invoke()
|
||||
@@ -335,6 +344,7 @@ class TerminalSession(
|
||||
/** the capture file closed: the file, or null if there was none */
|
||||
fun stopCapture(): File? = synchronized(captureLock) { stopCaptureLocked() }
|
||||
|
||||
/** the capture closed, with [captureLock] held: its file, or null */
|
||||
private fun stopCaptureLocked(): File? {
|
||||
val f = _capture.value
|
||||
try {
|
||||
|
||||
@@ -104,6 +104,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
// blinking
|
||||
private var blinkOn = true
|
||||
private val blink = object : Runnable {
|
||||
/** the blink's phase flipped and the screen redrawn, again in [BLINK_MS] */
|
||||
override fun run() {
|
||||
blinkOn = !blinkOn
|
||||
invalidate()
|
||||
@@ -133,6 +134,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
private var regularFace: Typeface = Typeface.MONOSPACE
|
||||
private var boldFace: Typeface? = null
|
||||
|
||||
/** the settings applied: the font, theme and the modem session's keys and echo, the cells measured and the emulator resized */
|
||||
fun applySettings(s: TerminalSettings) {
|
||||
val fontChanged = s.font != settings.font || s.ligatures != settings.ligatures || boldFace == null
|
||||
val sizeChanged = fontChanged || s.fontSize != settings.fontSize || s.fixedColumns != settings.fixedColumns
|
||||
@@ -169,6 +171,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
// ------------------------------------------------------------------
|
||||
// size
|
||||
|
||||
/** the font's size (from the settings, or to fit the fixed columns in the width) and the cell's from it */
|
||||
private fun measureFont() {
|
||||
val w = width
|
||||
fontPx = if (settings.fixedColumns > 0 && w > 0) {
|
||||
@@ -193,12 +196,14 @@ class TerminalView @JvmOverloads constructor(
|
||||
ascent = up
|
||||
}
|
||||
|
||||
/** the cells measured again and the emulator fitted to the new size */
|
||||
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
|
||||
measureFont()
|
||||
syncEmulator()
|
||||
resizeEmulator()
|
||||
}
|
||||
|
||||
/** the emulator (and the far end) told the columns and rows that fit the view */
|
||||
private fun resizeEmulator() {
|
||||
val s = session ?: return
|
||||
if (width <= 0 || height <= 0) return
|
||||
@@ -208,11 +213,13 @@ class TerminalView @JvmOverloads constructor(
|
||||
scrollRows = scrollRows.coerceIn(0, historySize())
|
||||
}
|
||||
|
||||
/** the scrollback's rows, 0 without a session */
|
||||
private fun historySize(): Int = session?.let { synchronized(it.emulator) { it.emulator.historySize } } ?: 0
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// drawing
|
||||
|
||||
/** a redraw on the next frame, at most one waiting (any thread) */
|
||||
private fun postRedraw() {
|
||||
if (redrawPosted) return
|
||||
redrawPosted = true
|
||||
@@ -222,6 +229,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
}
|
||||
}
|
||||
|
||||
/** the background, then the visible rows (scrolled back or live) and the cursor if it shows */
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
val s = session
|
||||
val e = s?.emulator
|
||||
@@ -244,6 +252,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
}
|
||||
}
|
||||
|
||||
/** whether the remote turned on reverse video (DECSCNM) */
|
||||
private fun reverse(): Boolean = session?.let { synchronized(it.emulator) { it.emulator.reverseVideo } } ?: false
|
||||
|
||||
/** the emulator being drawn: its own colours (OSC 4, 10, 11) over the theme's */
|
||||
@@ -269,6 +278,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
|
||||
private val runText = StringBuilder()
|
||||
|
||||
/** a line's cells in runs of one look: background, then text, then any images */
|
||||
private fun drawLine(c: Canvas, line: Line, row: Int, y: Float, rev: Boolean) {
|
||||
val cols = min(line.cols, (width / cellW).toInt() + 1)
|
||||
var x = 0
|
||||
@@ -312,6 +322,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
/** the images' bitmaps, made once each (gone with their images) */
|
||||
private val bitmaps = java.util.WeakHashMap<TermImage, android.graphics.Bitmap>()
|
||||
|
||||
/** [img]'s bitmap, made the first time; null if it can't be */
|
||||
private fun bitmapOf(img: TermImage): android.graphics.Bitmap? =
|
||||
bitmaps[img] ?: runCatching {
|
||||
android.graphics.Bitmap.createBitmap(img.pixels, img.width, img.height, android.graphics.Bitmap.Config.ARGB_8888)
|
||||
@@ -337,6 +348,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
resolvedBg = b
|
||||
}
|
||||
|
||||
/** a run's text in [fg] with its attributes: bold, italic, box drawing, wide characters, the underlines, overline and strike */
|
||||
private fun drawText(c: Canvas, line: Line, from: Int, to: Int, y: Float, st: Long, fg: Int) {
|
||||
val a = Style.attrs(st)
|
||||
if (a and Style.INVISIBLE != 0) return
|
||||
@@ -352,6 +364,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
runText.setLength(0)
|
||||
var runStart = from
|
||||
var runCells = 0
|
||||
// the text gathered so far drawn, and a new run from at
|
||||
fun flush(at: Int) {
|
||||
if (runText.isNotEmpty()) drawRun(c, runText, runStart, runCells, y)
|
||||
runText.setLength(0)
|
||||
@@ -468,6 +481,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
/** a column's left edge, on a whole pixel */
|
||||
private fun px(col: Int): Float = kotlin.math.round(col * cellW)
|
||||
|
||||
/** the cursor in the remote's shape (DECSCUSR) or the user's; a block hollow without focus */
|
||||
private fun drawCursor(c: Canvas, e: TerminalEmulator) {
|
||||
val col = min(e.cursorX, e.cols - 1)
|
||||
val x = px(col)
|
||||
@@ -513,28 +527,33 @@ class TerminalView @JvmOverloads constructor(
|
||||
}
|
||||
}
|
||||
|
||||
/** the blink started over, on */
|
||||
private fun restartBlink() {
|
||||
removeCallbacks(blink)
|
||||
blinkOn = true
|
||||
if (isAttachedToWindow) postDelayed(blink, BLINK_MS)
|
||||
}
|
||||
|
||||
/** the blink started */
|
||||
override fun onAttachedToWindow() {
|
||||
super.onAttachedToWindow()
|
||||
restartBlink()
|
||||
}
|
||||
|
||||
/** the blink stopped */
|
||||
override fun onDetachedFromWindow() {
|
||||
removeCallbacks(blink)
|
||||
super.onDetachedFromWindow()
|
||||
}
|
||||
|
||||
/** the cursor redrawn and the remote told (if it asked) of the focus */
|
||||
override fun onFocusChanged(gainFocus: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
|
||||
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect)
|
||||
reportFocus(gainFocus)
|
||||
invalidate()
|
||||
}
|
||||
|
||||
/** the remote told (if it asked) the window's focus */
|
||||
override fun onWindowFocusChanged(hasWindowFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasWindowFocus)
|
||||
reportFocus(hasWindowFocus && hasFocus())
|
||||
@@ -554,6 +573,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
// ------------------------------------------------------------------
|
||||
// the mouse, as the remote asked for it (a tap a click, a drag the wheel)
|
||||
|
||||
/** how the remote asked for the mouse, NONE without a session */
|
||||
private fun mouseMode(): TerminalEmulator.MouseMode =
|
||||
session?.let { synchronized(it.emulator) { it.emulator.mouseMode } } ?: TerminalEmulator.MouseMode.NONE
|
||||
|
||||
@@ -614,11 +634,13 @@ class TerminalView @JvmOverloads constructor(
|
||||
// touch: tap shows the keyboard, drag scrolls back, pinch zooms, long press selects
|
||||
|
||||
private val gestures = GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() {
|
||||
/** a fling stopped by a touch */
|
||||
override fun onDown(e: MotionEvent): Boolean {
|
||||
scroller.forceFinished(true)
|
||||
return true
|
||||
}
|
||||
|
||||
/** a tap: the selection ended, or a link opened, or a click to the remote; the keyboard up */
|
||||
override fun onSingleTapUp(e: MotionEvent): Boolean {
|
||||
if (actionMode != null) {
|
||||
actionMode?.finish()
|
||||
@@ -631,6 +653,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
return true
|
||||
}
|
||||
|
||||
/** a drag: the selection's, else the remote's (wheel, arrows), else the scrollback scrolled */
|
||||
override fun onScroll(e1: MotionEvent?, e2: MotionEvent, dx: Float, dy: Float): Boolean {
|
||||
if (selecting) return true
|
||||
if (scrollRows == 0 && scrollRemote(e2.x, e2.y, dy)) return true
|
||||
@@ -638,6 +661,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
return true
|
||||
}
|
||||
|
||||
/** a fling through the scrollback, unless selecting or the remote takes the drags */
|
||||
override fun onFling(e1: MotionEvent?, e2: MotionEvent, vx: Float, vy: Float): Boolean {
|
||||
if (selecting) return true
|
||||
if (scrollRows == 0 && (mouseMode() != TerminalEmulator.MouseMode.NONE || session?.emulator?.let { synchronized(it) { it.altScreen } } == true)) return true
|
||||
@@ -647,6 +671,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
return true
|
||||
}
|
||||
|
||||
/** a long press: the word under it selected */
|
||||
override fun onLongPress(e: MotionEvent) {
|
||||
if (scale.isInProgress) return
|
||||
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
|
||||
@@ -656,11 +681,13 @@ class TerminalView @JvmOverloads constructor(
|
||||
|
||||
private val scale = ScaleGestureDetector(context, object : ScaleGestureDetector.SimpleOnScaleGestureListener() {
|
||||
private var startSp = 0f
|
||||
/** the font size the pinch starts from (sp) kept */
|
||||
override fun onScaleBegin(detector: ScaleGestureDetector): Boolean {
|
||||
startSp = fontPx / resources.displayMetrics.scaledDensity()
|
||||
return true
|
||||
}
|
||||
|
||||
/** the font resized with the pinch, fixed columns off */
|
||||
override fun onScale(detector: ScaleGestureDetector): Boolean {
|
||||
val sp = (fontPx / resources.displayMetrics.scaledDensity() * detector.scaleFactor).coerceIn(MIN_SP, MAX_SP)
|
||||
settings = settings.copy(fontSize = sp, fixedColumns = 0)
|
||||
@@ -670,11 +697,13 @@ class TerminalView @JvmOverloads constructor(
|
||||
return true
|
||||
}
|
||||
|
||||
/** the pinched size to [onFontSizeChanged] if it changed */
|
||||
override fun onScaleEnd(detector: ScaleGestureDetector) {
|
||||
if (startSp != settings.fontSize) onFontSizeChanged?.invoke(settings.fontSize)
|
||||
}
|
||||
})
|
||||
|
||||
/** the pixels of 1 sp */
|
||||
private fun android.util.DisplayMetrics.scaledDensity(): Float =
|
||||
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 1f, this)
|
||||
|
||||
@@ -706,6 +735,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
return true
|
||||
}
|
||||
|
||||
/** the fling's next step: the rows scrolled back to where it is */
|
||||
override fun computeScroll() {
|
||||
if (scroller.computeScrollOffset()) {
|
||||
val rows = (scroller.currY / cellH).toInt().coerceIn(0, historySize())
|
||||
@@ -717,6 +747,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
}
|
||||
}
|
||||
|
||||
/** the scrollback moved by a drag of [dy] pixels, in whole rows */
|
||||
private fun scrollBy(dy: Float) {
|
||||
scrollRemainder += -dy / cellH
|
||||
val n = scrollRemainder.toInt()
|
||||
@@ -749,6 +780,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
// ------------------------------------------------------------------
|
||||
// the selection
|
||||
|
||||
/** whether the cell is in the selection (while there is one) */
|
||||
private fun isSelected(row: Int, col: Int): Boolean {
|
||||
if (actionMode == null && !selecting) return false
|
||||
val startFirst = selStartRow < selEndRow || (selStartRow == selEndRow && selStartCol <= selEndCol)
|
||||
@@ -762,6 +794,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
return true
|
||||
}
|
||||
|
||||
/** the selection's ends in order: start row, start col, end row, end col */
|
||||
private fun ordered(): List<Int> =
|
||||
if (selStartRow < selEndRow || (selStartRow == selEndRow && selStartCol <= selEndCol)) {
|
||||
listOf(selStartRow, selStartCol, selEndRow, selEndCol)
|
||||
@@ -769,6 +802,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
listOf(selEndRow, selEndCol, selStartRow, selStartCol)
|
||||
}
|
||||
|
||||
/** the word at the point selected and the selection's menu up, the link there kept */
|
||||
private fun startSelection(x: Float, y: Float) {
|
||||
val s = session ?: return
|
||||
val (row, col) = cellAt(x, y)
|
||||
@@ -777,6 +811,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
val l = s.emulator.line(row)
|
||||
var a = col
|
||||
var b = col
|
||||
// whether the cell at i is part of a word (not empty or a space)
|
||||
fun word(i: Int) = l.chars[i] != 0 && l.chars[i] != ' '.code
|
||||
if (word(col)) {
|
||||
while (a > 0 && word(a - 1)) a--
|
||||
@@ -791,6 +826,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
invalidate()
|
||||
}
|
||||
|
||||
/** the selection's text, its lines joined */
|
||||
private fun selectedText(): String {
|
||||
val s = session ?: return ""
|
||||
val (r1, c1, r2, c2) = ordered()
|
||||
@@ -798,6 +834,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
}
|
||||
|
||||
private val selectionCallback = object : ActionMode.Callback2() {
|
||||
/** the menu: copy, paste, select all, open link, share */
|
||||
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
|
||||
menu.add(0, ID_COPY, 0, "Copy")
|
||||
menu.add(0, ID_PASTE, 1, "Paste")
|
||||
@@ -807,12 +844,14 @@ class TerminalView @JvmOverloads constructor(
|
||||
return true
|
||||
}
|
||||
|
||||
/** "Open link" shown only if there is one at the press or in the selection */
|
||||
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
|
||||
val link = linkAtPress ?: UrlFinder.all(selectedText()).firstOrNull()
|
||||
menu.findItem(ID_LINK)?.isVisible = link != null
|
||||
return true
|
||||
}
|
||||
|
||||
/** the menu's item done: copy, paste, select all, open the link, share */
|
||||
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
|
||||
when (item.itemId) {
|
||||
ID_COPY -> {
|
||||
@@ -848,6 +887,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
return true
|
||||
}
|
||||
|
||||
/** the selection gone */
|
||||
override fun onDestroyActionMode(mode: ActionMode) {
|
||||
actionMode = null
|
||||
selecting = false
|
||||
@@ -855,6 +895,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
invalidate()
|
||||
}
|
||||
|
||||
/** the selection's rows, for the menu to float by */
|
||||
override fun onGetContentRect(mode: ActionMode, view: View, outRect: Rect) {
|
||||
val (r1, _, r2, _) = ordered()
|
||||
val top = ((r1 + scrollRows) * cellH).toInt()
|
||||
@@ -863,6 +904,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
}
|
||||
}
|
||||
|
||||
/** [text] on the clipboard */
|
||||
private fun copy(text: String) {
|
||||
val cm = context.getSystemService(ClipboardManager::class.java)
|
||||
cm.setPrimaryClip(ClipData.newPlainText("terminal", text))
|
||||
@@ -878,6 +920,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
}
|
||||
}
|
||||
|
||||
/** [url] opened in an app for it, if there is one */
|
||||
private fun openLink(url: String) {
|
||||
try {
|
||||
context.startActivity(Intent(Intent.ACTION_VIEW, url.toUri()).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
@@ -888,15 +931,18 @@ class TerminalView @JvmOverloads constructor(
|
||||
// ------------------------------------------------------------------
|
||||
// the keyboard
|
||||
|
||||
/** the soft keyboard up, the view focused */
|
||||
fun showKeyboard() {
|
||||
requestFocus()
|
||||
context.getSystemService(InputMethodManager::class.java).showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
|
||||
}
|
||||
|
||||
/** the soft keyboard down */
|
||||
fun hideKeyboard() {
|
||||
context.getSystemService(InputMethodManager::class.java).hideSoftInputFromWindow(windowToken, 0)
|
||||
}
|
||||
|
||||
/** the soft keyboard down if it shows, else up */
|
||||
fun toggleKeyboard() {
|
||||
val imm = context.getSystemService(InputMethodManager::class.java)
|
||||
val insets = rootWindowInsets
|
||||
@@ -905,8 +951,10 @@ class TerminalView @JvmOverloads constructor(
|
||||
if (visible) imm.hideSoftInputFromWindow(windowToken, 0) else showKeyboard()
|
||||
}
|
||||
|
||||
/** a text editor: the soft keyboard is for it */
|
||||
override fun onCheckIsTextEditor(): Boolean = true
|
||||
|
||||
/** keys straight through: no suggestions, corrections or full screen editor; the typed text sent as it comes */
|
||||
override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection {
|
||||
// no suggestions, no corrections, no full screen editor: keys straight through
|
||||
outAttrs.inputType = InputType.TYPE_CLASS_TEXT or
|
||||
@@ -916,18 +964,21 @@ class TerminalView @JvmOverloads constructor(
|
||||
EditorInfo.IME_FLAG_NO_FULLSCREEN or
|
||||
EditorInfo.IME_ACTION_NONE
|
||||
return object : BaseInputConnection(this, true) {
|
||||
/** the text committed sent */
|
||||
override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean {
|
||||
super.commitText(text, newCursorPosition)
|
||||
flush()
|
||||
return true
|
||||
}
|
||||
|
||||
/** the composing text sent */
|
||||
override fun finishComposingText(): Boolean {
|
||||
super.finishComposingText()
|
||||
flush()
|
||||
return true
|
||||
}
|
||||
|
||||
/** a backspace to the remote for each character deleted once the editor is empty */
|
||||
override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean {
|
||||
val ed = editable
|
||||
if (ed == null || ed.isEmpty()) {
|
||||
@@ -938,11 +989,13 @@ class TerminalView @JvmOverloads constructor(
|
||||
return super.deleteSurroundingText(beforeLength, afterLength)
|
||||
}
|
||||
|
||||
/** a key from the keyboard as if pressed */
|
||||
override fun sendKeyEvent(event: KeyEvent): Boolean {
|
||||
if (event.action == KeyEvent.ACTION_DOWN) onKeyDown(event.keyCode, event)
|
||||
return true
|
||||
}
|
||||
|
||||
/** the editor's text sent (typed) and cleared */
|
||||
private fun flush() {
|
||||
val ed = editable ?: return
|
||||
val text = ed.toString()
|
||||
@@ -955,11 +1008,13 @@ class TerminalView @JvmOverloads constructor(
|
||||
}
|
||||
}
|
||||
|
||||
/** [k] sent with its modifiers, back on the live screen */
|
||||
private fun typed(k: Key, shift: Boolean = false, alt: Boolean = false, ctrl: Boolean = false) {
|
||||
scrollToBottom()
|
||||
session?.sendKey(k, shift, alt, ctrl)
|
||||
}
|
||||
|
||||
/** a key: the volume keys as set (font size, Ctrl/Alt), Shift+PgUp/PgDn the scrollback, the rest to the remote */
|
||||
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
|
||||
val s = session ?: return super.onKeyDown(keyCode, event)
|
||||
when (keyCode) {
|
||||
@@ -1034,6 +1089,7 @@ class TerminalView @JvmOverloads constructor(
|
||||
|
||||
private var flashing = false
|
||||
|
||||
/** the view, and the bell's flash over it */
|
||||
override fun draw(canvas: Canvas) {
|
||||
super.draw(canvas)
|
||||
if (flashing) {
|
||||
|
||||
@@ -46,6 +46,7 @@ class DownloadsIncoming(context: Context) : Incoming {
|
||||
return out.asSink() to actual
|
||||
}
|
||||
|
||||
/** [name] finished: no longer pending in Downloads, its time set if known */
|
||||
override fun done(name: String, mtime: Long) {
|
||||
if (Build.VERSION.SDK_INT < 29) return folder!!.done(name, mtime)
|
||||
val uri = synchronized(pending) { pending.remove(name) } ?: return
|
||||
@@ -56,6 +57,7 @@ class DownloadsIncoming(context: Context) : Incoming {
|
||||
runCatching { ctx.contentResolver.update(uri, v, null, null) }
|
||||
}
|
||||
|
||||
/** [name]'s unfinished file deleted */
|
||||
override fun abandon(name: String) {
|
||||
if (Build.VERSION.SDK_INT < 29) return folder!!.abandon(name)
|
||||
val uri = synchronized(pending) { pending.remove(name) } ?: return
|
||||
|
||||
@@ -55,6 +55,7 @@ fun AppearanceSection() {
|
||||
val scope = rememberCoroutineScope()
|
||||
val current by store.appearance.collectAsStateWithLifecycle(initialValue = null)
|
||||
val a = current ?: return
|
||||
/** [change] applied to the stored appearance */
|
||||
fun set(change: (Appearance) -> Appearance) {
|
||||
scope.launch { store.update(change) }
|
||||
}
|
||||
@@ -96,6 +97,7 @@ fun AppearanceSection() {
|
||||
}
|
||||
}
|
||||
|
||||
/** a palette's swatch to pick: its primary in its tertiary container, ringed and ticked when [selected] */
|
||||
@Composable
|
||||
private fun Swatch(p: AppPalette, selected: Boolean, onPick: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
|
||||
@@ -54,6 +54,7 @@ fun BridgeSection() {
|
||||
val scope = rememberCoroutineScope()
|
||||
val current by store.settings.collectAsStateWithLifecycle(initialValue = null)
|
||||
val s = current ?: return
|
||||
/** [f] applied to the stored settings, the internet host's service brought in line with them */
|
||||
fun change(f: (BridgeSettings) -> BridgeSettings) {
|
||||
scope.launch {
|
||||
store.update(f)
|
||||
@@ -187,6 +188,7 @@ fun BridgeSection() {
|
||||
}
|
||||
}
|
||||
|
||||
/** the TCP bridge's state, as a line */
|
||||
private fun tcpText(st: TcpBridge.State, s: BridgeSettings): String = when (st) {
|
||||
TcpBridge.State.Stopped -> "Starts with the modem"
|
||||
is TcpBridge.State.Listening -> "Listening on " + (if (s.tcpAnyAddress) "port" else "localhost port") + " ${st.port}" +
|
||||
@@ -194,6 +196,7 @@ private fun tcpText(st: TcpBridge.State, s: BridgeSettings): String = when (st)
|
||||
is TcpBridge.State.Failed -> "Can't listen: ${st.why}"
|
||||
}
|
||||
|
||||
/** the USB bridge's state, as a line */
|
||||
private fun usbText(st: com.neodesktop.dmodem.bridge.UsbBridge.State): String = when (st) {
|
||||
com.neodesktop.dmodem.bridge.UsbBridge.State.Stopped -> "Starts with the modem"
|
||||
com.neodesktop.dmodem.bridge.UsbBridge.State.Waiting -> "Waiting for an adapter to be plugged in"
|
||||
@@ -202,6 +205,7 @@ private fun usbText(st: com.neodesktop.dmodem.bridge.UsbBridge.State): String =
|
||||
is com.neodesktop.dmodem.bridge.UsbBridge.State.Failed -> st.why
|
||||
}
|
||||
|
||||
/** the USB gadget's state, as a line */
|
||||
private fun gadgetText(st: com.neodesktop.dmodem.bridge.UsbGadget.State): String = when (st) {
|
||||
com.neodesktop.dmodem.bridge.UsbGadget.State.Stopped -> "Starts with the modem"
|
||||
com.neodesktop.dmodem.bridge.UsbGadget.State.Ready -> "Ready: the computer sees a modem on its USB (COM port, /dev/ttyACM0)"
|
||||
@@ -209,6 +213,7 @@ private fun gadgetText(st: com.neodesktop.dmodem.bridge.UsbGadget.State): String
|
||||
is com.neodesktop.dmodem.bridge.UsbGadget.State.Failed -> st.why
|
||||
}
|
||||
|
||||
/** the Bluetooth bridge's state, as a line */
|
||||
private fun btText(st: BluetoothBridge.State): String = when (st) {
|
||||
BluetoothBridge.State.Stopped -> "Starts with the modem"
|
||||
is BluetoothBridge.State.Listening -> "Waiting for a device to connect to \"${st.name}\""
|
||||
@@ -290,6 +295,7 @@ private fun PicoBoardPanel(b: PicoBoard) {
|
||||
private fun lines(bits: Int, names: List<Pair<Int, String>>): String =
|
||||
names.filter { bits and it.first != 0 }.joinToString(" ") { it.second }.ifEmpty { "none" }
|
||||
|
||||
/** a labelled switch */
|
||||
@Composable
|
||||
private fun Toggle(label: String, value: Boolean, onChange: (Boolean) -> Unit) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
@@ -298,6 +304,7 @@ private fun Toggle(label: String, value: Boolean, onChange: (Boolean) -> Unit) {
|
||||
}
|
||||
}
|
||||
|
||||
/** a labelled radio button, the whole row tappable */
|
||||
@Composable
|
||||
private fun Choice(label: String, selected: Boolean, onClick: () -> Unit) {
|
||||
Row(Modifier.fillMaxWidth().clickable(onClick = onClick), verticalAlignment = Alignment.CenterVertically) {
|
||||
|
||||
@@ -196,6 +196,7 @@ private val Online = Color(0xff2e7d32)
|
||||
private val Busy = Color(0xffef6c00)
|
||||
private val Off = Color(0xff757575)
|
||||
|
||||
/** the modem's state at the top: a dot and a title, the call's time and rates, any error, and the button for what's next */
|
||||
@Composable
|
||||
private fun HeroCard(
|
||||
run: ModemState.Run,
|
||||
@@ -279,6 +280,7 @@ private fun HeroCard(
|
||||
}
|
||||
}
|
||||
|
||||
/** a rate in big figures: bit/s, or kbit/s from 1000 */
|
||||
@Composable
|
||||
private fun Rate(label: String, bps: Int) {
|
||||
Column {
|
||||
@@ -293,6 +295,7 @@ private fun Rate(label: String, bps: Int) {
|
||||
}
|
||||
}
|
||||
|
||||
/** the line the modem calls on (none, another phone, a Bluetooth or USB modem, SIP) and how it is; a tap to its settings */
|
||||
@Composable
|
||||
private fun LineCard(s: ModemSettings, run: ModemState.Run, network: String?, onSettings: () -> Unit) {
|
||||
Card(Modifier.fillMaxWidth().clickable(onClick = onSettings)) {
|
||||
@@ -349,6 +352,7 @@ private fun PeerLineRows(s: ModemSettings, run: ModemState.Run, network: String?
|
||||
error?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) }
|
||||
}
|
||||
|
||||
/** a label and its value, on one line */
|
||||
@Composable
|
||||
private fun InfoRow(label: String, value: String) {
|
||||
Row {
|
||||
@@ -357,6 +361,7 @@ private fun InfoRow(label: String, value: String) {
|
||||
}
|
||||
}
|
||||
|
||||
/** a section's heading, with an action button on the right if [action] is given */
|
||||
@Composable
|
||||
private fun SectionTitle(text: String, action: String? = null, onAction: () -> Unit = {}) {
|
||||
Row(Modifier.fillMaxWidth().padding(top = 4.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
@@ -365,6 +370,7 @@ private fun SectionTitle(text: String, action: String? = null, onAction: () -> U
|
||||
}
|
||||
}
|
||||
|
||||
/** a directory entry to dial (or open) with a tap: its initial, name, address and when it was last dialled */
|
||||
@Composable
|
||||
private fun QuickDial(e: DialEntry, enabled: Boolean, onDial: () -> Unit) {
|
||||
Card(Modifier.fillMaxWidth()) {
|
||||
@@ -391,6 +397,7 @@ private fun QuickDial(e: DialEntry, enabled: Boolean, onDial: () -> Unit) {
|
||||
}
|
||||
}
|
||||
|
||||
/** a card to tap: a glyph (or [icon]), a title and a line under it */
|
||||
@Composable
|
||||
private fun Shortcut(
|
||||
glyph: String?,
|
||||
@@ -462,10 +469,12 @@ private fun rememberNetwork(context: Context): String? {
|
||||
DisposableEffect(Unit) {
|
||||
val cm = context.getSystemService(ConnectivityManager::class.java)
|
||||
val cb = object : ConnectivityManager.NetworkCallback() {
|
||||
/** the network's name again as it changes */
|
||||
override fun onCapabilitiesChanged(network: Network, caps: NetworkCapabilities) {
|
||||
name = networkName(context, caps)
|
||||
}
|
||||
|
||||
/** no network */
|
||||
override fun onLost(network: Network) {
|
||||
name = null
|
||||
}
|
||||
@@ -484,6 +493,7 @@ private fun rememberNetwork(context: Context): String? {
|
||||
return name
|
||||
}
|
||||
|
||||
/** the network as words (Wi-Fi, Ethernet, Mobile data, VPN), from [given] or the active one's; null without one */
|
||||
private fun networkName(context: Context, given: NetworkCapabilities?): String? {
|
||||
val cm = context.getSystemService(ConnectivityManager::class.java) ?: return null
|
||||
val caps = given ?: cm.activeNetwork?.let { cm.getNetworkCapabilities(it) } ?: return null
|
||||
|
||||
@@ -152,6 +152,7 @@ fun DirectoryScreen(modifier: Modifier = Modifier, onDialed: () -> Unit) {
|
||||
}
|
||||
}
|
||||
|
||||
/** a directory entry edited (or a new one): how it's reached and its details; Save only once it's [DialEntry.complete] */
|
||||
@Composable
|
||||
internal fun EntryDialog(entry: DialEntry, onSave: (DialEntry) -> Unit, onDismiss: () -> Unit) {
|
||||
var e by remember(entry.id) { mutableStateOf(entry) }
|
||||
|
||||
@@ -83,6 +83,7 @@ fun FaxSection() {
|
||||
}
|
||||
}
|
||||
|
||||
/** the fax call now or just ended: which way, its phase or outcome, its progress; cancel, or open and dismiss */
|
||||
@Composable
|
||||
private fun FaxCallCard(st: Fax.State) {
|
||||
val context = LocalContext.current
|
||||
@@ -115,6 +116,7 @@ private fun FaxCallCard(st: Fax.State) {
|
||||
}
|
||||
}
|
||||
|
||||
/** a fax in the log: which way, with whom, pages, when and how it ended; a tap opens it */
|
||||
@Composable
|
||||
private fun FaxRow(r: FaxRecord) {
|
||||
val context = LocalContext.current
|
||||
|
||||
@@ -53,6 +53,7 @@ fun InternetCard(onSetUp: () -> Unit) {
|
||||
val state by Internet.state.collectAsStateWithLifecycle()
|
||||
val run by ModemState.run.collectAsStateWithLifecycle()
|
||||
|
||||
/** the ISP dialled with the stored settings, its packets through the VPN; why not, if it can't, in a toast */
|
||||
fun dial() {
|
||||
val app = context.applicationContext
|
||||
scope.launch {
|
||||
@@ -143,6 +144,7 @@ private fun DialInRows(d: DialIn.State) {
|
||||
}
|
||||
}
|
||||
|
||||
/** a byte count in B, KB or MB */
|
||||
private fun size(n: Long) = when {
|
||||
n < 1024 -> "$n B"
|
||||
n < 1024 * 1024 -> "%.1f KB".format(n / 1024.0)
|
||||
|
||||
@@ -161,6 +161,7 @@ fun LinuxSection(onOpened: () -> Unit = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
/** what Linux is doing: its step with a progress bar, or why it failed; nothing when idle */
|
||||
@Composable
|
||||
private fun WorkLine(work: Linux.Work) {
|
||||
when (work) {
|
||||
@@ -284,6 +285,7 @@ fun PickLinuxDialog(systems: List<LinuxSystem>, onPick: (LinuxSystem) -> Unit, o
|
||||
)
|
||||
}
|
||||
|
||||
/** a radio button with a title and a line about it, greyed when not [enabled] */
|
||||
@Composable
|
||||
private fun Choice(title: String, about: String, selected: Boolean, enabled: Boolean, onPick: () -> Unit) {
|
||||
Row(
|
||||
@@ -300,6 +302,7 @@ private fun Choice(title: String, about: String, selected: Boolean, enabled: Boo
|
||||
|
||||
private const val CUSTOM = "\u0000custom"
|
||||
|
||||
/** a size in GB, MB or KB */
|
||||
private fun formatSize(b: Long): String = when {
|
||||
b >= 1L shl 30 -> "%.1f GB".format(b / (1L shl 30).toDouble())
|
||||
b >= 1L shl 20 -> "%.0f MB".format(b / (1L shl 20).toDouble())
|
||||
|
||||
@@ -50,6 +50,7 @@ class MainActivity : ComponentActivity() {
|
||||
private val askPermissions =
|
||||
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { }
|
||||
|
||||
/** the app's screen: permissions asked, the internet host's service resumed, a call's notification handled, the tabs in the app's theme */
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
// (a fresh start: Settings at its menu)
|
||||
@@ -157,6 +158,7 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
/** a call's notification tapped while the app is open: handled as at the start */
|
||||
override fun onNewIntent(intent: android.content.Intent) {
|
||||
super.onNewIntent(intent)
|
||||
handleCall(intent)
|
||||
@@ -185,6 +187,7 @@ class MainActivity : ComponentActivity() {
|
||||
i.action = null
|
||||
}
|
||||
|
||||
/** the incoming call answered as a fax: its ringing ended, the fax shown on the modem's tab (why not, in a toast) */
|
||||
private fun answerAsFax() {
|
||||
com.neodesktop.dmodem.modem.ModemState.incoming.end()
|
||||
val why = com.neodesktop.dmodem.fax.Fax.answer(this)
|
||||
@@ -212,6 +215,7 @@ class MainActivity : ComponentActivity() {
|
||||
runCatching { ui.setApplicationNightMode(want) }
|
||||
}
|
||||
|
||||
/** the status and navigation bars shown, or hidden until a swipe (the terminal's full screen) */
|
||||
private fun setSystemBars(show: Boolean) {
|
||||
val c = WindowCompat.getInsetsController(window, window.decorView)
|
||||
if (show) {
|
||||
@@ -236,6 +240,7 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
/** a tab of the navigation bar */
|
||||
@androidx.compose.runtime.Composable
|
||||
private fun androidx.compose.foundation.layout.RowScope.Item(
|
||||
selected: Boolean,
|
||||
|
||||
@@ -56,6 +56,7 @@ data class Lights(
|
||||
val sd: Boolean = false,
|
||||
val arq: Boolean = false,
|
||||
) {
|
||||
/** the lights with their legends, in the panel's order */
|
||||
fun list() = listOf("MR" to mr, "TR" to tr, "CS" to cs, "AA" to aa, "CD" to cd, "OH" to oh, "RD" to rd, "SD" to sd, "ARQ/FAX" to arq)
|
||||
}
|
||||
|
||||
|
||||
@@ -177,6 +177,7 @@ fun PeerLineFields(s: ModemSettings, onChange: (ModemSettings) -> Unit) {
|
||||
}
|
||||
}
|
||||
|
||||
/** the other phone on Wi-Fi: its address (typed, or found on the network), the port calls come in on, this phone's addresses */
|
||||
@Composable
|
||||
private fun WifiPeer(s: ModemSettings, onChange: (ModemSettings) -> Unit) {
|
||||
val context = LocalContext.current
|
||||
@@ -242,6 +243,7 @@ private fun WifiPeer(s: ModemSettings, onChange: (ModemSettings) -> Unit) {
|
||||
}
|
||||
}
|
||||
|
||||
/** the other phone on Bluetooth: chosen from the paired devices */
|
||||
@Composable
|
||||
private fun BluetoothPeer(s: ModemSettings, onChange: (ModemSettings) -> Unit, context: android.content.Context) {
|
||||
var picking by remember { mutableStateOf(false) }
|
||||
@@ -305,6 +307,7 @@ fun BluetoothModemFields(s: ModemSettings, onChange: (ModemSettings) -> Unit) {
|
||||
}
|
||||
}
|
||||
|
||||
/** a labelled radio button, the whole row tappable */
|
||||
@Composable
|
||||
private fun LineRadio(label: String, selected: Boolean, onClick: () -> Unit) {
|
||||
Row(Modifier.fillMaxWidth().clickable(onClick = onClick), verticalAlignment = Alignment.CenterVertically) {
|
||||
|
||||
@@ -53,6 +53,7 @@ fun PromptHost() {
|
||||
}
|
||||
}
|
||||
|
||||
/** a new or changed host key's question: its fingerprint (and the kept one's, if changed); accept and keep, once, or cancel */
|
||||
@Composable
|
||||
private fun HostKeyDialog(q: Prompt.HostKey) {
|
||||
val changed = q.oldFingerprint != null
|
||||
@@ -93,6 +94,7 @@ private fun HostKeyDialog(q: Prompt.HostKey) {
|
||||
)
|
||||
}
|
||||
|
||||
/** a password asked for, with Remember when it can be kept */
|
||||
@Composable
|
||||
private fun PasswordDialog(q: Prompt.Password) {
|
||||
var text by remember(q) { mutableStateOf("") }
|
||||
@@ -128,6 +130,7 @@ private fun PasswordDialog(q: Prompt.Password) {
|
||||
)
|
||||
}
|
||||
|
||||
/** the server's questions, each in its field (hidden unless it echoes) */
|
||||
@Composable
|
||||
private fun QuestionsDialog(q: Prompt.Questions) {
|
||||
val answers = remember(q) { q.questions.map { mutableStateOf("") } }
|
||||
|
||||
@@ -13,6 +13,7 @@ import androidx.compose.ui.unit.dp
|
||||
* so as not to take the whole extended set for nine of them.
|
||||
*/
|
||||
object SettingsIcons {
|
||||
/** a 24 dp icon of [paths] (SVG path data) filled black */
|
||||
private fun icon(name: String, vararg paths: String): ImageVector =
|
||||
ImageVector.Builder(name, 24.dp, 24.dp, 24f, 24f).apply {
|
||||
for (p in paths) addPath(addPathNodes(p), fill = SolidColor(androidx.compose.ui.graphics.Color.Black))
|
||||
|
||||
@@ -76,6 +76,7 @@ enum class SettingsPage(val title: String) {
|
||||
object SettingsNav {
|
||||
val page = kotlinx.coroutines.flow.MutableStateFlow<SettingsPage?>(null)
|
||||
|
||||
/** [p] opened (null: the menu) */
|
||||
fun open(p: SettingsPage?) {
|
||||
page.value = p
|
||||
}
|
||||
@@ -114,6 +115,7 @@ fun SettingsScreen(modifier: Modifier = Modifier, onOpenTerminal: () -> Unit = {
|
||||
return
|
||||
}
|
||||
|
||||
/** the line's and the modem's Save button, and whether they're saved (and need a restart to apply) */
|
||||
@Composable
|
||||
fun SaveRow() {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
@@ -304,6 +306,7 @@ private fun lineSummary(s: ModemSettings): String = when (s.line) {
|
||||
else -> if (s.complete) "SIP: ${s.user}@${s.domain}" + (if (s.listen) ", taking calls" else "") else "SIP: no account set up yet"
|
||||
}
|
||||
|
||||
/** a one-line text field */
|
||||
@Composable
|
||||
private fun Field(label: String, value: String, onChange: (String) -> Unit) {
|
||||
OutlinedTextField(
|
||||
@@ -312,6 +315,7 @@ private fun Field(label: String, value: String, onChange: (String) -> Unit) {
|
||||
)
|
||||
}
|
||||
|
||||
/** a number field taking a sign and up to three digits */
|
||||
@Composable
|
||||
private fun SignedNumberField(label: String, value: Int, onChange: (Int) -> Unit) {
|
||||
var text by remember(value) { mutableStateOf(value.toString()) }
|
||||
@@ -329,6 +333,7 @@ private fun SignedNumberField(label: String, value: Int, onChange: (Int) -> Unit
|
||||
)
|
||||
}
|
||||
|
||||
/** a number field taking up to five digits */
|
||||
@Composable
|
||||
private fun NumberField(label: String, value: Int, onChange: (Int) -> Unit) {
|
||||
var text by remember(value) { mutableStateOf(value.toString()) }
|
||||
@@ -345,6 +350,7 @@ private fun NumberField(label: String, value: Int, onChange: (Int) -> Unit) {
|
||||
)
|
||||
}
|
||||
|
||||
/** a labelled switch */
|
||||
@Composable
|
||||
private fun Toggle(label: String, value: Boolean, onChange: (Boolean) -> Unit) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
|
||||
@@ -107,6 +107,7 @@ fun SshKeysSection() {
|
||||
}
|
||||
}
|
||||
|
||||
/** a new key made: its name, type and comment, with the ssh-keygen line for the same; any failure in a toast */
|
||||
@Composable
|
||||
private fun GenerateDialog(onDone: () -> Unit) {
|
||||
val scope = rememberCoroutineScope()
|
||||
@@ -150,6 +151,7 @@ private fun GenerateDialog(onDone: () -> Unit) {
|
||||
)
|
||||
}
|
||||
|
||||
/** a private key imported from a file or pasted (OpenSSH, PuTTY or PEM), with its passphrase; closed once it's read */
|
||||
@Composable
|
||||
private fun ImportDialog(onDone: () -> Unit) {
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
@@ -405,6 +405,7 @@ private fun Disconnected(reason: String?, local: Boolean, onReconnect: () -> Uni
|
||||
}
|
||||
}
|
||||
|
||||
/** the bar's line: the modem's state (online with its rates and the call's time), then the window's title if any */
|
||||
private fun barText(
|
||||
run: ModemState.Run,
|
||||
st: NativeModem.Status,
|
||||
@@ -426,6 +427,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, paste, new shells, files, character set, clear, reset, full screen) */
|
||||
@Composable
|
||||
private fun TopBar(
|
||||
text: String,
|
||||
@@ -541,6 +543,7 @@ private fun ExtraKeys(
|
||||
}
|
||||
}
|
||||
|
||||
/** a row of the extra keys, 40 dp high */
|
||||
@Composable
|
||||
private fun KeyRow(content: @Composable androidx.compose.foundation.layout.RowScope.() -> Unit) {
|
||||
Row(Modifier.fillMaxWidth().height(40.dp), horizontalArrangement = Arrangement.spacedBy(2.dp), content = content)
|
||||
@@ -590,6 +593,7 @@ private fun androidx.compose.foundation.layout.RowScope.KeyButton(
|
||||
private const val REPEAT_DELAY_MS = 400L
|
||||
private const val REPEAT_MS = 60L
|
||||
|
||||
/** the bell as a 60 ms vibration */
|
||||
private fun vibrate(context: Context) {
|
||||
val v: Vibrator = if (android.os.Build.VERSION.SDK_INT >= 31) {
|
||||
context.getSystemService(VibratorManager::class.java).defaultVibrator
|
||||
|
||||
@@ -58,6 +58,7 @@ fun TerminalSettingsSection() {
|
||||
val scope = rememberCoroutineScope()
|
||||
val current by store.settings.collectAsStateWithLifecycle(initialValue = null)
|
||||
val s = current ?: return
|
||||
/** [change] applied to the stored terminal settings */
|
||||
fun set(change: (TerminalSettings) -> TerminalSettings) {
|
||||
scope.launch { store.update(change) }
|
||||
}
|
||||
@@ -117,6 +118,7 @@ fun TerminalSettingsSection() {
|
||||
}
|
||||
}
|
||||
|
||||
/** a labelled switch */
|
||||
@Composable
|
||||
private fun Flag(label: String, value: Boolean, onChange: (Boolean) -> Unit) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
|
||||
@@ -28,6 +28,7 @@ fun isDark(a: Appearance): Boolean = when (a.dark) {
|
||||
DarkMode.DARK -> true
|
||||
}
|
||||
|
||||
/** the app's Material theme: the wallpaper's colours (Android 12 on) or the palette's, light or dark, on black if asked */
|
||||
@Composable
|
||||
fun DModemTheme(appearance: Appearance = Appearance(), content: @Composable () -> Unit) {
|
||||
val dark = isDark(appearance)
|
||||
@@ -66,6 +67,7 @@ object Palettes {
|
||||
return Color(rgb[0].toFloat(), rgb[1].toFloat(), rgb[2].toFloat())
|
||||
}
|
||||
|
||||
/** sRGB (0..1 each) of L* [l], chroma [c] and hue [hDeg] in CIE LCh(ab), D65; null if outside sRGB */
|
||||
private fun rgbOf(l: Double, c: Double, hDeg: Double): DoubleArray? {
|
||||
val h = Math.toRadians(hDeg)
|
||||
val a = c * cos(h)
|
||||
@@ -73,6 +75,7 @@ object Palettes {
|
||||
val fy = (l + 16) / 116
|
||||
val fx = fy + a / 500
|
||||
val fz = fy - b / 200
|
||||
/** CIE Lab's f inverted: t cubed, or its linear part near black */
|
||||
fun inv(t: Double) = if (t * t * t > 216.0 / 24389) t * t * t else (116 * t - 16) / (24389.0 / 27)
|
||||
val x = 0.95047 * inv(fx)
|
||||
val y = if (l > 8) fy * fy * fy else l / (24389.0 / 27)
|
||||
@@ -91,9 +94,11 @@ object Palettes {
|
||||
}
|
||||
|
||||
private class Tones(val h: Double, val c: Double) {
|
||||
/** the colour at tone [t] of this hue and chroma */
|
||||
operator fun invoke(t: Int) = lch(t.toDouble(), c, h)
|
||||
}
|
||||
|
||||
/** the Material light or dark scheme of [p]'s hue: each role its tone of the palette's tonal palettes */
|
||||
fun scheme(p: AppPalette, dark: Boolean): ColorScheme {
|
||||
val a = Tones(p.hue, p.chroma)
|
||||
val b = Tones(p.hue, (p.chroma / 3).coerceAtMost(16.0))
|
||||
@@ -132,6 +137,7 @@ object Palettes {
|
||||
|
||||
/** a dark scheme on black: the surfaces black, their containers a step up each */
|
||||
fun black(s: ColorScheme): ColorScheme {
|
||||
/** a grey of level [by] (0..1) */
|
||||
fun up(by: Float) = Color(by, by, by)
|
||||
return s.copy(
|
||||
background = Color.Black, surface = Color.Black, surfaceDim = Color.Black,
|
||||
|
||||
@@ -147,6 +147,7 @@ fun TransferBanner(t: TransferState, savedTo: String, onCancel: () -> Unit, onDi
|
||||
}
|
||||
}
|
||||
|
||||
/** a byte count in B, KB or MB */
|
||||
private fun sizeText(n: Long): String = when {
|
||||
n < 1024 -> "$n B"
|
||||
n < 1024 * 1024 -> "%.1f KB".format(n / 1024.0)
|
||||
|
||||
@@ -25,6 +25,7 @@ fun rememberUsbModemsPlugged(): String {
|
||||
var plugged by remember { mutableStateOf(UsbModems.describe(context)) }
|
||||
DisposableEffect(context) {
|
||||
val r = object : BroadcastReceiver() {
|
||||
/** a USB device attached or detached: the plugged-in modems looked at again, without the one just gone */
|
||||
override fun onReceive(c: Context, i: Intent) {
|
||||
@Suppress("DEPRECATION")
|
||||
val d = i.getParcelableExtra<UsbDevice>(UsbManager.EXTRA_DEVICE)
|
||||
|
||||
@@ -7,18 +7,21 @@ import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class BuildInfoTest {
|
||||
/** a release build says its version and the two commits, nothing more */
|
||||
@Test
|
||||
fun releaseIsPlain() = assertEquals(
|
||||
"D-Modem 0.1.0 03a196a (D-Modem-RE e2b9d1c)",
|
||||
BuildInfo.describe("0.1.0", "03a196a", "e2b9d1c", "release", ""),
|
||||
)
|
||||
|
||||
/** a dirty debug build with a special variant says so after the commits */
|
||||
@Test
|
||||
fun dirtyDebugSpecial() = assertEquals(
|
||||
"D-Modem 0.1.0 03a196a-dirty (D-Modem-RE e2b9d1c-dirty), debug, special: agere-iso",
|
||||
BuildInfo.describe("0.1.0", "03a196a-dirty", "e2b9d1c-dirty", "debug", "agere-iso"),
|
||||
)
|
||||
|
||||
/** this build's line has a commit (or "unknown") after the version */
|
||||
@Test
|
||||
fun thisBuildHasACommit() = assertTrue(BuildInfo.described, Regex("D-Modem \\S+ ([0-9a-f]{7}(-dirty)?|unknown) .*").matches(BuildInfo.described))
|
||||
}
|
||||
@@ -37,8 +37,11 @@ class BluetoothBridgeTest {
|
||||
override val state: StateFlow<TerminalLink.State> = MutableStateFlow(TerminalLink.State.Open)
|
||||
val listeners = CopyOnWriteArrayList<TerminalLink.Listener>()
|
||||
val got = ByteArrayOutputStream()
|
||||
/** [l] told the modem's replies */
|
||||
override fun addListener(l: TerminalLink.Listener) { listeners.add(l) }
|
||||
/** [l] told no more */
|
||||
override fun removeListener(l: TerminalLink.Listener) { listeners.remove(l) }
|
||||
/** the bytes kept, and OK replied to a command (one ending in CR) */
|
||||
override fun write(data: ByteArray, offset: Int, length: Int): Boolean {
|
||||
synchronized(got) { got.write(data, offset, length) }
|
||||
if (String(data, offset, length).endsWith("\r")) {
|
||||
@@ -47,6 +50,7 @@ class BluetoothBridgeTest {
|
||||
}
|
||||
return true
|
||||
}
|
||||
/** what was written to the modem, as text */
|
||||
fun sent() = synchronized(got) { String(got.toByteArray()) }
|
||||
}
|
||||
|
||||
@@ -58,23 +62,27 @@ class BluetoothBridgeTest {
|
||||
private var bridge: BluetoothBridge? = null
|
||||
private val adapter get() = ctx.getSystemService(BluetoothManager::class.java).adapter
|
||||
|
||||
/** Bluetooth on and allowed */
|
||||
@Before
|
||||
fun setUp() {
|
||||
shadowOf(ctx as Application).grantPermissions(Manifest.permission.BLUETOOTH_CONNECT)
|
||||
shadowOf(adapter).setEnabled(true)
|
||||
}
|
||||
|
||||
/** the bridge stopped */
|
||||
@After
|
||||
fun tearDown() {
|
||||
bridge?.stop()
|
||||
}
|
||||
|
||||
/** [ok] waited for (5 s at most), failing with [what] if it never holds */
|
||||
private fun waitUntil(what: String, ok: () -> Boolean) {
|
||||
val end = System.currentTimeMillis() + 5000
|
||||
while (!ok() && System.currentTimeMillis() < end) Thread.sleep(20)
|
||||
assertTrue(what, ok())
|
||||
}
|
||||
|
||||
/** [i] read until [want] has come (5 s at most): what was read */
|
||||
private fun readUntil(i: InputStream, want: String): String {
|
||||
val sb = StringBuilder()
|
||||
val end = System.currentTimeMillis() + 5000
|
||||
@@ -85,6 +93,7 @@ class BluetoothBridgeTest {
|
||||
return sb.toString()
|
||||
}
|
||||
|
||||
/** a device connecting to the phone's port gets the modem; when it goes online, the call's hung up and the port offered again */
|
||||
@Test
|
||||
fun aDeviceConnectsToThePhone() {
|
||||
val b = BluetoothBridge(ctx, serial).also { bridge = it }
|
||||
@@ -105,6 +114,7 @@ class BluetoothBridgeTest {
|
||||
assertEquals(null, serial.client.value)
|
||||
}
|
||||
|
||||
/** the phone connects to a paired device and the device gets the modem */
|
||||
@Test
|
||||
fun thePhoneConnectsToAPairedDevice() {
|
||||
val device = adapter.getRemoteDevice("66:77:88:99:AA:BB")
|
||||
@@ -119,6 +129,7 @@ class BluetoothBridgeTest {
|
||||
assertEquals("AT&F\r", modem.sent())
|
||||
}
|
||||
|
||||
/** Bluetooth off, or its permission denied, fails to start and says why */
|
||||
@Test
|
||||
fun offOrNotAllowedSaysSo() {
|
||||
shadowOf(adapter).setEnabled(false)
|
||||
|
||||
@@ -29,6 +29,7 @@ import java.util.concurrent.atomic.AtomicInteger
|
||||
class InternetHostTest {
|
||||
private val closers = ArrayList<() -> Unit>()
|
||||
|
||||
/** everything the test opened closed */
|
||||
@After
|
||||
fun tearDown() = closers.forEach { runCatching { it() } }
|
||||
|
||||
@@ -36,11 +37,15 @@ class InternetHostTest {
|
||||
private class Untouched : TerminalLink {
|
||||
override val state: StateFlow<TerminalLink.State> = MutableStateFlow(TerminalLink.State.Open)
|
||||
val writes = AtomicInteger()
|
||||
/** no listeners kept: it never answers */
|
||||
override fun addListener(l: TerminalLink.Listener) {}
|
||||
/** nothing to remove */
|
||||
override fun removeListener(l: TerminalLink.Listener) {}
|
||||
/** a write counted (there should be none) */
|
||||
override fun write(data: ByteArray, offset: Int, length: Int): Boolean { writes.incrementAndGet(); return true }
|
||||
}
|
||||
|
||||
/** a computer dialling on the TCP bridge gets PPP and a TCP connection through the phone; dropping DTR ends it, the modem untouched */
|
||||
@Test
|
||||
fun aComputerOnTheTcpBridgeGetsTheInternet() {
|
||||
val modem = Untouched()
|
||||
@@ -82,8 +87,11 @@ class InternetHostTest {
|
||||
val up = ArrayBlockingQueue<Ppp.IpConfig>(1)
|
||||
val packets = LinkedBlockingQueue<ByteArray>()
|
||||
val ppp = Ppp({ b -> synchronized(out) { out.write(b); out.flush() } }, events = object : Ppp.Events {
|
||||
/** the link's address kept */
|
||||
override fun up(config: Ppp.IpConfig) { up.add(config) }
|
||||
/** an IP packet from the phone kept */
|
||||
override fun ip(packet: ByteArray) { packets.add(packet) }
|
||||
/** nothing to do when the link goes down */
|
||||
override fun down(reason: String) {}
|
||||
}, retryMs = 500)
|
||||
Thread {
|
||||
|
||||
@@ -29,15 +29,20 @@ class ModemTtyTest {
|
||||
override val state: StateFlow<TerminalLink.State> = MutableStateFlow(TerminalLink.State.Open)
|
||||
val listeners = CopyOnWriteArrayList<TerminalLink.Listener>()
|
||||
val got = ByteArrayOutputStream()
|
||||
/** [l] told the modem's output */
|
||||
override fun addListener(l: TerminalLink.Listener) { listeners.add(l) }
|
||||
/** [l] told no more */
|
||||
override fun removeListener(l: TerminalLink.Listener) { listeners.remove(l) }
|
||||
/** the bytes kept, and OK replied to an AT command */
|
||||
override fun write(data: ByteArray, offset: Int, length: Int): Boolean {
|
||||
synchronized(got) { got.write(data, offset, length) }
|
||||
val s = String(data, offset, length, Charsets.ISO_8859_1)
|
||||
if (s.contains("AT") && s.endsWith("\r")) emit("\r\nOK\r\n".toByteArray())
|
||||
return true
|
||||
}
|
||||
/** [b] from the modem to its listeners */
|
||||
fun emit(b: ByteArray) = listeners.forEach { it.onData(b, b.size) }
|
||||
/** what was written to the modem, as text */
|
||||
fun sent(): String = synchronized(got) { String(got.toByteArray(), Charsets.ISO_8859_1) }
|
||||
}
|
||||
|
||||
@@ -47,9 +52,11 @@ class ModemTtyTest {
|
||||
private val serial = SerialBridge(modem, signals, { hangUps.incrementAndGet() })
|
||||
private val tty = ModemTty(serial)
|
||||
|
||||
/** the pty library built for the host, loaded */
|
||||
@Before
|
||||
fun setUp() = Pty.load(LocalShellTest.hostPty())
|
||||
|
||||
/** [cond] waited for ([secs] at most), failing with [what] if it never holds */
|
||||
private fun until(what: String, secs: Int = 5, cond: () -> Boolean) {
|
||||
val end = System.currentTimeMillis() + secs * 1000L
|
||||
while (!cond()) {
|
||||
@@ -71,6 +78,7 @@ class ModemTtyTest {
|
||||
return sb.toString()
|
||||
}
|
||||
|
||||
/** a program opening the tty has the modem: its commands answered, RING unasked; closing it in a call hangs up, and it can open it again */
|
||||
@Test
|
||||
fun aProgramOnTheTtyHasTheModem() {
|
||||
val path = tty.slave()
|
||||
@@ -106,6 +114,7 @@ class ModemTtyTest {
|
||||
until("the bridge free again") { serial.client.value == null }
|
||||
}
|
||||
|
||||
/** the tty doesn't take the modem from another client: what's written to it doesn't reach the modem */
|
||||
@Test
|
||||
fun anotherClientsModemIsntTheTtys() {
|
||||
val other = Port("tcp", "a TCP client", java.io.ByteArrayInputStream(ByteArray(0)), ByteArrayOutputStream()) {}
|
||||
|
||||
@@ -32,15 +32,20 @@ class TcpBridgeTest {
|
||||
override val state: StateFlow<TerminalLink.State> = MutableStateFlow(TerminalLink.State.Open)
|
||||
val listeners = CopyOnWriteArrayList<TerminalLink.Listener>()
|
||||
val got = ByteArrayOutputStream()
|
||||
/** [l] told the modem's output */
|
||||
override fun addListener(l: TerminalLink.Listener) { listeners.add(l) }
|
||||
/** [l] told no more */
|
||||
override fun removeListener(l: TerminalLink.Listener) { listeners.remove(l) }
|
||||
/** the bytes kept, and OK replied to an AT command */
|
||||
override fun write(data: ByteArray, offset: Int, length: Int): Boolean {
|
||||
synchronized(got) { got.write(data, offset, length) }
|
||||
val s = String(data, offset, length, Charsets.ISO_8859_1)
|
||||
if (s.contains("AT") && s.endsWith("\r")) emit("\r\nOK\r\n".toByteArray())
|
||||
return true
|
||||
}
|
||||
/** [b] from the modem to its listeners */
|
||||
fun emit(b: ByteArray) = listeners.forEach { it.onData(b, b.size) }
|
||||
/** what was written to the modem */
|
||||
fun sent(): ByteArray = synchronized(got) { got.toByteArray() }
|
||||
}
|
||||
|
||||
@@ -50,12 +55,15 @@ class TcpBridgeTest {
|
||||
private val serial = SerialBridge(modem, signals, { hangUps.incrementAndGet() })
|
||||
private val bridges = ArrayList<TcpBridge>()
|
||||
|
||||
/** every bridge the test started stopped */
|
||||
@After
|
||||
fun tearDown() = bridges.forEach { it.stop() }
|
||||
|
||||
/** a bridge on a free port, started (and stopped after the test) */
|
||||
private fun bridge(telnet: Boolean = false, password: String = ""): TcpBridge =
|
||||
TcpBridge(serial, 0, telnet = telnet, password = password).also { assertTrue(it.start()); bridges.add(it) }
|
||||
|
||||
/** a client connected to [b] on localhost, reads timing out in 5 s */
|
||||
private fun connect(b: TcpBridge) = Socket().apply {
|
||||
connect(InetSocketAddress("127.0.0.1", b.localPort), 2000)
|
||||
soTimeout = 5000
|
||||
@@ -75,12 +83,14 @@ class TcpBridgeTest {
|
||||
return sb.toString()
|
||||
}
|
||||
|
||||
/** [ok] waited for (5 s at most), failing with [what] if it never holds */
|
||||
private fun waitUntil(what: String, ok: () -> Boolean) {
|
||||
val end = System.currentTimeMillis() + 5000
|
||||
while (!ok() && System.currentTimeMillis() < end) Thread.sleep(20)
|
||||
assertTrue(what, ok())
|
||||
}
|
||||
|
||||
/** raw TCP carries every byte value unchanged both ways; the client leaving frees the bridge without a hang-up */
|
||||
@Test
|
||||
fun rawBothWaysEveryByte() {
|
||||
val b = bridge()
|
||||
@@ -105,6 +115,7 @@ class TcpBridgeTest {
|
||||
assertEquals(0, hangUps.get())
|
||||
}
|
||||
|
||||
/** a second client gets BUSY while one has the modem; the first leaving in a call hangs it up and frees the bridge */
|
||||
@Test
|
||||
fun oneClientAtATimeAndTheCallHungUpWhenItGoes() {
|
||||
val b = bridge()
|
||||
@@ -118,6 +129,7 @@ class TcpBridgeTest {
|
||||
connect(b).use { waitUntil("claimed again") { serial.client.value != null } }
|
||||
}
|
||||
|
||||
/** with a password the client is asked it first, a wrong one refused, and it never reaches the modem */
|
||||
@Test
|
||||
fun aPasswordFirst() {
|
||||
val b = bridge(password = "s3cret")
|
||||
@@ -136,6 +148,7 @@ class TcpBridgeTest {
|
||||
}
|
||||
}
|
||||
|
||||
/** Telnet mode offers its options, takes the client's IAC IAC as one 0xff and doubles the modem's */
|
||||
@Test
|
||||
fun telnetDoublesIacAndNegotiates() {
|
||||
val b = bridge(telnet = true)
|
||||
@@ -162,6 +175,7 @@ class TcpBridgeTest {
|
||||
}
|
||||
}
|
||||
|
||||
/** pyserial's rfc2217:// client sets the speed, sees the carrier and DSR, and dropping DTR in a call hangs up */
|
||||
@Test
|
||||
fun rfc2217WithPyserial() {
|
||||
assumeTrue("python3 with pyserial", runCatching {
|
||||
|
||||
Reference in new issue
Block a user