Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

android: Kotlin shell that runs end to end

RoversX48f10affed7c
diff --git a/android/.gitignore b/android/.gitignore
new file mode 100644
index 00000000..3f2f3e40
--- /dev/null
+++ b/android/.gitignore
@@ -0,0 +1,11 @@
+# Regenerated by android/build.sh
+app/src/main/java/com/roversx/thinkterm/core/
+app/src/main/jniLibs/
+app/src/main/assets/*.ttf
+app/src/main/assets/probe_key
+app/src/main/assets/schemes.json
+.gradle/
+build/
+app/build/
+local.properties
+gradle-dist
diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts
new file mode 100644
index 00000000..61e9ea42
--- /dev/null
+++ b/android/app/build.gradle.kts
@@ -0,0 +1,48 @@
+plugins {
+ id("com.android.application")
+ id("org.jetbrains.kotlin.android")
+ id("org.jetbrains.kotlin.plugin.compose")
+}
+
+android {
+ namespace = "com.roversx.thinkterm"
+ compileSdk = 36
+
+ defaultConfig {
+ applicationId = "com.roversx.thinkterm"
+ minSdk = 35
+ targetSdk = 36
+ versionCode = 1
+ versionName = "0.1"
+ ndk { abiFilters += listOf("arm64-v8a") }
+ }
+
+ buildTypes {
+ release {
+ isMinifyEnabled = false
+ }
+ }
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ }
+ kotlinOptions { jvmTarget = "17" }
+ buildFeatures { compose = true }
+ packaging {
+ // JNA ships its own native pieces per ABI; only arm64 is built.
+ jniLibs { useLegacyPackaging = false }
+ }
+}
+
+dependencies {
+ implementation("net.java.dev.jna:jna:5.17.0@aar")
+ implementation(platform("androidx.compose:compose-bom:2025.09.00"))
+ implementation("androidx.compose.ui:ui")
+ implementation("androidx.compose.material3:material3")
+ implementation("androidx.compose.ui:ui-tooling-preview")
+ implementation("androidx.activity:activity-compose:1.11.0")
+ implementation("androidx.lifecycle:lifecycle-runtime-compose:2.9.4")
+ implementation("androidx.navigation:navigation-compose:2.9.5")
+ implementation("androidx.security:security-crypto:1.1.0")
+ implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")
+}
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
new file mode 100644
index 00000000..b13706a3
--- /dev/null
+++ b/android/app/src/main/AndroidManifest.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+ <uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="android.permission.VIBRATE" />
+ <application
+ android:label="ThinkTerm"
+ android:icon="@mipmap/ic_launcher"
+ android:theme="@style/Theme.ThinkTerm"
+ android:supportsRtl="true">
+ <activity
+ android:name=".MainActivity"
+ android:exported="true"
+ android:windowSoftInputMode="adjustResize"
+ android:configChanges="orientation|screenSize|keyboardHidden">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+ </application>
+</manifest>
diff --git a/android/app/src/main/java/com/roversx/thinkterm/GlyphPainter.kt b/android/app/src/main/java/com/roversx/thinkterm/GlyphPainter.kt
new file mode 100644
index 00000000..e9cd81d4
--- /dev/null
+++ b/android/app/src/main/java/com/roversx/thinkterm/GlyphPainter.kt
@@ -0,0 +1,58 @@
+package com.roversx.thinkterm
+
+import android.graphics.Bitmap
+import android.graphics.Canvas
+import android.graphics.Color
+import android.graphics.Paint
+import android.graphics.Typeface
+import com.roversx.thinkterm.core.GlyphPainter
+
+/// What the shaped fonts cannot draw (emoji, most symbols) the platform
+/// draws instead: a transparent bitmap the core blits into its atlas.
+/// Called on the core thread, so nothing here touches the UI.
+class AndroidGlyphPainter : GlyphPainter {
+ override fun paint(
+ text: String,
+ px: Double,
+ width: UInt,
+ height: UInt,
+ penX: Double,
+ baseline: Double,
+ red: UByte,
+ green: UByte,
+ blue: UByte,
+ ): ByteArray {
+ val w = width.toInt()
+ val h = height.toInt()
+ if (w <= 0 || h <= 0 || text.isEmpty()) return ByteArray(0)
+ return try {
+ val bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
+ bitmap.eraseColor(Color.TRANSPARENT)
+ val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ typeface = Typeface.MONOSPACE
+ textSize = px.toFloat()
+ color = Color.rgb(red.toInt(), green.toInt(), blue.toInt())
+ isSubpixelText = true
+ }
+ Canvas(bitmap).drawText(text, penX.toFloat(), baseline.toFloat(), paint)
+
+ val pixels = IntArray(w * h)
+ // getPixels hands back straight (un-premultiplied) ARGB ints,
+ // which is exactly what the core asks for.
+ bitmap.getPixels(pixels, 0, w, 0, 0, w, h)
+ bitmap.recycle()
+ val out = ByteArray(w * h * 4)
+ var i = 0
+ for (p in pixels) {
+ out[i] = ((p shr 16) and 0xff).toByte()
+ out[i + 1] = ((p shr 8) and 0xff).toByte()
+ out[i + 2] = (p and 0xff).toByte()
+ out[i + 3] = ((p ushr 24) and 0xff).toByte()
+ i += 4
+ }
+ out
+ } catch (e: Throwable) {
+ ByteArray(0)
+ }
+ }
+}
diff --git a/android/app/src/main/java/com/roversx/thinkterm/HostStore.kt b/android/app/src/main/java/com/roversx/thinkterm/HostStore.kt
new file mode 100644
index 00000000..5bcac08c
--- /dev/null
+++ b/android/app/src/main/java/com/roversx/thinkterm/HostStore.kt
@@ -0,0 +1,160 @@
+package com.roversx.thinkterm
+
+import android.content.Context
+import android.content.SharedPreferences
+import android.util.Log
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import androidx.security.crypto.EncryptedSharedPreferences
+import androidx.security.crypto.MasterKey
+import org.json.JSONArray
+import org.json.JSONObject
+import java.util.UUID
+
+/// A host the app connects to. The secret (key text or password) is not
+/// here: it lives in the encrypted preferences under the host's id.
+data class Host(
+ val id: String = UUID.randomUUID().toString(),
+ val name: String = "",
+ val hostname: String = "",
+ val port: Int = 22,
+ val user: String = "",
+ /// "key" (the secret is the private key's text) or "password".
+ val auth: String = "key",
+ /// The fingerprint seen on the first connection.
+ val knownHost: String? = null,
+ /// Empty means the default proxy command on the host.
+ val remoteCommand: String = "",
+) {
+ val display: String get() = if (name.isNotEmpty()) name else "$user@$hostname:$port"
+ val address: String get() = "$user@$hostname" + if (port == 22) "" else ":$port"
+
+ /// The dev-only entry that reaches the Mac's probe sshd. 10.0.2.2 is
+ /// the emulator's route to the host's loopback.
+ companion object {
+ const val PROBE_ID = "probe"
+
+ val probe = Host(
+ id = PROBE_ID,
+ name = "This Mac (probe)",
+ hostname = "10.0.2.2",
+ port = 2299,
+ user = "",
+ auth = "key",
+ remoteCommand = "/tmp/ttp-ssh/thinkterm-remote cli --prefer-mux proxy",
+ )
+ }
+}
+
+/// The hosts, in the app's preferences (small, edited rarely), with the
+/// secrets one file over in EncryptedSharedPreferences.
+class HostStore(context: Context) {
+ private val app = context.applicationContext
+ private val prefs: SharedPreferences = app.getSharedPreferences("thinkterm", Context.MODE_PRIVATE)
+ private val secrets: SharedPreferences = openSecrets(app)
+
+ var hosts by mutableStateOf<List<Host>>(emptyList())
+ private set
+
+ init {
+ hosts = decode(prefs.getString(KEY, "") ?: "")
+ }
+
+ /// This install's name to the servers, made once: the tab this phone
+ /// holds stays its own across launches.
+ val deviceId: String
+ get() = prefs.getString("client.id", null) ?: UUID.randomUUID().toString().also {
+ prefs.edit().putString("client.id", it).apply()
+ }
+
+ fun upsert(host: Host) {
+ val at = hosts.indexOfFirst { it.id == host.id }
+ hosts = if (at >= 0) hosts.toMutableList().also { it[at] = host } else hosts + host
+ save()
+ }
+
+ fun remove(host: Host) {
+ hosts = hosts.filter { it.id != host.id }
+ secrets.edit().remove(host.id).remove(host.id + ".passphrase").apply()
+ save()
+ }
+
+ fun rememberHostKey(id: String, fingerprint: String) {
+ val at = hosts.indexOfFirst { it.id == id }
+ if (at < 0 || hosts[at].knownHost == fingerprint) return
+ hosts = hosts.toMutableList().also { it[at] = it[at].copy(knownHost = fingerprint) }
+ save()
+ }
+
+ fun secret(id: String): String = secrets.getString(id, "") ?: ""
+ fun passphrase(id: String): String? = secrets.getString(id + ".passphrase", null)?.ifEmpty { null }
+
+ fun putSecret(id: String, secret: String, passphrase: String?) {
+ secrets.edit()
+ .putString(id, secret)
+ .putString(id + ".passphrase", passphrase ?: "")
+ .apply()
+ }
+
+ private fun save() {
+ val arr = JSONArray()
+ for (h in hosts) {
+ arr.put(
+ JSONObject()
+ .put("id", h.id)
+ .put("name", h.name)
+ .put("hostname", h.hostname)
+ .put("port", h.port)
+ .put("user", h.user)
+ .put("auth", h.auth)
+ .put("knownHost", h.knownHost ?: JSONObject.NULL)
+ .put("remoteCommand", h.remoteCommand)
+ )
+ }
+ prefs.edit().putString(KEY, arr.toString()).apply()
+ }
+
+ private fun decode(json: String): List<Host> {
+ if (json.isEmpty()) return emptyList()
+ return try {
+ val arr = JSONArray(json)
+ (0 until arr.length()).mapNotNull { i ->
+ val o = arr.optJSONObject(i) ?: return@mapNotNull null
+ Host(
+ id = o.optString("id", UUID.randomUUID().toString()),
+ name = o.optString("name"),
+ hostname = o.optString("hostname"),
+ port = o.optInt("port", 22),
+ user = o.optString("user"),
+ auth = o.optString("auth", "key"),
+ knownHost = o.optString("knownHost").ifEmpty { null },
+ remoteCommand = o.optString("remoteCommand"),
+ )
+ }
+ } catch (e: Throwable) {
+ Log.w("thinkterm", "hosts decode failed: $e")
+ emptyList()
+ }
+ }
+
+ private companion object {
+ const val KEY = "hosts.v1"
+
+ /// Keystore-backed preferences. If the device refuses (a broken
+ /// keystore on an emulator), plain preferences keep the app usable.
+ fun openSecrets(app: Context): SharedPreferences = try {
+ val key = MasterKey.Builder(app).setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build()
+ EncryptedSharedPreferences.create(
+ app,
+ "thinkterm-secrets",
+ key,
+ EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
+ EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,
+ )
+ } catch (e: Throwable) {
+ Log.w("thinkterm", "encrypted preferences unavailable: $e")
+ app.getSharedPreferences("thinkterm-secrets-plain", Context.MODE_PRIVATE)
+ }
+ }
+}
diff --git a/android/app/src/main/java/com/roversx/thinkterm/HostsScreen.kt b/android/app/src/main/java/com/roversx/thinkterm/HostsScreen.kt
new file mode 100644
index 00000000..e515e4a2
--- /dev/null
+++ b/android/app/src/main/java/com/roversx/thinkterm/HostsScreen.kt
@@ -0,0 +1,176 @@
+package com.roversx.thinkterm
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.imePadding
+import androidx.compose.foundation.layout.safeDrawingPadding
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.Button
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.text.input.KeyboardType
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+
+/// The saved hosts, plus — in a debuggable build — the entry that reaches
+/// the probe sshd on the developer's Mac.
+@Composable
+fun HostsScreen(store: HostStore, showProbe: Boolean, onOpen: (Host) -> Unit) {
+ var editing by remember { mutableStateOf<Host?>(null) }
+
+ editing?.let { host ->
+ HostEditor(store, host, onDone = { editing = null })
+ return
+ }
+
+ Column(
+ Modifier
+ .fillMaxSize()
+ .background(Color(0xFF111111))
+ .safeDrawingPadding()
+ ) {
+ Row(
+ Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Text("Hosts", color = Color.White, fontSize = 22.sp, modifier = Modifier.weight(1f))
+ TextButton(onClick = { editing = Host() }) { Text("Add", fontSize = 15.sp) }
+ }
+ LazyColumn(Modifier.fillMaxSize()) {
+ if (showProbe) {
+ item {
+ HostRow(Host.probe, onOpen = { onOpen(Host.probe) }, onEdit = null)
+ }
+ }
+ items(store.hosts, key = { it.id }) { host ->
+ HostRow(host, onOpen = { onOpen(host) }, onEdit = { editing = host })
+ }
+ if (store.hosts.isEmpty() && !showProbe) {
+ item {
+ Text(
+ "No hosts yet. Add one.",
+ color = Color.White.copy(alpha = 0.5f),
+ modifier = Modifier.padding(16.dp),
+ )
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun HostRow(host: Host, onOpen: () -> Unit, onEdit: (() -> Unit)?) {
+ Row(
+ Modifier
+ .fillMaxWidth()
+ .clickable(onClick = onOpen)
+ .padding(horizontal = 16.dp, vertical = 12.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Column(Modifier.weight(1f)) {
+ Text(host.display, color = Color.White, fontSize = 16.sp)
+ Text(host.address, color = Color.White.copy(alpha = 0.55f), fontSize = 12.sp)
+ }
+ if (onEdit != null) {
+ TextButton(onClick = onEdit) { Text("Edit", fontSize = 13.sp) }
+ }
+ }
+}
+
+/// Name, address, user and the secret. The secret never goes into the
+/// host record: it is written straight to the encrypted preferences.
+@Composable
+private fun HostEditor(store: HostStore, host: Host, onDone: () -> Unit) {
+ var name by remember { mutableStateOf(host.name) }
+ var hostname by remember { mutableStateOf(host.hostname) }
+ var port by remember { mutableStateOf(host.port.toString()) }
+ var user by remember { mutableStateOf(host.user) }
+ var auth by remember { mutableStateOf(host.auth) }
+ var secret by remember { mutableStateOf(store.secret(host.id)) }
+ var passphrase by remember { mutableStateOf(store.passphrase(host.id) ?: "") }
+ var remoteCommand by remember { mutableStateOf(host.remoteCommand) }
+
+ Column(
+ Modifier
+ .fillMaxSize()
+ .background(Color(0xFF111111))
+ .safeDrawingPadding()
+ .imePadding()
+ .verticalScroll(rememberScrollState())
+ .padding(16.dp),
+ verticalArrangement = Arrangement.spacedBy(10.dp),
+ ) {
+ Text("Host", color = Color.White, fontSize = 20.sp)
+ Field("Name", name) { name = it }
+ Field("Hostname", hostname) { hostname = it }
+ Field("Port", port, KeyboardType.Number) { port = it }
+ Field("User", user) { user = it }
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ for (kind in listOf("key", "password")) {
+ TextButton(onClick = { auth = kind }) {
+ Text(if (auth == kind) "• $kind" else kind, fontSize = 14.sp)
+ }
+ }
+ }
+ Field(if (auth == "key") "Private key text" else "Password", secret) { secret = it }
+ if (auth == "key") Field("Passphrase (optional)", passphrase) { passphrase = it }
+ Field("Remote command (optional)", remoteCommand) { remoteCommand = it }
+ Row(Modifier.fillMaxWidth().height(56.dp), verticalAlignment = Alignment.CenterVertically) {
+ Button(onClick = {
+ store.putSecret(host.id, secret, passphrase.ifEmpty { null })
+ store.upsert(
+ host.copy(
+ name = name,
+ hostname = hostname,
+ port = port.toIntOrNull() ?: 22,
+ user = user,
+ auth = auth,
+ remoteCommand = remoteCommand,
+ )
+ )
+ onDone()
+ }) { Text("Save") }
+ TextButton(onClick = onDone) { Text("Cancel") }
+ if (store.hosts.any { it.id == host.id }) {
+ TextButton(onClick = { store.remove(host); onDone() }) { Text("Delete") }
+ }
+ }
+ }
+}
+
+@Composable
+private fun Field(
+ label: String,
+ value: String,
+ keyboard: KeyboardType = KeyboardType.Text,
+ onChange: (String) -> Unit,
+) {
+ OutlinedTextField(
+ value = value,
+ onValueChange = onChange,
+ label = { Text(label) },
+ singleLine = keyboard != KeyboardType.Text || !label.contains("key text", ignoreCase = true),
+ keyboardOptions = KeyboardOptions(keyboardType = keyboard),
+ modifier = Modifier.fillMaxWidth(),
+ )
+}
diff --git a/android/app/src/main/java/com/roversx/thinkterm/KeyBar.kt b/android/app/src/main/java/com/roversx/thinkterm/KeyBar.kt
new file mode 100644
index 00000000..2e43b9bc
--- /dev/null
+++ b/android/app/src/main/java/com/roversx/thinkterm/KeyBar.kt
@@ -0,0 +1,95 @@
+package com.roversx.thinkterm
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.horizontalScroll
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.text.font.FontFamily
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+
+/// What a key sends. Sticky Ctrl and Alt stay pressed until the next key
+/// or the next character spends them, as on iOS.
+private sealed interface Cap {
+ val label: String
+
+ data class Dom(override val label: String, val name: String, val ctrl: Boolean = false) : Cap
+ data class Txt(override val label: String) : Cap { val text = label }
+ data class Sticky(override val label: String, val ctrl: Boolean) : Cap
+}
+
+/// The keys a soft keyboard has not got.
+private val bar: List<Cap> = listOf(
+ Cap.Dom("esc", "Escape"),
+ Cap.Dom("tab", "Tab"),
+ Cap.Sticky("ctrl", ctrl = true),
+ Cap.Sticky("alt", ctrl = false),
+ Cap.Dom("↑", "ArrowUp"),
+ Cap.Dom("↓", "ArrowDown"),
+ Cap.Dom("←", "ArrowLeft"),
+ Cap.Dom("→", "ArrowRight"),
+ Cap.Dom("home", "Home"),
+ Cap.Dom("end", "End"),
+ Cap.Dom("pgup", "PageUp"),
+ Cap.Dom("pgdn", "PageDown"),
+ Cap.Txt("-"),
+ Cap.Txt("/"),
+ Cap.Txt("|"),
+ Cap.Txt("~"),
+ Cap.Dom("^C", "c", ctrl = true),
+ Cap.Dom("^D", "d", ctrl = true),
+ Cap.Dom("^L", "l", ctrl = true),
+ Cap.Dom("^Z", "z", ctrl = true),
+ Cap.Dom("⌫", "Backspace"),
+)
+
+@Composable
+fun KeyBar(model: TerminalModel, modifier: Modifier = Modifier) {
+ Row(
+ modifier = modifier
+ .fillMaxWidth()
+ .height(40.dp)
+ .horizontalScroll(rememberScrollState())
+ .padding(horizontal = 6.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(6.dp),
+ ) {
+ for (cap in bar) {
+ val held = when (cap) {
+ is Cap.Sticky -> if (cap.ctrl) model.ctrlSticky else model.altSticky
+ else -> false
+ }
+ Text(
+ text = cap.label,
+ color = Color.White,
+ fontSize = 13.sp,
+ fontFamily = FontFamily.Monospace,
+ modifier = Modifier
+ .clip(RoundedCornerShape(6.dp))
+ .background(if (held) Color(0xFF3B6EA5) else Color.White.copy(alpha = 0.10f))
+ .clickable { send(cap, model) }
+ .padding(horizontal = 11.dp, vertical = 7.dp),
+ )
+ }
+ }
+}
+
+private fun send(cap: Cap, model: TerminalModel) {
+ when (cap) {
+ is Cap.Dom -> model.key(cap.name, ctrl = cap.ctrl)
+ is Cap.Txt -> model.text(cap.text)
+ is Cap.Sticky -> if (cap.ctrl) model.ctrlSticky = !model.ctrlSticky else model.altSticky = !model.altSticky
+ }
+}
diff --git a/android/app/src/main/java/com/roversx/thinkterm/MainActivity.kt b/android/app/src/main/java/com/roversx/thinkterm/MainActivity.kt
new file mode 100644
index 00000000..ddfb7a01
--- /dev/null
+++ b/android/app/src/main/java/com/roversx/thinkterm/MainActivity.kt
@@ -0,0 +1,33 @@
+package com.roversx.thinkterm
+
+import android.content.pm.ApplicationInfo
+import android.os.Bundle
+import androidx.activity.ComponentActivity
+import androidx.activity.compose.setContent
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.darkColorScheme
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+
+class MainActivity : ComponentActivity() {
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ // The core opens the faces as files, so they leave the APK once.
+ Assets.install(this)
+ val debuggable = (applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0
+ val store = HostStore(this)
+ setContent {
+ MaterialTheme(colorScheme = darkColorScheme()) {
+ var open by remember { mutableStateOf<Host?>(null) }
+ val host = open
+ if (host == null) {
+ HostsScreen(store, showProbe = debuggable) { open = it }
+ } else {
+ TerminalScreen(host, store) { open = null }
+ }
+ }
+ }
+ }
+}
diff --git a/android/app/src/main/java/com/roversx/thinkterm/NativeWindow.kt b/android/app/src/main/java/com/roversx/thinkterm/NativeWindow.kt
new file mode 100644
index 00000000..8d2694fe
--- /dev/null
+++ b/android/app/src/main/java/com/roversx/thinkterm/NativeWindow.kt
@@ -0,0 +1,17 @@
+package com.roversx.thinkterm
+
+/// The two JNI entries in libthinkterm_mobile.so that turn a Surface into
+/// the ANativeWindow pointer the core's GPU side attaches to. The core
+/// itself is reached through JNA (the generated bindings); these two need
+/// the JNIEnv, so they are plain JNI and the library is loaded here.
+object NativeWindow {
+ init {
+ System.loadLibrary("thinkterm_mobile")
+ }
+
+ @JvmStatic
+ external fun fromSurface(surface: android.view.Surface): Long
+
+ @JvmStatic
+ external fun release(window: Long)
+}
diff --git a/android/app/src/main/java/com/roversx/thinkterm/TerminalModel.kt b/android/app/src/main/java/com/roversx/thinkterm/TerminalModel.kt
new file mode 100644
index 00000000..c9410308
--- /dev/null
+++ b/android/app/src/main/java/com/roversx/thinkterm/TerminalModel.kt
@@ -0,0 +1,262 @@
+package com.roversx.thinkterm
+
+import android.content.ClipData
+import android.content.ClipboardManager
+import android.content.Context
+import android.os.Build
+import android.os.Handler
+import android.os.Looper
+import android.os.VibrationEffect
+import android.os.Vibrator
+import android.os.VibratorManager
+import android.util.Log
+import android.view.Choreographer
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.graphics.Color
+import com.roversx.thinkterm.core.Core
+import com.roversx.thinkterm.core.Notify
+import java.util.concurrent.atomic.AtomicBoolean
+
+/// The shell's side of the thread contract. `Notify` calls arrive on the
+/// core thread; nothing here blocks them and nothing here calls back into
+/// the core from inside one. The Choreographer callback is the only place
+/// `render` is called; the core only ever *asks* for a frame.
+class TerminalModel(
+ private val context: Context,
+ private val store: HostStore,
+ val host: Host,
+) {
+ val core: Core
+
+ // What the screen shows, as Compose state (written on the main thread).
+ var tabs by mutableStateOf<TabsView?>(null)
+ private set
+ var status by mutableStateOf<StatusView?>(null)
+ private set
+ var title by mutableStateOf("")
+ private set
+ var connection by mutableStateOf("")
+ private set
+ var background by mutableStateOf(Color(0xFF1C1C1C))
+ private set
+ var ctrlSticky by mutableStateOf(false)
+ var altSticky by mutableStateOf(false)
+
+ private val frameNeeded = AtomicBoolean(false)
+ private val changePending = AtomicBoolean(false)
+ private val main = Handler(Looper.getMainLooper())
+ private val choreographer = Choreographer.getInstance()
+ private var running = true
+ private var connected = false
+
+ /// Set by the view once the surface is attached; the connection waits
+ /// for it so the first frame has somewhere to go.
+ var generation: ULong = 0uL
+
+ private val tick = object : Choreographer.FrameCallback {
+ override fun doFrame(frameTimeNanos: Long) {
+ if (!running) return
+ if (frameNeeded.getAndSet(false)) core.render()
+ if (changePending.getAndSet(false)) refreshViews()
+ choreographer.postFrameCallback(this)
+ }
+ }
+
+ init {
+ core = Core(Sink())
+ choreographer.postFrameCallback(tick)
+ }
+
+ // MARK: connection
+
+ /// Connect once; the surface must be attached first so the core has a
+ /// size to lay the panes out in.
+ fun connect() {
+ if (connected) return
+ connected = true
+ val secret = if (host.id == Host.PROBE_ID) probeKey() else store.secret(host.id)
+ val passphrase = if (host.id == Host.PROBE_ID) null else store.passphrase(host.id)
+ Log.i("thinkterm", "shell: connecting ${host.address}, ${secret.length} chars of secret")
+ core.connect(
+ host = host.hostname,
+ port = host.port.toUShort(),
+ user = host.user,
+ authKind = host.auth,
+ secret = secret,
+ passphrase = passphrase,
+ knownHost = host.knownHost,
+ remoteCommand = host.remoteCommand,
+ deviceId = store.deviceId,
+ keepaliveSecs = 15u,
+ fontPaths = Assets.fontPaths(context),
+ sizePt = 11.0,
+ painter = AndroidGlyphPainter(),
+ )
+ }
+
+ /// The probe's throwaway key travels in the APK, not the preferences.
+ private fun probeKey(): String = try {
+ context.assets.open("probe_key").bufferedReader().use { it.readText() }
+ } catch (e: Throwable) {
+ Log.w("thinkterm", "no probe_key asset: $e")
+ ""
+ }
+
+ fun disconnect() {
+ connected = false
+ core.disconnect()
+ }
+
+ /// Leaving the screen for good: the frame loop stops, then the core.
+ fun shutdown() {
+ running = false
+ choreographer.removeFrameCallback(tick)
+ core.disconnect()
+ core.shutdown()
+ }
+
+ // MARK: input
+
+ fun key(name: String, ctrl: Boolean = false, alt: Boolean = false, shift: Boolean = false) {
+ core.key(name, ctrl || takeCtrl(), alt || takeAlt(), shift)
+ }
+
+ /// Text from the keyboard. A sticky Ctrl or Alt turns a single
+ /// character into a chord instead.
+ fun text(text: String) {
+ if ((ctrlSticky || altSticky) && text.length == 1) {
+ key(text)
+ return
+ }
+ core.text(text)
+ }
+
+ private fun takeCtrl(): Boolean = ctrlSticky.also { if (it) ctrlSticky = false }
+ private fun takeAlt(): Boolean = altSticky.also { if (it) altSticky = false }
+
+ fun chromeClick(action: String, pane: Int? = null, tab: Int? = null) {
+ core.chromeClick(action, pane?.toUInt(), tab?.toUInt())
+ }
+
+ // MARK: the views
+
+ /// Pull every view the screen shows. Called on the main thread after
+ /// the core said something changed; a burst of changes is one pull.
+ private fun refreshViews() {
+ val tabs = Views.tabs(core.view("tabs"))
+ if (tabs != this.tabs) this.tabs = tabs
+ val status = Views.status(core.view("status"))
+ if (status != this.status) this.status = status
+ }
+
+ // MARK: what the core tells the shell
+
+ private inner class Sink : Notify {
+ override fun onFrameNeeded() {
+ frameNeeded.set(true)
+ }
+
+ override fun onStatus(status: String) {
+ main.post { connection = status }
+ }
+
+ override fun onLog(line: String) {
+ Log.i("thinkterm", line)
+ }
+
+ override fun onTitle(title: String) {
+ main.post { [email protected] = title }
+ }
+
+ override fun onChange() {
+ changePending.set(true)
+ }
+
+ override fun onClipboard(text: String) {
+ main.post {
+ val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
+ cm?.setPrimaryClip(ClipData.newPlainText("thinkterm", text))
+ }
+ }
+
+ override fun onFocusInput() {
+ main.post { onFocusRequested?.invoke() }
+ }
+
+ override fun onImeAnchor(left: Double, top: Double, width: Double, height: Double) {
+ // Nothing yet: the Android IME is not asked where the caret is.
+ }
+
+ override fun onHostKey(fingerprint: String) {
+ main.post { store.rememberHostKey(host.id, fingerprint) }
+ }
+
+ override fun onPublished(key: String, value: String) {
+ if (key != "bg") return
+ val color = parseHex(value) ?: return
+ main.post { if (background != color) background = color }
+ }
+
+ override fun onBell() {
+ main.post { buzz() }
+ }
+
+ override fun onPreview(pane: UInt, rows: String) {
+ // The overview is not built yet.
+ }
+ }
+
+ /// The view sets this so the core can ask for the keyboard.
+ var onFocusRequested: (() -> Unit)? = null
+
+ private fun buzz() {
+ try {
+ val v = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ (context.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager).defaultVibrator
+ } else {
+ @Suppress("DEPRECATION")
+ context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
+ }
+ v.vibrate(VibrationEffect.createOneShot(20, VibrationEffect.DEFAULT_AMPLITUDE))
+ } catch (e: Throwable) {
+ // No vibrator, or no permission: the bell is silent.
+ }
+ }
+
+ private fun parseHex(value: String): Color? {
+ val hex = value.removePrefix("#")
+ if (hex.length != 6 && hex.length != 8) return null
+ return try {
+ val n = hex.toLong(16)
+ if (hex.length == 6) Color(0xFF000000L.or(n).toInt()) else Color(n.toInt())
+ } catch (e: Throwable) {
+ null
+ }
+ }
+}
+
+/// The fonts the core shapes with: copied out of the APK once, because
+/// the core opens them as files.
+object Assets {
+ private val faces = listOf("JetBrainsMono-Regular.ttf", "SymbolsNerdFontMono-Regular.ttf", "FiraCode-Regular.ttf")
+
+ fun install(context: Context) {
+ for (name in faces) {
+ val out = java.io.File(context.filesDir, name)
+ if (out.exists() && out.length() > 0) continue
+ try {
+ context.assets.open(name).use { input -> out.outputStream().use { input.copyTo(it) } }
+ } catch (e: Throwable) {
+ Log.w("thinkterm", "font $name not installed: $e")
+ }
+ }
+ }
+
+ /// The base face first, the symbols fallback after it.
+ fun fontPaths(context: Context): List<String> =
+ listOf("JetBrainsMono-Regular.ttf", "SymbolsNerdFontMono-Regular.ttf")
+ .map { java.io.File(context.filesDir, it).absolutePath }
+ .filter { java.io.File(it).exists() }
+}
diff --git a/android/app/src/main/java/com/roversx/thinkterm/TerminalScreen.kt b/android/app/src/main/java/com/roversx/thinkterm/TerminalScreen.kt
new file mode 100644
index 00000000..684e469d
--- /dev/null
+++ b/android/app/src/main/java/com/roversx/thinkterm/TerminalScreen.kt
@@ -0,0 +1,163 @@
+package com.roversx.thinkterm
+
+import androidx.activity.compose.BackHandler
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.horizontalScroll
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.imePadding
+import androidx.compose.foundation.layout.safeDrawingPadding
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.widthIn
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.remember
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import androidx.compose.ui.viewinterop.AndroidView
+
+/// The screen that shows one host: the tab strip, the terminal surface,
+/// a status line and the key bar. One model per connection; leaving
+/// disconnects and stops the core.
+@Composable
+fun TerminalScreen(host: Host, store: HostStore, onBack: () -> Unit) {
+ val context = LocalContext.current
+ val model = remember(host.id) { TerminalModel(context, store, host) }
+
+ // The connection does not wait for the surface: the core attaches to
+ // a pane when both have arrived, in whichever order they come.
+ LaunchedEffect(model) { model.connect() }
+
+ DisposableEffect(model) {
+ onDispose { model.shutdown() }
+ }
+
+ BackHandler {
+ model.disconnect()
+ onBack()
+ }
+
+ Column(
+ Modifier
+ .fillMaxSize()
+ .background(model.background)
+ // targetSdk 36 draws edge to edge: keep the chrome out from
+ // under the status bar, and let the key bar ride the keyboard.
+ .safeDrawingPadding()
+ .imePadding()
+ ) {
+ TopBar(model, onBack = {
+ model.disconnect()
+ onBack()
+ })
+ TabStrip(model)
+ Box(Modifier.fillMaxWidth().weight(1f)) {
+ AndroidView(
+ factory = { TerminalHostView(it, model) },
+ modifier = Modifier.fillMaxSize(),
+ )
+ }
+ StatusLine(model)
+ KeyBar(model)
+ }
+}
+
+@Composable
+private fun TopBar(model: TerminalModel, onBack: () -> Unit) {
+ Row(
+ Modifier
+ .fillMaxWidth()
+ .height(44.dp)
+ .padding(horizontal = 10.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Text(
+ "‹",
+ color = Color.White,
+ fontSize = 24.sp,
+ modifier = Modifier.clickable(onClick = onBack).padding(end = 12.dp),
+ )
+ Text(
+ model.title.ifEmpty { model.host.display },
+ color = Color.White,
+ fontSize = 15.sp,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.weight(1f),
+ )
+ }
+}
+
+@Composable
+private fun TabStrip(model: TerminalModel) {
+ val tabs = model.tabs?.tabs ?: emptyList()
+ Row(
+ Modifier
+ .fillMaxWidth()
+ .height(34.dp)
+ .horizontalScroll(rememberScrollState())
+ .padding(horizontal = 8.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(6.dp),
+ ) {
+ for (tab in tabs) {
+ Text(
+ text = tab.label.ifEmpty { "Tab ${tab.tab}" },
+ color = if (tab.current) Color.White else Color.White.copy(alpha = 0.62f),
+ fontSize = 12.sp,
+ fontWeight = if (tab.current) FontWeight.SemiBold else FontWeight.Normal,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier
+ .clip(RoundedCornerShape(50))
+ .background(Color.White.copy(alpha = if (tab.current) 0.18f else 0.06f))
+ .clickable { model.chromeClick("pane", pane = tab.target) }
+ .widthIn(min = 70.dp, max = 150.dp)
+ .padding(horizontal = 10.dp, vertical = 6.dp),
+ )
+ }
+ Text(
+ "+",
+ color = Color.White.copy(alpha = 0.62f),
+ fontSize = 16.sp,
+ modifier = Modifier
+ .clickable { model.chromeClick("new-tab") }
+ .padding(horizontal = 10.dp, vertical = 4.dp),
+ )
+ }
+}
+
+/// The connection's own line while it is not yet a pane, and whatever
+/// the App wants said on top of it.
+@Composable
+private fun StatusLine(model: TerminalModel) {
+ val toast = model.status?.toast
+ val connection = model.connection.takeIf { it.isNotEmpty() && !it.startsWith("pane ") }
+ val line = toast ?: connection ?: return
+ Text(
+ line,
+ color = Color.White.copy(alpha = 0.7f),
+ fontSize = 11.sp,
+ maxLines = 2,
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 10.dp, vertical = 4.dp),
+ )
+}
diff --git a/android/app/src/main/java/com/roversx/thinkterm/TerminalView.kt b/android/app/src/main/java/com/roversx/thinkterm/TerminalView.kt
new file mode 100644
index 00000000..e7464283
--- /dev/null
+++ b/android/app/src/main/java/com/roversx/thinkterm/TerminalView.kt
@@ -0,0 +1,289 @@
+package com.roversx.thinkterm
+
+import android.annotation.SuppressLint
+import android.content.Context
+import android.util.Log
+import android.view.KeyEvent
+import android.view.MotionEvent
+import android.view.ScaleGestureDetector
+import android.view.SurfaceHolder
+import android.view.SurfaceView
+import android.view.View
+import android.view.ViewConfiguration
+import android.view.inputmethod.BaseInputConnection
+import android.view.inputmethod.EditorInfo
+import android.view.inputmethod.InputConnection
+import android.view.inputmethod.InputMethodManager
+import android.widget.FrameLayout
+
+/// The terminal itself: a SurfaceView the core draws on, with a
+/// transparent, focusable view over it for touches and the IME. Points
+/// handed to the core are in dp, the unit implied by `attachSurface`'s
+/// scale; the surface's own size stays in pixels.
+@SuppressLint("ViewConstructor")
+class TerminalHostView(context: Context, private val model: TerminalModel) : FrameLayout(context) {
+ private val surfaceView = SurfaceView(context)
+ private val input = TerminalInputView(context, model)
+
+ private var window: Long = 0
+ private var lastSize = Triple(0, 0, 0.0)
+
+ init {
+ addView(surfaceView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
+ addView(input, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
+ model.onFocusRequested = { input.focusAndShowKeyboard() }
+ surfaceView.holder.addCallback(object : SurfaceHolder.Callback {
+ override fun surfaceCreated(holder: SurfaceHolder) {
+ window = NativeWindow.fromSurface(holder.surface)
+ Log.i("thinkterm", "shell: native window $window")
+ }
+
+ override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
+ if (window == 0L) return
+ val density = resources.displayMetrics.density.toDouble()
+ if (model.generation == 0uL) {
+ val gen = model.core.attachSurface(window.toULong(), width.toUInt(), height.toUInt(), density)
+ model.generation = gen
+ lastSize = Triple(width, height, density)
+ Log.i("thinkterm", "shell: attached generation $gen (${width}x$height @$density)")
+ if (gen == 0uL) {
+ Log.w("thinkterm", "shell: the core could not take the surface")
+ } else {
+ input.focusAndShowKeyboard()
+ }
+ } else if (lastSize != Triple(width, height, density)) {
+ lastSize = Triple(width, height, density)
+ model.core.resize(model.generation, width.toUInt(), height.toUInt(), density)
+ }
+ }
+
+ override fun surfaceDestroyed(holder: SurfaceHolder) {
+ // The handshake: detach must return before the surface is
+ // released, or the core would draw into freed memory.
+ if (model.generation != 0uL) {
+ model.core.detachSurface(model.generation)
+ model.generation = 0uL
+ }
+ if (window != 0L) {
+ NativeWindow.release(window)
+ window = 0
+ }
+ lastSize = Triple(0, 0, 0.0)
+ }
+ })
+ }
+}
+
+/// Touches, hardware keys and the IME. Invisible: it only takes input.
+@SuppressLint("ViewConstructor")
+class TerminalInputView(context: Context, private val model: TerminalModel) : View(context) {
+ private val slop = ViewConfiguration.get(context).scaledTouchSlop
+ private val tapTimeout = ViewConfiguration.getTapTimeout().toLong() * 2
+ private var downX = 0f
+ private var downY = 0f
+ private var lastY = 0f
+ private var downAt = 0L
+ private var dragging = false
+ private var pinchStart = 1f
+
+ /// The composition the IME is building. Nothing reaches the pane
+ /// while it is open; it is sent once, when it is committed.
+ private var composing: String? = null
+
+ private val density: Float get() = resources.displayMetrics.density
+
+ private val pinch = ScaleGestureDetector(context, object : ScaleGestureDetector.SimpleOnScaleGestureListener() {
+ override fun onScaleBegin(d: ScaleGestureDetector): Boolean {
+ pinchStart = 1f
+ return true
+ }
+
+ override fun onScale(d: ScaleGestureDetector): Boolean {
+ // One font step per 15% of scale, either way, as on iOS.
+ while (d.scaleFactor > pinchStart * 1.15f) {
+ pinchStart *= 1.15f
+ model.core.stepFont(1.0)
+ }
+ while (d.scaleFactor < pinchStart / 1.15f) {
+ pinchStart /= 1.15f
+ model.core.stepFont(-1.0)
+ }
+ return true
+ }
+ })
+
+ init {
+ isFocusable = true
+ isFocusableInTouchMode = true
+ isClickable = true
+ }
+
+ fun focusAndShowKeyboard() {
+ requestFocus()
+ val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
+ imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
+ }
+
+ // MARK: touches
+
+ @SuppressLint("ClickableViewAccessibility")
+ override fun onTouchEvent(event: MotionEvent): Boolean {
+ pinch.onTouchEvent(event)
+ when (event.actionMasked) {
+ MotionEvent.ACTION_DOWN -> {
+ downX = event.x
+ downY = event.y
+ lastY = event.y
+ downAt = event.eventTime
+ dragging = false
+ }
+
+ MotionEvent.ACTION_MOVE -> {
+ if (event.pointerCount > 1) return true
+ if (!dragging && Math.abs(event.y - downY) > slop) dragging = true
+ if (dragging) {
+ // A busy main thread gets the moves coalesced: the
+ // samples in between ride along as history.
+ for (h in 0 until event.historySize) scrollTo(event.getHistoricalY(h))
+ scrollTo(event.y)
+ }
+ }
+
+ MotionEvent.ACTION_UP -> {
+ // The lift carries the last of the travel.
+ if (dragging) scrollTo(event.y)
+ if (!dragging && event.eventTime - downAt < tapTimeout) {
+ val x = (downX / density).toDouble()
+ val y = (downY / density).toDouble()
+ model.core.pointer("down", x, y)
+ model.core.pointer("up", x, y)
+ focusAndShowKeyboard()
+ }
+ }
+ }
+ return true
+ }
+
+ /// The finger is now at `y`: the rows between there and where it
+ /// was go past. Dragging up moves towards the newest row, which is
+ /// what the core calls positive travel.
+ private fun scrollTo(y: Float) {
+ val px = (lastY - y) / density
+ lastY = y
+ if (px == 0f) return
+ model.core.wheelPx(
+ (width / 2f / density).toDouble(),
+ (height / 2f / density).toDouble(),
+ px.toDouble(),
+ )
+ }
+
+ // MARK: hardware keys (and `adb shell input text`)
+
+ override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
+ val ctrl = event.isCtrlPressed
+ val alt = event.isAltPressed
+ val shift = event.isShiftPressed
+ val name = domName(keyCode)
+ if (name != null) {
+ model.key(name, ctrl, alt, shift)
+ return true
+ }
+ val ch = event.unicodeChar
+ if (ch != 0) {
+ val s = ch.toChar().toString()
+ if (ctrl || alt) model.key(s, ctrl, alt, false) else model.text(s)
+ return true
+ }
+ return super.onKeyDown(keyCode, event)
+ }
+
+ private fun domName(keyCode: Int): String? = when (keyCode) {
+ KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER -> "Enter"
+ KeyEvent.KEYCODE_DEL -> "Backspace"
+ KeyEvent.KEYCODE_FORWARD_DEL -> "Delete"
+ KeyEvent.KEYCODE_TAB -> "Tab"
+ KeyEvent.KEYCODE_ESCAPE -> "Escape"
+ KeyEvent.KEYCODE_DPAD_UP -> "ArrowUp"
+ KeyEvent.KEYCODE_DPAD_DOWN -> "ArrowDown"
+ KeyEvent.KEYCODE_DPAD_LEFT -> "ArrowLeft"
+ KeyEvent.KEYCODE_DPAD_RIGHT -> "ArrowRight"
+ KeyEvent.KEYCODE_MOVE_HOME -> "Home"
+ KeyEvent.KEYCODE_MOVE_END -> "End"
+ KeyEvent.KEYCODE_PAGE_UP -> "PageUp"
+ KeyEvent.KEYCODE_PAGE_DOWN -> "PageDown"
+ KeyEvent.KEYCODE_INSERT -> "Insert"
+ else -> null
+ }
+
+ // MARK: the IME
+
+ override fun onCheckIsTextEditor(): Boolean = true
+
+ override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection {
+ // No suggestions and no autocorrect: a terminal wants the keys as
+ // typed, and the password variation is the one every IME honours.
+ outAttrs.inputType = EditorInfo.TYPE_CLASS_TEXT or
+ EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS or
+ EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
+ outAttrs.imeOptions = EditorInfo.IME_ACTION_NONE or EditorInfo.IME_FLAG_NO_EXTRACT_UI
+ return Connection(this)
+ }
+
+ private inner class Connection(view: View) : BaseInputConnection(view, false) {
+ override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean {
+ val s = text?.toString() ?: return true
+ endComposing()
+ if (s == "\n") model.key("Enter") else if (s.isNotEmpty()) model.text(s)
+ return true
+ }
+
+ override fun setComposingText(text: CharSequence?, newCursorPosition: Int): Boolean {
+ val s = text?.toString() ?: ""
+ if (s.isEmpty()) {
+ // The IME cleared the composition (backspaced it away).
+ if (composing != null) {
+ composing = null
+ model.core.setComposing(false)
+ }
+ return true
+ }
+ if (composing == null) model.core.setComposing(true)
+ composing = s
+ return true
+ }
+
+ override fun finishComposingText(): Boolean {
+ val s = composing
+ composing = null
+ if (s != null) {
+ model.core.setComposing(false)
+ if (s.isNotEmpty()) model.text(s)
+ }
+ return true
+ }
+
+ override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean {
+ // While composing the IME edits its own buffer, not the pane.
+ if (composing != null) return true
+ repeat(beforeLength) { model.key("Backspace") }
+ return true
+ }
+
+ override fun sendKeyEvent(event: KeyEvent): Boolean {
+ if (event.action != KeyEvent.ACTION_DOWN) return true
+ return onKeyDown(event.keyCode, event)
+ }
+
+ override fun performEditorAction(actionCode: Int): Boolean {
+ model.key("Enter")
+ return true
+ }
+
+ private fun endComposing() {
+ if (composing == null) return
+ composing = null
+ model.core.setComposing(false)
+ }
+ }
+}
diff --git a/android/app/src/main/java/com/roversx/thinkterm/Views.kt b/android/app/src/main/java/com/roversx/thinkterm/Views.kt
new file mode 100644
index 00000000..d3bbe453
--- /dev/null
+++ b/android/app/src/main/java/com/roversx/thinkterm/Views.kt
@@ -0,0 +1,65 @@
+package com.roversx.thinkterm
+
+import android.util.Log
+import org.json.JSONArray
+import org.json.JSONObject
+
+/// The App's views, as its JSON names them. Only the fields this shell
+/// shows are picked out; org.json is in the platform, so no codegen.
+
+data class TabEntry(
+ val tab: Int,
+ val label: String,
+ val title: String,
+ val target: Int,
+ val current: Boolean,
+)
+
+data class TabsView(val tabs: List<TabEntry>)
+
+data class StatusView(
+ val summary: String,
+ val toast: String?,
+ val sticky: Boolean,
+)
+
+object Views {
+ fun tabs(json: String): TabsView? {
+ val root = obj(json) ?: return null
+ val arr = root.optJSONArray("tabs") ?: JSONArray()
+ val out = ArrayList<TabEntry>(arr.length())
+ for (i in 0 until arr.length()) {
+ val t = arr.optJSONObject(i) ?: continue
+ out.add(
+ TabEntry(
+ tab = t.optInt("tab"),
+ label = t.optString("label"),
+ title = t.optString("title"),
+ target = t.optInt("target"),
+ current = t.optBoolean("current"),
+ )
+ )
+ }
+ return TabsView(out)
+ }
+
+ fun status(json: String): StatusView? {
+ val root = obj(json) ?: return null
+ val toast = root.optJSONObject("toast")
+ return StatusView(
+ summary = root.optString("summary"),
+ toast = toast?.optString("text")?.ifEmpty { null },
+ sticky = toast?.optBoolean("sticky") ?: false,
+ )
+ }
+
+ private fun obj(json: String): JSONObject? {
+ if (json.isEmpty() || json == "null") return null
+ return try {
+ JSONObject(json)
+ } catch (e: Throwable) {
+ Log.w("thinkterm", "view decode failed: ${json.take(200)}")
+ null
+ }
+ }
+}
diff --git a/android/app/src/main/res/drawable/ic_launcher_background.xml b/android/app/src/main/res/drawable/ic_launcher_background.xml
new file mode 100644
index 00000000..74c08050
--- /dev/null
+++ b/android/app/src/main/res/drawable/ic_launcher_background.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108">
+ <path android:pathData="M0,0h108v108h-108z">
+ <aapt:attr xmlns:aapt="http://schemas.android.com/aapt" name="android:fillColor">
+ <gradient android:startX="54" android:startY="0" android:endX="54" android:endY="108" android:type="linear">
+ <item android:offset="0" android:color="#FF05052E" />
+ <item android:offset="1" android:color="#FF1A26C8" />
+ </gradient>
+ </aapt:attr>
+ </path>
+</vector>
diff --git a/android/app/src/main/res/drawable/ic_launcher_foreground.xml b/android/app/src/main/res/drawable/ic_launcher_foreground.xml
new file mode 100644
index 00000000..362afd63
--- /dev/null
+++ b/android/app/src/main/res/drawable/ic_launcher_foreground.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="utf-8"?>
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108">
+ <!-- The chevron, as on the Mac and the iPhone. -->
+ <path android:fillColor="#FFFFFFFF"
+ android:pathData="M44,30 L66,54 L44,78 L38.5,72.5 L55,54 L38.5,35.5 Z" />
+</vector>
diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
new file mode 100644
index 00000000..6b78462d
--- /dev/null
+++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
+ <background android:drawable="@drawable/ic_launcher_background" />
+ <foreground android:drawable="@drawable/ic_launcher_foreground" />
+</adaptive-icon>
diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml
new file mode 100644
index 00000000..e0c49769
--- /dev/null
+++ b/android/app/src/main/res/values/strings.xml
@@ -0,0 +1,3 @@
+<resources>
+ <string name="app_name">ThinkTerm</string>
+</resources>
diff --git a/android/app/src/main/res/values/themes.xml b/android/app/src/main/res/values/themes.xml
new file mode 100644
index 00000000..5f096050
--- /dev/null
+++ b/android/app/src/main/res/values/themes.xml
@@ -0,0 +1,6 @@
+<resources>
+ <style name="Theme.ThinkTerm" parent="android:Theme.Material.NoActionBar">
+ <item name="android:windowBackground">@android:color/black</item>
+ <item name="android:statusBarColor">@android:color/black</item>
+ </style>
+</resources>
diff --git a/android/build.gradle.kts b/android/build.gradle.kts
new file mode 100644
index 00000000..303619cf
--- /dev/null
+++ b/android/build.gradle.kts
@@ -0,0 +1,8 @@
+// The Android shell: Kotlin and Compose over the shared Rust core, which
+// android/build.sh builds into app/src/main/jniLibs and binds through
+// UniFFI's generated Kotlin.
+plugins {
+ id("com.android.application") version "8.13.0" apply false
+ id("org.jetbrains.kotlin.android") version "2.2.20" apply false
+ id("org.jetbrains.kotlin.plugin.compose") version "2.2.20" apply false
+}
diff --git a/android/build.sh b/android/build.sh
new file mode 100755
index 00000000..483aab63
--- /dev/null
+++ b/android/build.sh
@@ -0,0 +1,61 @@
+#!/bin/sh
+# Build the Android app and, optionally, run it on an emulator.
+#
+# android/build.sh build the Rust library, bindings, assets and APK
+# android/build.sh run ...and boot the emulator, install, launch
+# android/build.sh shot FILE ...and save a screenshot to FILE after launch
+#
+# Needs: the Android SDK at ~/Library/Android/sdk with an NDK, the
+# aarch64-linux-android Rust target, cargo-ndk, and a JDK (Android Studio's).
+set -eu
+cd "$(dirname "$0")/.."
+ROOT=$PWD
+export ANDROID_HOME=${ANDROID_HOME:-$HOME/Library/Android/sdk}
+export ANDROID_NDK_HOME=${ANDROID_NDK_HOME:-$(ls -d "$ANDROID_HOME"/ndk/* | sort -V | tail -1)}
+# Gradle 8.14 does not run on JDK 25 (Android Studio's); a 17 does.
+export JAVA_HOME=${JAVA_HOME:-$(/usr/libexec/java_home -v 17 2>/dev/null || echo "/Applications/Android Studio.app/Contents/jbr/Contents/Home")}
+GRADLE=${GRADLE:-$(command -v gradle || echo "$ROOT/android/gradle-dist/bin/gradle")}
+AVD=${AVD:-ThinkTerm36}
+BUNDLE=com.roversx.thinkterm
+TARGET=aarch64-linux-android
+
+echo "== rust ($TARGET, release) via cargo ndk ($ANDROID_NDK_HOME)"
+cargo ndk -t arm64-v8a -o android/app/src/main/jniLibs build -p thinkterm-mobile --release --lib
+# cargo ndk copies every cdylib it built; the web crate's is for wasm.
+rm -f android/app/src/main/jniLibs/arm64-v8a/libthinkterm_web.so
+
+echo "== bindings"
+rm -rf android/app/src/main/java/com/roversx/thinkterm/core
+cargo run -q -p thinkterm-mobile --bin uniffi-bindgen -- generate \
+ --library target/$TARGET/release/libthinkterm_mobile.so \
+ --language kotlin --out-dir android/app/src/main/java
+
+echo "== assets"
+mkdir -p android/app/src/main/assets
+cp assets/fonts/JetBrainsMono-Regular.ttf assets/fonts/FiraCode-Regular.ttf assets/fonts/SymbolsNerdFontMono-Regular.ttf android/app/src/main/assets/
+cp thinkterm-web/www/schemes.json android/app/src/main/assets/
+# The probe sshd's throwaway key, for the emulator's "This Mac" entry.
+[ -f /tmp/ttp-ssh/userkey ] && cp /tmp/ttp-ssh/userkey android/app/src/main/assets/probe_key || true
+
+echo "== gradle"
+(cd android && "$GRADLE" --quiet assembleDebug 2>&1 | grep -E "error|warning: unused|BUILD|FAIL" || true)
+APK="android/app/build/outputs/apk/debug/app-debug.apk"
+test -f "$APK" || { echo "no APK at $APK" >&2; exit 1; }
+
+[ "${1:-}" = run ] || [ "${1:-}" = shot ] || exit 0
+
+echo "== emulator"
+ADB="$ANDROID_HOME/platform-tools/adb"
+if ! "$ADB" devices | grep -q "emulator-.*device"; then
+ "$ANDROID_HOME/emulator/emulator" -avd "$AVD" -no-snapshot-load -no-boot-anim -no-audio >/dev/null 2>&1 &
+ "$ADB" wait-for-device
+ until [ "$("$ADB" shell getprop sys.boot_completed 2>/dev/null | tr -d '\r')" = "1" ]; do sleep 2; done
+fi
+"$ADB" install -r "$APK" >/dev/null
+"$ADB" shell am force-stop $BUNDLE
+"$ADB" shell am start -n $BUNDLE/.MainActivity ${LAUNCH_ARGS:-} >/dev/null
+if [ "${1:-}" = shot ]; then
+ sleep "${SHOT_DELAY:-6}"
+ "$ADB" exec-out screencap -p > "$2"
+ echo "screenshot: $2"
+fi
diff --git a/android/gradle.properties b/android/gradle.properties
new file mode 100644
index 00000000..589cec0b
--- /dev/null
+++ b/android/gradle.properties
@@ -0,0 +1,3 @@
+org.gradle.jvmargs=-Xmx3g
+android.useAndroidX=true
+kotlin.code.style=official
diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts
new file mode 100644
index 00000000..1a3886c1
--- /dev/null
+++ b/android/settings.gradle.kts
@@ -0,0 +1,16 @@
+pluginManagement {
+ repositories {
+ google()
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+dependencyResolutionManagement {
+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+rootProject.name = "ThinkTerm"
+include(":app")