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.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
android: align the app with iOS
RoversXa11d8847f287
diff --git a/android/.gitignore b/android/.gitignoreindex 3f2f3e40..901dd2f1 100644--- a/android/.gitignore+++ b/android/.gitignore@@ -4,6 +4,7 @@ app/src/main/jniLibs/app/src/main/assets/*.ttfapp/src/main/assets/probe_keyapp/src/main/assets/schemes.json+app/src/main/assets/strings.json.gradle/build/app/build/diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.ktsindex 61e9ea42..75ad115f 100644--- a/android/app/build.gradle.kts+++ b/android/app/build.gradle.kts@@ -39,6 +39,7 @@ dependencies {implementation(platform("androidx.compose:compose-bom:2025.09.00"))implementation("androidx.compose.ui:ui")implementation("androidx.compose.material3:material3")+ implementation("androidx.compose.material:material-icons-extended")implementation("androidx.compose.ui:ui-tooling-preview")implementation("androidx.activity:activity-compose:1.11.0")implementation("androidx.lifecycle:lifecycle-runtime-compose:2.9.4")diff --git a/android/app/src/main/java/com/roversx/thinkterm/AppSettings.kt b/android/app/src/main/java/com/roversx/thinkterm/AppSettings.ktnew file mode 100644index 00000000..2044283a--- /dev/null+++ b/android/app/src/main/java/com/roversx/thinkterm/AppSettings.kt@@ -0,0 +1,128 @@+package com.roversx.thinkterm++import android.content.Context+import android.content.SharedPreferences+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import kotlin.properties.ReadWriteProperty+import kotlin.reflect.KProperty++/// The app's preferences, one object for every screen: the Settings tab+/// edits them with no terminal open, and an open terminal follows them+/// as they change. The keys and values are the iOS app's+/// (ios/Sources/AppSettings.swift), so the two stay one design.+class AppSettings private constructor(private val prefs: SharedPreferences) {+ companion object {+ @Volatile private var instance: AppSettings? = null++ fun get(context: Context): AppSettings = instance ?: synchronized(this) {+ instance ?: AppSettings(+ context.applicationContext.getSharedPreferences("thinkterm-settings", Context.MODE_PRIVATE)+ ).also { instance = it }+ }++ /// Only after `get` has run once (MainActivity does), for code+ /// with no Context at hand.+ val shared: AppSettings get() = instance ?: error("AppSettings.get(context) first")+ }++ // MARK: general++ /// A tag of strings.json, or "system" to follow the phone's.+ var language by pref("lang", "system") { AppLanguage.tag = it }++ // MARK: appearance++ /// A scheme name from schemes.json, or "desktop" to follow the host's.+ var schemeName by pref("scheme.name", Schemes.FOLLOW_DESKTOP)+ /// The text size a connection starts at, in points.+ var fontSize by pref("font.size", 11.0)+ /// One of the bundled faces; a change reconnects to shape with it.+ var fontFamily by pref("font.family", "JetBrains Mono")+ /// "off", "3", "45" or "7": a WCAG floor text is lifted to.+ var contrast by pref("text.contrast", "off")++ // MARK: terminal++ /// Smooth (by the pixel, with inertia) or stepped (whole rows).+ var smoothScroll by pref("scroll.smooth", true)+ /// A thin bar at the right while the scrollback moves.+ var scrollbar by pref("scroll.bar", false)+ /// "auto" (the program's), "block", "bar" or "underline".+ var cursorStyle by pref("cursor.style", "block")+ var cursorBlink by pref("cursor.blink", true)+ /// A pane's bell buzzes the phone.+ var bell by pref("bell", false)+ /// "auto" or "live": the server's panes follow a divider drag as it+ /// goes; "release": once, when the finger lifts.+ var resizeMode by pref("resize.mode", "auto")++ // MARK: interface++ /// "one" or "two" levels of tabs: threads over tabs, or tabs alone.+ var tabBarLevels by pref("ui.tabbar", "two")+ /// The bars over split panes; off, the rows go to the terminal.+ var paneBars by pref("ui.panebars", true)++ // MARK: keyboard++ var hapticKeys by pref("key.haptics", true)+ /// The key panel opens with the software keyboard.+ var autoKeyPanel by pref("key.autopanel", false)++ // MARK: gestures++ var pinchZoom by pref("gesture.pinch", true)+ var twoFingerHidesKeyboard by pref("gesture.twofinger", true)+ var longPressSelects by pref("gesture.longpress", true)++ // MARK: connection++ var autoReconnect by pref("conn.autoreconnect", true)+ /// Seconds between ssh keep-alives, 0 for none; the next connection+ /// takes it.+ var keepAliveSeconds by pref("conn.keepalive", 30)+ /// Hold the connection when the app goes to the background; off,+ /// drop it at once and redial on return.+ var keepSessionInBackground by pref("conn.background", true)++ // MARK: diagnostics++ var devMode by pref("dev.mode", false)++ /// A preference as Compose state: reads subscribe, writes persist.+ private inline fun <reified T> pref(key: String, default: T, crossinline changed: (T) -> Unit = {}) =+ object : ReadWriteProperty<AppSettings, T> {+ private var state by mutableStateOf(load(key, default))++ override fun getValue(thisRef: AppSettings, property: KProperty<*>): T = state++ override fun setValue(thisRef: AppSettings, property: KProperty<*>, value: T) {+ if (state == value) return+ state = value+ store(key, value)+ changed(value)+ }+ }++ @Suppress("UNCHECKED_CAST")+ private fun <T> load(key: String, default: T): T = when (default) {+ is String -> (prefs.getString(key, default) ?: default) as T+ is Boolean -> prefs.getBoolean(key, default) as T+ is Int -> prefs.getInt(key, default) as T+ is Double -> (if (prefs.contains(key)) prefs.getFloat(key, default.toFloat()).toDouble() else default) as T+ else -> default+ }++ private fun <T> store(key: String, value: T) {+ val e = prefs.edit()+ when (value) {+ is String -> e.putString(key, value)+ is Boolean -> e.putBoolean(key, value)+ is Int -> e.putInt(key, value)+ is Double -> e.putFloat(key, value.toFloat())+ }+ e.apply()+ }+}diff --git a/android/app/src/main/java/com/roversx/thinkterm/HostEditScreen.kt b/android/app/src/main/java/com/roversx/thinkterm/HostEditScreen.ktnew file mode 100644index 00000000..e8b7775b--- /dev/null+++ b/android/app/src/main/java/com/roversx/thinkterm/HostEditScreen.kt@@ -0,0 +1,467 @@+package com.roversx.thinkterm++import android.content.ClipData+import android.content.ClipboardManager+import android.content.Context+import android.util.Log+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+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.Column+import androidx.compose.foundation.layout.ColumnScope+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.imePadding+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.foundation.verticalScroll+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.Check+import androidx.compose.material.icons.filled.CheckCircle+import androidx.compose.material.icons.filled.ContentCopy+import androidx.compose.material.icons.filled.ContentPaste+import androidx.compose.material.icons.filled.ExpandLess+import androidx.compose.material.icons.filled.ExpandMore+import androidx.compose.material.icons.filled.Folder+import androidx.compose.material.icons.filled.GppBad+import androidx.compose.material.icons.filled.Lock+import androidx.compose.material.icons.filled.VpnKey+import androidx.compose.material.icons.filled.Warning+import androidx.compose.material3.AlertDialog+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.FilledTonalButton+import androidx.compose.material3.FilterChip+import androidx.compose.material3.Icon+import androidx.compose.material3.LocalTextStyle+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.OutlinedButton+import androidx.compose.material3.OutlinedTextField+import androidx.compose.material3.Scaffold+import androidx.compose.material3.SegmentedButton+import androidx.compose.material3.SegmentedButtonDefaults+import androidx.compose.material3.SingleChoiceSegmentedButtonRow+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.material3.TopAppBar+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+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.graphics.vector.ImageVector+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.input.KeyboardCapitalization+import androidx.compose.ui.text.input.KeyboardType+import androidx.compose.ui.text.input.PasswordVisualTransformation+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.roversx.thinkterm.core.generateSshKey+import com.roversx.thinkterm.core.sshPublicLine+import kotlinx.coroutines.delay++/// Add or edit one host. The private key never travels back out of the+/// encrypted preferences into a field: the editor only reports whether one+/// is stored, and hands a new secret to `onSave` when the user supplies+/// one. Follows ios/Sources/HostEditView.swift.+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun HostEditScreen(+ store: HostStore,+ host: Host,+ onSave: (Host, String, String?) -> Unit,+ onCancel: () -> Unit,+) {+ val context = LocalContext.current+ var draft by remember { mutableStateOf(host) }+ var portText by remember { mutableStateOf(host.port.toString()) }+ var secret by remember { mutableStateOf("") }+ var passphrase by remember { mutableStateOf("") }+ var showKeyText by remember { mutableStateOf(false) }+ var showAdvanced by remember { mutableStateOf(false) }+ var importError by remember { mutableStateOf<String?>(null) }+ var copied by remember { mutableStateOf(false) }+ val hasStoredSecret = remember { store.secret(host.id).isNotEmpty() }+ val isExisting = remember { store.hosts.any { it.id == host.id } }++ val keyComment = "${draft.user}@thinkterm-android"++ /// Only an unencrypted ed25519 key yields a public line; for anything+ /// else the user pastes the public half on the host themselves.+ fun loadKey(text: String) {+ secret = text+ draft = draft.copy(+ publicKey = try {+ sshPublicLine(text, passphrase.ifEmpty { null }, keyComment)+ } catch (e: Throwable) {+ Log.w("thinkterm", "public line failed: $e")+ null+ }+ )+ copied = false+ }++ val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->+ if (uri != null) {+ val text = try {+ context.contentResolver.openInputStream(uri)?.bufferedReader()?.use { it.readText() }+ } catch (e: Throwable) {+ Log.w("thinkterm", "key import failed: $e")+ null+ }+ if (text.isNullOrBlank()) importError = tr("key.notext") else loadKey(text)+ }+ }++ LaunchedEffect(copied) {+ if (copied) {+ delay(1600)+ copied = false+ }+ }++ val canSave = draft.hostname.isNotBlank() && draft.user.isNotBlank() &&+ (isExisting || hasStoredSecret || secret.isNotEmpty())++ Scaffold(+ modifier = Modifier.imePadding(),+ containerColor = MaterialTheme.colorScheme.background,+ topBar = {+ TopAppBar(+ title = {+ Text(+ if (draft.hostname.isBlank()) tr("newhost") else draft.display,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ },+ navigationIcon = { TextButton(onClick = onCancel) { Text(tr("cancel")) } },+ actions = {+ TextButton(+ onClick = { onSave(draft, secret, passphrase.ifEmpty { null }) },+ enabled = canSave,+ ) {+ Text(tr("save"), fontWeight = FontWeight.SemiBold)+ }+ },+ )+ },+ ) { inset ->+ Column(+ Modifier+ .fillMaxSize()+ .padding(inset)+ .verticalScroll(rememberScrollState())+ .padding(bottom = 28.dp),+ ) {+ EditSection(tr("f.host")) {+ EditField(tr("f.name"), draft.name, placeholder = tr("optional")) { draft = draft.copy(name = it) }+ EditField(+ tr("f.hostname"),+ draft.hostname,+ placeholder = "example.com or 10.0.0.4",+ keyboard = KeyboardType.Uri,+ ) { draft = draft.copy(hostname = it.trim()) }+ EditField(tr("f.port"), portText, placeholder = "22", keyboard = KeyboardType.Number) { typed ->+ portText = typed.filter { it.isDigit() }.take(5)+ draft = draft.copy(port = portText.toIntOrNull() ?: 22)+ }+ EditField(tr("f.user"), draft.user, placeholder = "root") { draft = draft.copy(user = it.trim()) }+ }++ EditSection(tr("f.group"), footer = tr("f.groupfoot")) {+ EditField(tr("f.group"), draft.group, placeholder = tr("none")) { draft = draft.copy(group = it) }+ val groups = store.groups+ if (groups.isNotEmpty()) {+ Row(+ Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ for (group in groups) {+ FilterChip(+ selected = draft.group == group,+ onClick = { draft = draft.copy(group = if (draft.group == group) "" else group) },+ label = { Text(group) },+ )+ }+ }+ }+ }++ EditSection(tr("f.auth")) {+ val kinds = listOf("key" to tr("f.key"), "password" to tr("f.password"))+ SingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth()) {+ kinds.forEachIndexed { index, (kind, label) ->+ SegmentedButton(+ selected = draft.auth == kind,+ onClick = { draft = draft.copy(auth = kind) },+ shape = SegmentedButtonDefaults.itemShape(index = index, count = kinds.size),+ ) {+ Text(label)+ }+ }+ }++ if (draft.auth == "key") {+ KeyStatusRow(hasNewSecret = secret.isNotEmpty(), ed25519 = draft.publicKey != null, stored = hasStoredSecret)+ EditActionButton(Icons.Filled.ContentPaste, tr("key.paste")) {+ val pasted = clipboardText(context)+ if (!pasted.isNullOrBlank()) loadKey(pasted)+ }+ EditActionButton(Icons.Filled.Folder, tr("key.import")) { importer.launch(arrayOf("*/*")) }+ EditActionButton(Icons.Filled.VpnKey, tr("key.generate")) {+ val pair = try {+ generateSshKey(keyComment)+ } catch (e: Throwable) {+ Log.w("thinkterm", "key generation failed: $e")+ null+ }+ if (pair != null) {+ secret = pair.privatePem+ draft = draft.copy(publicKey = pair.publicLine)+ copied = false+ }+ }+ draft.publicKey?.takeIf { it.isNotEmpty() }?.let { publicKey ->+ PublicKeyBlock(publicKey, copied) {+ val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager+ cm?.setPrimaryClip(ClipData.newPlainText("thinkterm", publicKey))+ copied = true+ }+ }+ Disclosure(tr("key.pastetext"), showKeyText) { showKeyText = !showKeyText }+ if (showKeyText) {+ OutlinedTextField(+ value = secret,+ onValueChange = { loadKey(it) },+ singleLine = false,+ minLines = 6,+ textStyle = LocalTextStyle.current.copy(fontFamily = FontFamily.Monospace, fontSize = 11.sp),+ keyboardOptions = plainKeyboard(KeyboardType.Ascii),+ modifier = Modifier.fillMaxWidth(),+ )+ }+ OutlinedTextField(+ value = passphrase,+ onValueChange = { passphrase = it },+ label = { Text(tr("key.passphrase")) },+ singleLine = true,+ visualTransformation = PasswordVisualTransformation(),+ keyboardOptions = plainKeyboard(KeyboardType.Password),+ modifier = Modifier.fillMaxWidth(),+ )+ } else {+ OutlinedTextField(+ value = secret,+ onValueChange = { secret = it },+ label = { Text(tr("f.password")) },+ singleLine = true,+ visualTransformation = PasswordVisualTransformation(),+ keyboardOptions = plainKeyboard(KeyboardType.Password),+ modifier = Modifier.fillMaxWidth(),+ )+ }+ }++ EditSection(null) {+ Disclosure(tr("f.advanced"), showAdvanced) { showAdvanced = !showAdvanced }+ if (showAdvanced) {+ EditField(tr("f.remotecmd"), draft.remoteCommand, mono = true) {+ draft = draft.copy(remoteCommand = it)+ }+ Text(+ tr("f.remotecmd.foot"),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ draft.knownHost?.let { known ->+ Text(tr("f.hostkey"), style = MaterialTheme.typography.bodyMedium)+ Text(+ known,+ fontFamily = FontFamily.Monospace,+ fontSize = 11.sp,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ maxLines = 3,+ overflow = TextOverflow.Ellipsis,+ )+ TextButton(onClick = { draft = draft.copy(knownHost = null) }) {+ Icon(+ Icons.Filled.GppBad,+ contentDescription = null,+ tint = MaterialTheme.colorScheme.error,+ modifier = Modifier.size(18.dp),+ )+ Spacer(Modifier.width(8.dp))+ Text(tr("forgetkey"), color = MaterialTheme.colorScheme.error)+ }+ }+ }+ }+ }+ }++ importError?.let { message ->+ AlertDialog(+ onDismissRequest = { importError = null },+ title = { Text(tr("key.importfailed")) },+ text = { Text(message) },+ confirmButton = { TextButton(onClick = { importError = null }) { Text(tr("ok")) } },+ )+ }+}++@Composable+private fun EditSection(title: String?, footer: String? = null, content: @Composable ColumnScope.() -> Unit) {+ Column(+ Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp),+ ) {+ if (title != null) {+ Text(+ title,+ style = MaterialTheme.typography.labelLarge,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.padding(top = 8.dp),+ )+ }+ content()+ if (footer != null) {+ Text(+ footer,+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }+}++@Composable+private fun EditField(+ label: String,+ value: String,+ placeholder: String? = null,+ keyboard: KeyboardType = KeyboardType.Text,+ mono: Boolean = false,+ onChange: (String) -> Unit,+) {+ OutlinedTextField(+ value = value,+ onValueChange = onChange,+ label = { Text(label) },+ placeholder = placeholder?.let { { Text(it) } },+ singleLine = true,+ textStyle = if (mono) {+ LocalTextStyle.current.copy(fontFamily = FontFamily.Monospace, fontSize = 13.sp)+ } else {+ LocalTextStyle.current+ },+ keyboardOptions = plainKeyboard(keyboard),+ modifier = Modifier.fillMaxWidth(),+ )+}++/// Nothing here is prose: no capitals of its own, no autocorrect.+private fun plainKeyboard(keyboard: KeyboardType) = KeyboardOptions(+ keyboardType = keyboard,+ capitalization = KeyboardCapitalization.None,+ autoCorrectEnabled = false,+)++@Composable+private fun KeyStatusRow(hasNewSecret: Boolean, ed25519: Boolean, stored: Boolean) {+ val green = Color(0xFF30D158)+ val (icon, tint, text) = when {+ hasNewSecret && ed25519 -> Triple(Icons.Filled.CheckCircle, green, tr("key.loaded.ed25519"))+ hasNewSecret -> Triple(Icons.Filled.CheckCircle, green, tr("key.loaded"))+ stored -> Triple(Icons.Filled.Lock, green, tr("key.stored"))+ else -> Triple(Icons.Filled.Warning, Color(0xFFFF9F0A), tr("key.none"))+ }+ Row(verticalAlignment = Alignment.CenterVertically) {+ Icon(icon, contentDescription = null, tint = tint, modifier = Modifier.size(18.dp))+ Spacer(Modifier.width(10.dp))+ Text(text, style = MaterialTheme.typography.bodyMedium)+ }+}++@Composable+private fun EditActionButton(icon: ImageVector, label: String, onClick: () -> Unit) {+ OutlinedButton(onClick = onClick, modifier = Modifier.fillMaxWidth()) {+ Icon(icon, contentDescription = null, modifier = Modifier.size(18.dp))+ Spacer(Modifier.width(10.dp))+ Text(label, modifier = Modifier.weight(1f), textAlign = TextAlign.Start)+ }+}++@Composable+private fun PublicKeyBlock(publicKey: String, copied: Boolean, onCopy: () -> Unit) {+ Column(+ Modifier+ .fillMaxWidth()+ .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f), RoundedCornerShape(10.dp))+ .padding(12.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ Text(+ publicKey,+ fontFamily = FontFamily.Monospace,+ fontSize = 11.sp,+ lineHeight = 15.sp,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ maxLines = 4,+ overflow = TextOverflow.Ellipsis,+ )+ FilledTonalButton(onClick = onCopy) {+ Icon(+ if (copied) Icons.Filled.Check else Icons.Filled.ContentCopy,+ contentDescription = null,+ modifier = Modifier.size(18.dp),+ )+ Spacer(Modifier.width(8.dp))+ Text(if (copied) tr("copied") else tr("key.copypub"))+ }+ Text(+ tr("key.authorized"),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+}++@Composable+private fun Disclosure(label: String, expanded: Boolean, onToggle: () -> Unit) {+ Row(+ Modifier.fillMaxWidth().clickable(onClick = onToggle).height(44.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(label, modifier = Modifier.weight(1f), style = MaterialTheme.typography.titleSmall)+ Icon(+ if (expanded) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore,+ contentDescription = null,+ tint = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+}++private fun clipboardText(context: Context): String? {+ val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager ?: return null+ val clip = cm.primaryClip ?: return null+ if (clip.itemCount == 0) return null+ return clip.getItemAt(0).coerceToText(context)?.toString()+}diff --git a/android/app/src/main/java/com/roversx/thinkterm/HostStore.kt b/android/app/src/main/java/com/roversx/thinkterm/HostStore.ktindex 5bcac08c..b7d1e1c3 100644--- a/android/app/src/main/java/com/roversx/thinkterm/HostStore.kt+++ b/android/app/src/main/java/com/roversx/thinkterm/HostStore.kt@@ -26,8 +26,18 @@ data class Host(val knownHost: String? = null,/// Empty means the default proxy command on the host.val remoteCommand: String = "",+ /// A label the list groups by; empty is no group.+ val group: String = "",+ /// The public half of a key the app generated or could read, so it+ /// can be shown and copied to the host's authorized_keys.+ val publicKey: String? = null,+ /// Unix milliseconds of the last connection that reached a pane.+ val lastConnected: Long? = null,) {val display: String get() = if (name.isNotEmpty()) name else "$user@$hostname:$port"+ /// The headline of a row: `display` would repeat the address below it+ /// when the host has no name.+ val title: String get() = name.ifEmpty { hostname }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@@ -80,6 +90,36 @@ class HostStore(context: Context) {save()}+ /// A connection reached the terminal: the list shows when.+ fun touchConnected(id: String) {+ val at = hosts.indexOfFirst { it.id == id }+ if (at < 0) return+ hosts = hosts.toMutableList().also { it[at] = it[at].copy(lastConnected = System.currentTimeMillis()) }+ save()+ }++ fun forgetHostKey(id: String) {+ val at = hosts.indexOfFirst { it.id == id }+ if (at < 0 || hosts[at].knownHost == null) return+ hosts = hosts.toMutableList().also { it[at] = it[at].copy(knownHost = null) }+ save()+ }++ /// The groups in use, for the editor's suggestions.+ val groups: List<String> get() = hosts.map { it.group }.filter { it.isNotEmpty() }.distinct().sorted()++ /// A copy under a new id, with the secret copied across so the+ /// duplicate connects without being re-keyed.+ fun duplicate(host: Host, nameSuffix: String) {+ val copy = host.copy(+ id = UUID.randomUUID().toString(),+ name = host.name.ifEmpty { host.display } + nameSuffix,+ lastConnected = null,+ )+ putSecret(copy.id, secret(host.id), passphrase(host.id))+ upsert(copy)+ }+fun rememberHostKey(id: String, fingerprint: String) {val at = hosts.indexOfFirst { it.id == id }if (at < 0 || hosts[at].knownHost == fingerprint) return@@ -110,6 +150,9 @@ class HostStore(context: Context) {.put("auth", h.auth).put("knownHost", h.knownHost ?: JSONObject.NULL).put("remoteCommand", h.remoteCommand)+ .put("group", h.group)+ .put("publicKey", h.publicKey ?: JSONObject.NULL)+ .put("lastConnected", h.lastConnected ?: JSONObject.NULL))}prefs.edit().putString(KEY, arr.toString()).apply()@@ -130,6 +173,9 @@ class HostStore(context: Context) {auth = o.optString("auth", "key"),knownHost = o.optString("knownHost").ifEmpty { null },remoteCommand = o.optString("remoteCommand"),+ group = o.optString("group"),+ publicKey = o.optString("publicKey").ifEmpty { null },+ lastConnected = if (o.isNull("lastConnected")) null else o.optLong("lastConnected"),)}} catch (e: Throwable) {diff --git a/android/app/src/main/java/com/roversx/thinkterm/HostsScreen.kt b/android/app/src/main/java/com/roversx/thinkterm/HostsScreen.ktindex e515e4a2..50fb805c 100644--- a/android/app/src/main/java/com/roversx/thinkterm/HostsScreen.kt+++ b/android/app/src/main/java/com/roversx/thinkterm/HostsScreen.kt@@ -1,23 +1,51 @@package com.roversx.thinkterm+import android.text.format.DateUtils+import androidx.activity.compose.BackHandler+import androidx.compose.foundation.ExperimentalFoundationApiimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.clickable+import androidx.compose.foundation.combinedClickableimport androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValuesimport androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacerimport androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.imePadding-import androidx.compose.foundation.layout.safeDrawingPaddingimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.heightimport androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.widthimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.items-import androidx.compose.foundation.rememberScrollState-import androidx.compose.foundation.text.KeyboardOptions-import androidx.compose.foundation.verticalScroll+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.Add+import androidx.compose.material.icons.filled.Bolt+import androidx.compose.material.icons.filled.Close+import androidx.compose.material.icons.filled.ContentCopy+import androidx.compose.material.icons.filled.Delete+import androidx.compose.material.icons.filled.Dns+import androidx.compose.material.icons.filled.Edit+import androidx.compose.material.icons.filled.GppBad+import androidx.compose.material.icons.filled.Hardware+import androidx.compose.material.icons.filled.Search+import androidx.compose.material3.AlertDialogimport androidx.compose.material3.Button+import androidx.compose.material3.DropdownMenu+import androidx.compose.material3.DropdownMenuItem+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.HorizontalDivider+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButton+import androidx.compose.material3.LargeTopAppBar+import androidx.compose.material3.ListItem+import androidx.compose.material3.ListItemDefaults+import androidx.compose.material3.MaterialThemeimport androidx.compose.material3.OutlinedTextField+import androidx.compose.material3.Scaffoldimport androidx.compose.material3.Textimport androidx.compose.material3.TextButtonimport androidx.compose.runtime.Composable@@ -27,150 +55,351 @@ import androidx.compose.runtime.rememberimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Brushimport androidx.compose.ui.graphics.Color-import androidx.compose.ui.text.input.KeyboardType+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflowimport 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.+/// The saved hosts, searched and grouped, plus — in a debuggable build —+/// the entry that reaches the probe sshd on the developer's Mac. The+/// editor takes the whole screen; system back closes it.+/// Follows ios/Sources/HostsView.swift.+@OptIn(ExperimentalMaterial3Api::class)@Composablefun HostsScreen(store: HostStore, showProbe: Boolean, onOpen: (Host) -> Unit) {var editing by remember { mutableStateOf<Host?>(null) }+ var search by remember { mutableStateOf("") }+ var pendingDelete by remember { mutableStateOf<Host?>(null) }- editing?.let { host ->- HostEditor(store, host, onDone = { editing = null })+ val target = editing+ if (target != null) {+ BackHandler { editing = null }+ HostEditScreen(+ store = store,+ host = target,+ onSave = { host, secret, passphrase ->+ // A host with nothing stored needs this save to write the+ // secret; an empty field on an edit keeps the stored one.+ if (secret.isNotEmpty() || store.secret(host.id).isEmpty()) {+ store.putSecret(host.id, secret, passphrase)+ }+ store.upsert(host)+ editing = null+ },+ onCancel = { editing = null },+ )return}- Column(- Modifier- .fillMaxSize()- .background(Color(0xFF111111))- .safeDrawingPadding()- ) {- Row(- Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),- verticalAlignment = Alignment.CenterVertically,+ val hosts = store.hosts+ val matches = remember(hosts, search) { matchingHosts(hosts, search) }+ val sections = remember(hosts, matches) { hostSections(hosts, matches) }++ Scaffold(+ containerColor = MaterialTheme.colorScheme.background,+ topBar = {+ LargeTopAppBar(+ title = { Text(tr("hosts")) },+ actions = {+ IconButton(onClick = { editing = Host() }) {+ Icon(Icons.Filled.Add, contentDescription = tr("hosts.add"))+ }+ },+ )+ },+ ) { inset ->+ LazyColumn(+ Modifier.fillMaxSize().padding(inset),+ contentPadding = PaddingValues(bottom = 28.dp),) {- 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 { HostSearchField(search) { search = it } }++ if (hosts.isEmpty()) {+ item { HostsEmptyState { editing = Host() } }+ } else if (matches.isEmpty()) {item {- HostRow(Host.probe, onOpen = { onOpen(Host.probe) }, onEdit = null)+ Text(+ tr("hosts.nomatch.q", search),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 24.dp, vertical = 28.dp),+ )+ }+ } else {+ val grouped = sections.size > 1 || sections.firstOrNull()?.title != null+ for (section in sections) {+ if (grouped) {+ item(key = "g:" + (section.title ?: "")) {+ HostGroupHeader(section.title ?: tr("hosts.other"))+ }+ }+ items(section.hosts, key = { it.id }) { host ->+ HostListRow(+ host = host,+ onOpen = { onOpen(host) },+ onEdit = { editing = host },+ onDuplicate = { store.duplicate(host, tr("host.copysuffix")) },+ onForgetKey = { store.forgetHostKey(host.id) },+ onDelete = { pendingDelete = host },+ )+ }}}- 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),++ if (showProbe) {+ item(key = "dev-header") { HostGroupHeader(tr("dev")) }+ item(key = Host.PROBE_ID) {+ ListItem(+ modifier = Modifier.clickable { onOpen(Host.probe) },+ colors = ListItemDefaults.colors(containerColor = Color.Transparent),+ leadingContent = { HostDisc(Icons.Filled.Hardware, Color(0xFF8E8E93)) },+ headlineContent = { Text(tr("thismac"), fontWeight = FontWeight.SemiBold) },+ supportingContent = {+ Text("probe sshd on ${Host.probe.hostname}:${Host.probe.port}")+ },)}}}}++ pendingDelete?.let { host ->+ AlertDialog(+ onDismissRequest = { pendingDelete = null },+ title = { Text(tr("host.delete.title")) },+ text = { Text(tr("host.delete.body")) },+ confirmButton = {+ TextButton(onClick = { store.remove(host); pendingDelete = null }) {+ Text(tr("host.delete.confirm", host.display), color = MaterialTheme.colorScheme.error)+ }+ },+ dismissButton = {+ TextButton(onClick = { pendingDelete = null }) { Text(tr("cancel")) }+ },+ )+ }}@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) }- }- }+private fun HostSearchField(search: String, onChange: (String) -> Unit) {+ OutlinedTextField(+ value = search,+ onValueChange = onChange,+ placeholder = { Text(tr("hosts.search")) },+ singleLine = true,+ leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },+ trailingIcon = {+ if (search.isNotEmpty()) {+ IconButton(onClick = { onChange("") }) {+ Icon(Icons.Filled.Close, contentDescription = tr("cancel"))+ }+ }+ },+ modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp),+ )}-/// 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) }+private fun HostGroupHeader(title: String) {+ Text(+ title,+ style = MaterialTheme.typography.labelLarge,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 18.dp, bottom = 4.dp),+ )+}- 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)+/// One host: the disc, the name, the address, and a line with when it was+/// last reached and how it authenticates. Long press opens the menu.+@OptIn(ExperimentalFoundationApi::class)+@Composable+private fun HostListRow(+ host: Host,+ onOpen: () -> Unit,+ onEdit: () -> Unit,+ onDuplicate: () -> Unit,+ onForgetKey: () -> Unit,+ onDelete: () -> Unit,+) {+ var menu by remember { mutableStateOf(false) }+ Box {+ ListItem(+ modifier = Modifier.combinedClickable(onClick = onOpen, onLongClick = { menu = true }),+ colors = ListItemDefaults.colors(containerColor = Color.Transparent),+ leadingContent = { HostDisc(Icons.Filled.Dns, host.tint) },+ headlineContent = {+ Text(host.title, maxLines = 1, overflow = TextOverflow.Ellipsis, fontWeight = FontWeight.SemiBold)+ },+ supportingContent = {+ Column {+ Text(host.address, maxLines = 1, overflow = TextOverflow.Ellipsis)+ Row(+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(6.dp),+ modifier = Modifier.padding(top = 3.dp),+ ) {+ Text(+ host.lastConnectedText,+ style = MaterialTheme.typography.labelSmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ AuthBadge(host)+ }}- }- }- 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,- )+ },+ trailingContent = {+ IconButton(onClick = onEdit) {+ Icon(Icons.Filled.Edit, contentDescription = tr("edit"))+ }+ },+ )+ DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {+ DropdownMenuItem(+ text = { Text(tr("connect")) },+ leadingIcon = { Icon(Icons.Filled.Bolt, contentDescription = null) },+ onClick = { menu = false; onOpen() },+ )+ DropdownMenuItem(+ text = { Text(tr("edit")) },+ leadingIcon = { Icon(Icons.Filled.Edit, contentDescription = null) },+ onClick = { menu = false; onEdit() },+ )+ DropdownMenuItem(+ text = { Text(tr("duplicate")) },+ leadingIcon = { Icon(Icons.Filled.ContentCopy, contentDescription = null) },+ onClick = { menu = false; onDuplicate() },+ )+ if (host.knownHost != null) {+ DropdownMenuItem(+ text = { Text(tr("forgetkey")) },+ leadingIcon = { Icon(Icons.Filled.GppBad, contentDescription = null) },+ onClick = { menu = false; onForgetKey() },)- onDone()- }) { Text("Save") }- TextButton(onClick = onDone) { Text("Cancel") }- if (store.hosts.any { it.id == host.id }) {- TextButton(onClick = { store.remove(host); onDone() }) { Text("Delete") }}+ HorizontalDivider()+ DropdownMenuItem(+ text = { Text(tr("delete"), color = MaterialTheme.colorScheme.error) },+ leadingIcon = {+ Icon(Icons.Filled.Delete, contentDescription = null, tint = MaterialTheme.colorScheme.error)+ },+ onClick = { menu = false; onDelete() },+ )}}}@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(),+private fun AuthBadge(host: Host) {+ Text(+ if (host.auth == "key") tr("badge.key") else tr("badge.password"),+ style = MaterialTheme.typography.labelSmall,+ fontWeight = FontWeight.SemiBold,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier+ .background(MaterialTheme.colorScheme.onSurface.copy(alpha = 0.16f), CircleShape)+ .padding(horizontal = 7.dp, vertical = 2.dp),)}++/// The tinted disc a row leads with; the gradient is the iOS row's.+@Composable+private fun HostDisc(icon: ImageVector, tint: Color) {+ Box(+ Modifier+ .size(40.dp)+ .background(Brush.verticalGradient(listOf(tint, tint.copy(alpha = 0.72f))), CircleShape),+ contentAlignment = Alignment.Center,+ ) {+ Icon(icon, contentDescription = null, tint = Color.White, modifier = Modifier.size(19.dp))+ }+}++@Composable+private fun HostsEmptyState(add: () -> Unit) {+ Column(+ Modifier.fillMaxWidth().padding(horizontal = 28.dp, vertical = 40.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ Icon(+ Icons.Filled.Dns,+ contentDescription = null,+ tint = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.size(46.dp),+ )+ Spacer(Modifier.height(14.dp))+ Text(tr("hosts.empty"), style = MaterialTheme.typography.titleMedium)+ Spacer(Modifier.height(6.dp))+ Text(+ tr("hosts.empty.body"),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ textAlign = TextAlign.Center,+ )+ Spacer(Modifier.height(18.dp))+ Button(onClick = add, modifier = Modifier.fillMaxWidth()) {+ Icon(Icons.Filled.Add, contentDescription = null)+ Spacer(Modifier.width(8.dp))+ Text(tr("hosts.add"))+ }+ }+}++private data class HostSection(val title: String?, val hosts: List<Host>)++private fun matchingHosts(hosts: List<Host>, search: String): List<Host> {+ val query = search.trim().lowercase()+ if (query.isEmpty()) return hosts+ return hosts.filter { host ->+ listOf(host.name, host.hostname, host.user, host.group).any { it.lowercase().contains(query) }+ }+}++/// One section per group once any host has one, ungrouped hosts last; a+/// single title-less section when nobody uses groups.+private fun hostSections(all: List<Host>, matches: List<Host>): List<HostSection> {+ if (all.none { it.group.isNotEmpty() }) return listOf(HostSection(null, matches))+ val byGroup = matches.groupBy { it.group }+ val out = byGroup.keys.filter { it.isNotEmpty() }.sorted()+ .map { HostSection(it, byGroup[it].orEmpty()) }+ .toMutableList()+ byGroup[""]?.takeIf { it.isNotEmpty() }?.let { out.add(HostSection(null, it)) }+ return out+}++private val HOST_PALETTE = listOf(+ Color(0xFF0A84FF), // blue+ Color(0xFF5E5CE6), // indigo+ Color(0xFFBF5AF2), // purple+ Color(0xFFFF375F), // pink+ Color(0xFFFF9F0A), // orange+ Color(0xFF40CBE0), // teal+ Color(0xFF30D158), // green+ Color(0xFF64D2FF), // cyan+)++/// A stable colour per host: the djb2 hash the iOS app uses, so a host+/// wears the same colour on both phones.+private val Host.tint: Color+ get() {+ var hash = 5381UL+ for (byte in (name + hostname + user).toByteArray()) {+ hash = hash * 33UL + byte.toUByte().toULong()+ }+ return HOST_PALETTE[(hash % HOST_PALETTE.size.toULong()).toInt()]+ }++/// "13m ago", or the never-connected line. The phone's locale formats it;+/// iOS follows the app's language, which Android has no formatter for.+private val Host.lastConnectedText: String+ get() {+ val last = lastConnected ?: return tr("hosts.never")+ return DateUtils.getRelativeTimeSpanString(+ last,+ System.currentTimeMillis(),+ DateUtils.MINUTE_IN_MILLIS,+ ).toString()+ }diff --git a/android/app/src/main/java/com/roversx/thinkterm/KeyBar.kt b/android/app/src/main/java/com/roversx/thinkterm/KeyBar.ktindex 2e43b9bc..345c2900 100644--- a/android/app/src/main/java/com/roversx/thinkterm/KeyBar.kt+++ b/android/app/src/main/java/com/roversx/thinkterm/KeyBar.kt@@ -4,92 +4,129 @@ import androidx.compose.foundation.backgroundimport androidx.compose.foundation.clickableimport androidx.compose.foundation.horizontalScrollimport androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.heightimport androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.widthimport androidx.compose.foundation.rememberScrollStateimport androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.GridView+import androidx.compose.material.icons.filled.KeyboardArrowDown+import androidx.compose.material3.Icon+import androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Textimport androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.graphics.Color+import androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.text.font.FontFamilyimport androidx.compose.ui.unit.dpimport 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, with sticky Ctrl and Alt, and at+/// the row's right end — fixed, never scrolling away — the button that+/// opens the extension panel underneath, where the rest of the keys, the+/// snippets, the history and the colours live. From ios KeyBar.swift.+@Composable+fun KeyBar(+ model: TerminalModel,+ keyboardUp: Boolean,+ onOpenSettings: () -> Unit,+ modifier: Modifier = Modifier,+) {+ val context = LocalContext.current+ val history = remember(context) { KeyHistory.get(context) }+ val tap = rememberKeyTap(model)+ var panelOpen by remember { mutableStateOf(false) }+ var tab by remember { mutableStateOf(KeyPanelTab.KEYS) }-/// 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"),-)+ // The panel joins the soft keyboard when the setting asks it to.+ LaunchedEffect(keyboardUp) {+ if (model.settings.autoKeyPanel) panelOpen = keyboardUp+ }-@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+ Column(modifier.fillMaxWidth().background(model.background)) {+ Row(+ Modifier.fillMaxWidth().height(38.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Row(+ Modifier+ .weight(1f)+ .horizontalScroll(rememberScrollState())+ .padding(horizontal = 6.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(6.dp),+ ) {+ for (cap in KeyCaps.bar) {+ BarKey(cap, held = isHeld(cap, model)) {+ KeyCaps.send(cap, model, history, tap)+ }+ }}- 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),- )+ MoreButton(open = panelOpen) {+ panelOpen = !panelOpen+ tap()+ }+ }+ if (panelOpen) {+ KeyPanel(model, tab, { tab = it }, onOpenSettings)}}}-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+/// A sticky modifier shows as pressed until the next key spends it.+private fun isHeld(cap: KeyCap, model: TerminalModel): Boolean = when {+ cap !is KeyCap.Sticky -> false+ cap.mod == KeyCap.Mod.CTRL -> model.ctrlSticky+ else -> model.altSticky+}++@Composable+private fun BarKey(cap: KeyCap, held: Boolean, onClick: () -> Unit) {+ Text(+ cap.label,+ color = Color.White,+ fontSize = 13.sp,+ fontFamily = FontFamily.Monospace,+ maxLines = 1,+ softWrap = false,+ modifier = Modifier+ .clip(RoundedCornerShape(6.dp))+ .background(if (held) MaterialTheme.colorScheme.primary else Color.White.copy(alpha = 0.08f))+ .clickable(onClick = onClick)+ .padding(horizontal = 10.dp, vertical = 6.dp),+ )+}++@Composable+private fun MoreButton(open: Boolean, onClick: () -> Unit) {+ Box(+ Modifier+ .padding(start = 4.dp, end = 6.dp)+ .width(40.dp)+ .height(28.dp)+ .clip(RoundedCornerShape(7.dp))+ .background(if (open) MaterialTheme.colorScheme.primary else Color.White.copy(alpha = 0.14f))+ .clickable(onClick = onClick),+ contentAlignment = Alignment.Center,+ ) {+ Icon(+ if (open) Icons.Filled.KeyboardArrowDown else Icons.Filled.GridView,+ contentDescription = tr("p.panel"),+ tint = Color.White,+ modifier = Modifier.height(18.dp).width(18.dp),+ )}}diff --git a/android/app/src/main/java/com/roversx/thinkterm/KeyPanel.kt b/android/app/src/main/java/com/roversx/thinkterm/KeyPanel.ktnew file mode 100644index 00000000..b21771d4--- /dev/null+++ b/android/app/src/main/java/com/roversx/thinkterm/KeyPanel.kt@@ -0,0 +1,638 @@+package com.roversx.thinkterm++import android.view.HapticFeedbackConstants+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.grid.GridCells+import androidx.compose.foundation.lazy.grid.LazyHorizontalGrid+import androidx.compose.foundation.lazy.grid.items+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.foundation.verticalScroll+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.Add+import androidx.compose.material.icons.filled.ContentPaste+import androidx.compose.material.icons.filled.DesktopWindows+import androidx.compose.material.icons.filled.Settings+import androidx.compose.material.icons.filled.Tune+import androidx.compose.material3.AlertDialog+import androidx.compose.material3.Icon+import androidx.compose.material3.LocalTextStyle+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.OutlinedTextField+import androidx.compose.material3.SegmentedButton+import androidx.compose.material3.SegmentedButtonDefaults+import androidx.compose.material3.SingleChoiceSegmentedButtonRow+import androidx.compose.material3.Switch+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.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalView+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.text.input.KeyboardCapitalization+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp++/// One key, on the bar or in the panel: what it says and what it sends.+/// The same shape as ios/Sources/KeyPanel.swift's `KeyCap`.+sealed interface KeyCap {+ val label: String++ /// A key by its DOM name, as the core takes it.+ data class Dom(+ override val label: String,+ val name: String,+ val ctrl: Boolean = false,+ val shift: Boolean = false,+ ) : KeyCap++ /// Typed text, the character itself.+ data class Txt(override val label: String) : KeyCap++ /// Ctrl or Alt held for the next key only.+ data class Sticky(override val label: String, val mod: Mod) : KeyCap++ enum class Mod { CTRL, ALT }+}++/// The key bar's row and the panel's grids, and the one place a cap turns+/// into input.+object KeyCaps {+ private fun dom(label: String, name: String, ctrl: Boolean = false, shift: Boolean = false) =+ KeyCap.Dom(label, name, ctrl, shift)++ /// The bar under the terminal: the keys a soft keyboard has not got.+ val bar: List<KeyCap> = listOf(+ dom("esc", "Escape"),+ dom("tab", "Tab"),+ KeyCap.Sticky("ctrl", KeyCap.Mod.CTRL),+ KeyCap.Sticky("alt", KeyCap.Mod.ALT),+ dom("↑", "ArrowUp"),+ dom("↓", "ArrowDown"),+ dom("←", "ArrowLeft"),+ dom("→", "ArrowRight"),+ dom("home", "Home"),+ dom("end", "End"),+ dom("pgup", "PageUp"),+ dom("pgdn", "PageDown"),+ KeyCap.Txt("-"),+ KeyCap.Txt("/"),+ KeyCap.Txt("|"),+ KeyCap.Txt("~"),+ dom("^C", "c", ctrl = true),+ dom("^D", "d", ctrl = true),+ dom("^L", "l", ctrl = true),+ dom("^Z", "z", ctrl = true),+ dom("⌫", "Backspace"),+ )++ val functions: List<KeyCap> = (1..12).map { dom("F$it", "F$it") }++ val navigation: List<KeyCap> = listOf(+ dom("ins", "Insert"),+ dom("del", "Delete"),+ dom("home", "Home"),+ dom("end", "End"),+ dom("pgup", "PageUp"),+ dom("pgdn", "PageDown"),+ dom("←", "ArrowLeft"),+ dom("↑", "ArrowUp"),+ dom("↓", "ArrowDown"),+ dom("→", "ArrowRight"),+ dom("⇧tab", "Tab", shift = true),+ dom("⏎", "Enter"),+ )++ val symbols: List<KeyCap> = listOf(+ "-", "=", "/", "|", "~", "^",+ ":", ";", "!", "*", "$", "%",+ "<", ">", "(", ")", "{", "}",+ "[", "]", "'", "\"", "`", "\\",+ ).map { KeyCap.Txt(it) }++ /// The chords a terminal wants and a phone cannot type.+ val chords: List<KeyCap> = listOf("a", "c", "d", "e", "k", "l", "r", "u", "w", "x", "y", "z")+ .map { dom("^${it.uppercase()}", it, ctrl = true) }++ /// Send one cap. Sticky Ctrl and Alt toggle here and are spent by the+ /// model on the next key; typed text joins the history.+ fun send(cap: KeyCap, model: TerminalModel, history: KeyHistory, tap: () -> Unit) {+ when (cap) {+ is KeyCap.Dom -> model.key(cap.name, ctrl = cap.ctrl, shift = cap.shift)+ is KeyCap.Txt -> {+ model.text(cap.label)+ history.record(cap.label)+ }+ is KeyCap.Sticky -> when (cap.mod) {+ KeyCap.Mod.CTRL -> model.ctrlSticky = !model.ctrlSticky+ KeyCap.Mod.ALT -> model.altSticky = !model.altSticky+ }+ }+ tap()+ }+}++/// The little knock under a key, when the setting asks for it.+@Composable+fun rememberKeyTap(model: TerminalModel): () -> Unit {+ val view = LocalView.current+ return remember(view, model) {+ {+ if (model.settings.hapticKeys) {+ view.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP)+ }+ }+ }+}++/// The four faces of the extension panel.+enum class KeyPanelTab {+ KEYS, SNIPPETS, HISTORY, COLORS;++ val title: String+ get() = when (this) {+ KEYS -> tr("p.keys")+ SNIPPETS -> tr("p.snippets")+ HISTORY -> tr("p.history")+ COLORS -> tr("p.colors")+ }+}++/// The panel under the key bar: the keys a phone keyboard has not got,+/// the user's snippets, what they sent last, and the colour schemes — on+/// the terminal's own background, as ios/Sources/KeyPanel.swift.+@Composable+fun KeyPanel(+ model: TerminalModel,+ tab: KeyPanelTab,+ onTab: (KeyPanelTab) -> Unit,+ onOpenSettings: () -> Unit,+) {+ val context = LocalContext.current+ val history = remember(context) { KeyHistory.get(context) }+ val store = remember(context) { SnippetStore.get(context) }+ val tap = rememberKeyTap(model)++ Column(+ Modifier+ .fillMaxWidth()+ // iOS pads for the home indicator; here the screen's own+ // safe-drawing padding already keeps the gesture bar clear.+ .height(268.dp)+ .background(model.background)+ ) {+ Row(+ Modifier+ .fillMaxWidth()+ .padding(horizontal = 10.dp)+ .padding(top = 8.dp, bottom = 6.dp),+ horizontalArrangement = Arrangement.spacedBy(10.dp),+ ) {+ Chip(Icons.Filled.Settings, tr("p.customize"), Modifier.weight(1f), onOpenSettings)+ Chip(Icons.Filled.ContentPaste, tr("paste"), Modifier.weight(1f)) { model.pasteFromClipboard() }+ }++ Box(Modifier.fillMaxWidth().weight(1f)) {+ when (tab) {+ KeyPanelTab.KEYS -> KeysFace(model, history, tap)+ KeyPanelTab.SNIPPETS -> SnippetsFace(model, store, history, tap)+ KeyPanelTab.HISTORY -> HistoryFace(model, history, tap)+ KeyPanelTab.COLORS -> ColorsFace(model, tap)+ }+ }++ Box(Modifier.fillMaxWidth().height(0.5.dp).background(Color.White.copy(alpha = 0.08f)))++ SingleChoiceSegmentedButtonRow(+ Modifier+ .fillMaxWidth()+ .padding(horizontal = 10.dp, vertical = 8.dp)+ ) {+ val tabs = KeyPanelTab.entries+ tabs.forEachIndexed { index, entry ->+ SegmentedButton(+ selected = tab == entry,+ onClick = { onTab(entry) },+ shape = SegmentedButtonDefaults.itemShape(index, tabs.size),+ icon = {},+ label = { Text(entry.title, fontSize = 12.sp, maxLines = 1) },+ )+ }+ }+ }+}++// MARK: keys++@Composable+private fun KeysFace(model: TerminalModel, history: KeyHistory, tap: () -> Unit) {+ Column(+ Modifier+ .fillMaxSize()+ .verticalScroll(rememberScrollState())+ .padding(horizontal = 10.dp, vertical = 6.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp),+ ) {+ KeyBlock(tr("k.function"), KeyCaps.functions, model, history, tap)+ KeyBlock(tr("k.navigation"), KeyCaps.navigation, model, history, tap)+ KeyBlock(tr("k.symbols"), KeyCaps.symbols, model, history, tap)+ KeyBlock(tr("k.control"), KeyCaps.chords, model, history, tap)+ }+}++/// One titled block of keys, six to a row. Plain rows, not a lazy grid:+/// the face above scrolls, and sixty keys are cheap to lay out.+@Composable+private fun KeyBlock(+ title: String,+ caps: List<KeyCap>,+ model: TerminalModel,+ history: KeyHistory,+ tap: () -> Unit,+) {+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {+ Text(+ title.uppercase(),+ color = Color.White.copy(alpha = 0.45f),+ fontSize = 10.sp,+ fontWeight = FontWeight.SemiBold,+ letterSpacing = 0.6.sp,+ )+ for (row in caps.chunked(6)) {+ Row(+ Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ for (cap in row) {+ PanelKey(cap, Modifier.weight(1f)) { KeyCaps.send(cap, model, history, tap) }+ }+ // A short last row keeps the other keys their own width.+ repeat(6 - row.size) { Box(Modifier.weight(1f)) }+ }+ }+ }+}++@Composable+private fun PanelKey(cap: KeyCap, modifier: Modifier, onClick: () -> Unit) {+ Box(+ modifier+ .height(38.dp)+ .clip(RoundedCornerShape(10.dp))+ .background(Color.White.copy(alpha = 0.07f))+ .clickable(onClick = onClick),+ contentAlignment = Alignment.Center,+ ) {+ Text(+ cap.label,+ color = Color.White,+ fontSize = 13.sp,+ fontFamily = FontFamily.Monospace,+ maxLines = 1,+ softWrap = false,+ )+ }+}++// MARK: snippets++@Composable+private fun SnippetsFace(+ model: TerminalModel,+ store: SnippetStore,+ history: KeyHistory,+ tap: () -> Unit,+) {+ var draft by remember { mutableStateOf<SnippetDraft?>(null) }++ Column(+ Modifier+ .fillMaxSize()+ .verticalScroll(rememberScrollState())+ .padding(horizontal = 10.dp, vertical = 6.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ for (snippet in store.items) {+ Row(+ Modifier+ .fillMaxWidth()+ .height(42.dp)+ .clip(RoundedCornerShape(11.dp))+ .background(Color.White.copy(alpha = 0.07f)),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Row(+ Modifier+ .weight(1f)+ .fillMaxSize()+ .clickable {+ model.text(snippet.text)+ if (snippet.runs) model.key("Enter")+ history.record(snippet.text)+ tap()+ }+ .padding(start = 12.dp, end = 8.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(10.dp),+ ) {+ Text(+ snippet.text,+ color = Color.White,+ fontSize = 13.sp,+ fontFamily = FontFamily.Monospace,+ maxLines = 1,+ overflow = TextOverflow.MiddleEllipsis,+ modifier = Modifier.weight(1f),+ )+ if (snippet.runs) {+ Text(tr("p.run"), color = MaterialTheme.colorScheme.primary, fontSize = 12.sp)+ }+ }+ Box(+ Modifier+ .width(40.dp)+ .fillMaxSize()+ .clickable { draft = SnippetDraft(snippet, isNew = false) },+ contentAlignment = Alignment.Center,+ ) {+ Icon(+ Icons.Filled.Tune,+ contentDescription = tr("snip.title"),+ tint = Color.White.copy(alpha = 0.5f),+ modifier = Modifier.size(17.dp),+ )+ }+ }+ }++ Row(+ Modifier+ .fillMaxWidth()+ .height(42.dp)+ .clip(RoundedCornerShape(11.dp))+ .background(Color.White.copy(alpha = 0.07f))+ .clickable { draft = SnippetDraft(Snippet(text = ""), isNew = true) },+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.Center,+ ) {+ Icon(+ Icons.Filled.Add,+ contentDescription = null,+ tint = Color.White.copy(alpha = 0.65f),+ modifier = Modifier.size(18.dp),+ )+ Text(+ tr("snip.new"),+ color = Color.White.copy(alpha = 0.65f),+ fontSize = 14.sp,+ modifier = Modifier.padding(start = 6.dp),+ )+ }+ }++ draft?.let { open ->+ SnippetEditor(open, store) { draft = null }+ }+}++/// The snippet being written, new or old, for the editor's dialog.+private data class SnippetDraft(val snippet: Snippet, val isNew: Boolean)++/// One snippet's text and whether it runs itself; Delete throws it away.+@Composable+private fun SnippetEditor(draft: SnippetDraft, store: SnippetStore, onClose: () -> Unit) {+ var text by remember(draft) { mutableStateOf(draft.snippet.text) }+ var runs by remember(draft) { mutableStateOf(draft.snippet.runs) }++ AlertDialog(+ onDismissRequest = onClose,+ title = { Text(if (draft.isNew) tr("snip.new") else tr("snip.title")) },+ text = {+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {+ OutlinedTextField(+ value = text,+ onValueChange = { text = it },+ label = { Text(tr("snip.command")) },+ textStyle = LocalTextStyle.current.copy(+ fontFamily = FontFamily.Monospace,+ fontSize = 14.sp,+ ),+ maxLines = 6,+ keyboardOptions = KeyboardOptions(+ capitalization = KeyboardCapitalization.None,+ autoCorrectEnabled = false,+ ),+ modifier = Modifier.fillMaxWidth(),+ )+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text(tr("snip.enter"), fontSize = 14.sp, modifier = Modifier.weight(1f))+ Switch(checked = runs, onCheckedChange = { runs = it })+ }+ }+ },+ confirmButton = {+ TextButton(+ enabled = text.isNotBlank(),+ onClick = {+ if (draft.isNew) store.add(text, runs)+ else store.replace(draft.snippet.copy(text = text, runs = runs))+ onClose()+ },+ ) { Text(tr("save")) }+ },+ dismissButton = {+ Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {+ if (!draft.isNew) {+ TextButton(onClick = {+ store.remove(draft.snippet)+ onClose()+ }) { Text(tr("delete"), color = MaterialTheme.colorScheme.error) }+ }+ TextButton(onClick = onClose) { Text(tr("cancel")) }+ }+ },+ )+}++// MARK: history++@Composable+private fun HistoryFace(model: TerminalModel, history: KeyHistory, tap: () -> Unit) {+ val lines = history.lines+ if (lines.isEmpty()) {+ Text(+ tr("hist.empty"),+ color = Color.White.copy(alpha = 0.45f),+ fontSize = 13.sp,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(top = 28.dp),+ )+ return+ }+ Column(+ Modifier+ .fillMaxSize()+ .verticalScroll(rememberScrollState())+ .padding(horizontal = 10.dp, vertical = 6.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ for (line in lines) {+ Box(+ Modifier+ .fillMaxWidth()+ .height(42.dp)+ .clip(RoundedCornerShape(11.dp))+ .background(Color.White.copy(alpha = 0.07f))+ .clickable {+ model.text(line)+ tap()+ }+ .padding(horizontal = 12.dp),+ contentAlignment = Alignment.CenterStart,+ ) {+ Text(+ line,+ color = Color.White,+ fontSize = 13.sp,+ fontFamily = FontFamily.Monospace,+ maxLines = 1,+ overflow = TextOverflow.MiddleEllipsis,+ )+ }+ }+ }+}++// MARK: colours++@Composable+private fun ColorsFace(model: TerminalModel, tap: () -> Unit) {+ val settings = model.settings+ val names = remember { listOf(Schemes.FOLLOW_DESKTOP) + Schemes.names }+ // A thousand schemes ship with the app: only a lazy grid may draw them.+ LazyHorizontalGrid(+ rows = GridCells.Fixed(2),+ modifier = Modifier.fillMaxWidth().height(146.dp),+ contentPadding = PaddingValues(horizontal = 10.dp, vertical = 6.dp),+ horizontalArrangement = Arrangement.spacedBy(10.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp),+ ) {+ items(names, key = { it }) { name ->+ Swatch(+ name = name,+ label = if (name == Schemes.FOLLOW_DESKTOP) tr("followhost") else name,+ picked = settings.schemeName == name,+ ) {+ settings.schemeName = name+ tap()+ }+ }+ }+}++@Composable+private fun Swatch(name: String, label: String, picked: Boolean, onClick: () -> Unit) {+ val accent = MaterialTheme.colorScheme.primary+ Column(+ Modifier.width(66.dp).clickable(onClick = onClick),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(5.dp),+ ) {+ Box(+ Modifier+ .width(64.dp)+ .height(40.dp)+ .clip(RoundedCornerShape(10.dp))+ .background(Schemes.background(name) ?: Color.White.copy(alpha = 0.12f))+ .border(+ width = if (picked) 2.dp else 1.dp,+ color = if (picked) accent else Color.White.copy(alpha = 0.18f),+ shape = RoundedCornerShape(10.dp),+ ),+ contentAlignment = Alignment.Center,+ ) {+ if (name == Schemes.FOLLOW_DESKTOP) {+ Icon(+ Icons.Filled.DesktopWindows,+ contentDescription = null,+ tint = Color.White.copy(alpha = 0.8f),+ modifier = Modifier.size(18.dp),+ )+ } else {+ Text(+ "Aa",+ color = Schemes.foreground(name) ?: Color.White,+ fontSize = 13.sp,+ fontFamily = FontFamily.Monospace,+ )+ }+ }+ Text(+ label,+ color = if (picked) accent else Color.White.copy(alpha = 0.6f),+ fontSize = 9.5.sp,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ textAlign = TextAlign.Center,+ )+ }+}++// MARK: chrome++@Composable+private fun Chip(+ icon: androidx.compose.ui.graphics.vector.ImageVector,+ title: String,+ modifier: Modifier,+ onClick: () -> Unit,+) {+ Row(+ modifier+ .height(36.dp)+ .clip(RoundedCornerShape(10.dp))+ .background(Color.White.copy(alpha = 0.07f))+ .clickable(onClick = onClick),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.Center,+ ) {+ Icon(+ icon,+ contentDescription = null,+ tint = Color.White.copy(alpha = 0.75f),+ modifier = Modifier.size(17.dp),+ )+ Text(+ title,+ color = Color.White.copy(alpha = 0.75f),+ fontSize = 14.sp,+ maxLines = 1,+ modifier = Modifier.padding(start = 7.dp),+ )+ }+}diff --git a/android/app/src/main/java/com/roversx/thinkterm/MainActivity.kt b/android/app/src/main/java/com/roversx/thinkterm/MainActivity.ktindex ddfb7a01..69dfe6ba 100644--- a/android/app/src/main/java/com/roversx/thinkterm/MainActivity.kt+++ b/android/app/src/main/java/com/roversx/thinkterm/MainActivity.kt@@ -4,29 +4,94 @@ import android.content.pm.ApplicationInfoimport android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContent+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.ExperimentalLayoutApi+import androidx.compose.foundation.layout.consumeWindowInsets+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.Dns+import androidx.compose.material.icons.filled.Settings+import androidx.compose.material3.Iconimport androidx.compose.material3.MaterialTheme+import androidx.compose.material3.NavigationBar+import androidx.compose.material3.NavigationBarItem+import androidx.compose.material3.Scaffold+import androidx.compose.material3.Textimport androidx.compose.material3.darkColorScheme+import androidx.compose.runtime.Composableimport androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.setValue+import androidx.compose.ui.Modifierclass 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)+ AppSettings.get(this)+ L10n.load(this)+ Schemes.load(this)+ AppLanguage.tag = AppSettings.get(this).languageval debuggable = (applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0val 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 }- }+ Root(store, debuggable)+ }+ }+ }+}++/// The two tabs. An open host takes the whole screen, the tab bar+/// included, the way the terminal does on iOS.+@OptIn(ExperimentalLayoutApi::class)+@Composable+private fun Root(store: HostStore, debuggable: Boolean) {+ // Reading the tag here relabels the tabs with the rest of the app.+ AppLanguage.tag+ var open by remember { mutableStateOf<Host?>(null) }+ var tab by remember { mutableIntStateOf(0) }++ val host = open+ if (host != null) {+ TerminalScreen(host, store) { open = null }+ return+ }++ Scaffold(+ modifier = Modifier.fillMaxSize(),+ bottomBar = {+ NavigationBar {+ NavigationBarItem(+ selected = tab == 0,+ onClick = { tab = 0 },+ icon = { Icon(Icons.Default.Dns, null) },+ label = { Text(tr("hosts")) },+ )+ NavigationBarItem(+ selected = tab == 1,+ onClick = { tab = 1 },+ icon = { Icon(Icons.Default.Settings, null) },+ label = { Text(tr("settings")) },+ )+ }+ },+ ) { padding ->+ // The bar over them spends the insets; the tabs must not again.+ Box(+ Modifier+ .fillMaxSize()+ .padding(padding)+ .consumeWindowInsets(padding)+ ) {+ if (tab == 0) {+ HostsScreen(store, showProbe = debuggable) { open = it }+ } else {+ SettingsScreen(model = null, showLog = null, onDone = null)}}}diff --git a/android/app/src/main/java/com/roversx/thinkterm/Menus.kt b/android/app/src/main/java/com/roversx/thinkterm/Menus.ktnew file mode 100644index 00000000..29e42441--- /dev/null+++ b/android/app/src/main/java/com/roversx/thinkterm/Menus.kt@@ -0,0 +1,97 @@+package com.roversx.thinkterm++import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width+import androidx.compose.material3.DropdownMenu+import androidx.compose.material3.DropdownMenuItem+import androidx.compose.material3.HorizontalDivider+import androidx.compose.material3.Icon+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.Check+import androidx.compose.material.icons.automirrored.filled.ArrowBack+import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight+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.Modifier+import androidx.compose.ui.unit.dp++/// The App's context menu for something (a thread, a tab, a pane, a+/// project, the space), as a dropdown a long press opens: its items,+/// checks, separators and submenus (a submenu takes over the dropdown,+/// with a row that goes back). Built when the menu shows.+@Composable+fun AppContextMenu(+ model: TerminalModel,+ kind: String,+ id: String,+ expanded: Boolean,+ onDismiss: () -> Unit,+ /// Rows the shell adds above the App's own (already dropdown items).+ extra: @Composable (() -> Unit)? = null,+) {+ var items by remember(kind, id) { mutableStateOf<List<MenuItem>>(emptyList()) }+ var stack by remember(kind, id) { mutableStateOf<List<MenuItem>>(emptyList()) }+ if (expanded && items.isEmpty()) {+ items = model.contextMenu(kind, id)+ }+ DropdownMenu(expanded = expanded, onDismissRequest = { stack = emptyList(); onDismiss() }) {+ val parent = stack.lastOrNull()+ if (parent == null && extra != null) {+ extra()+ HorizontalDivider()+ }+ if (parent != null) {+ DropdownMenuItem(+ text = { Text(parent.label) },+ leadingIcon = { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = null) },+ onClick = { stack = stack.dropLast(1) },+ )+ HorizontalDivider()+ }+ for (item in parent?.submenu ?: items) {+ MenuRow(item, onOpen = { stack = stack + it }) {+ model.menuAction(item.id)+ stack = emptyList()+ items = emptyList()+ onDismiss()+ }+ }+ }+}++@Composable+private fun MenuRow(item: MenuItem, onOpen: (MenuItem) -> Unit, onRun: () -> Unit) {+ when (item.kind) {+ "separator" -> HorizontalDivider()+ "header" -> Text(+ item.label,+ style = MaterialTheme.typography.labelSmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 6.dp),+ )+ else -> DropdownMenuItem(+ text = { Text(item.label) },+ enabled = item.enabled,+ leadingIcon = if (item.checked) ({ Icon(Icons.Default.Check, contentDescription = null) }) else null,+ trailingIcon = if (item.submenu.isNotEmpty()) ({+ Row { Spacer(Modifier.width(8.dp)); Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = null) }+ }) else null,+ onClick = { if (item.submenu.isNotEmpty()) onOpen(item) else onRun() },+ )+ }+}++/// The colour a thread's state dot takes, as on the desktop and iOS.+fun threadColor(status: String, live: Boolean): androidx.compose.ui.graphics.Color = when (status) {+ "Running" -> androidx.compose.ui.graphics.Color(0xFF34C759)+ "NeedsAttention" -> androidx.compose.ui.graphics.Color(0xFFFF9F0A)+ "Done" -> androidx.compose.ui.graphics.Color(0xFF0A84FF)+ else -> if (live) androidx.compose.ui.graphics.Color(0xFF8E8E93) else androidx.compose.ui.graphics.Color(0x668E8E93)+}diff --git a/android/app/src/main/java/com/roversx/thinkterm/Schemes.kt b/android/app/src/main/java/com/roversx/thinkterm/Schemes.ktnew file mode 100644index 00000000..2ef979cd--- /dev/null+++ b/android/app/src/main/java/com/roversx/thinkterm/Schemes.kt@@ -0,0 +1,70 @@+package com.roversx.thinkterm++import android.content.Context+import android.util.Log+import androidx.compose.ui.graphics.Color+import org.json.JSONArray++/// The colour schemes in assets/schemes.json (the web page's list,+/// straight from the desktop's), by name. Read once, on first use.+object Schemes {+ const val FOLLOW_DESKTOP = "desktop"++ /// Every scheme's name, in the file's order (alphabetical).+ var names: List<String> = emptyList()+ private set++ private var byName: Map<String, String> = emptyMap()+ private var backgrounds: Map<String, Color> = emptyMap()+ private var foregrounds: Map<String, Color> = emptyMap()++ fun load(context: Context) {+ if (names.isNotEmpty()) return+ try {+ val text = context.assets.open("schemes.json").bufferedReader().use { it.readText() }+ val list = JSONArray(text)+ val names = ArrayList<String>(list.length())+ val json = HashMap<String, String>()+ val bg = HashMap<String, Color>()+ val fg = HashMap<String, Color>()+ for (i in 0 until list.length()) {+ val entry = list.optJSONObject(i) ?: continue+ val name = entry.optString("name").ifEmpty { continue }+ names.add(name)+ json[name] = entry.toString()+ parseHex(entry.optString("background"))?.let { bg[name] = it }+ parseHex(entry.optString("foreground"))?.let { fg[name] = it }+ }+ this.names = names+ byName = json+ backgrounds = bg+ foregrounds = fg+ } catch (e: Throwable) {+ Log.w("thinkterm", "schemes.json unreadable: $e")+ }+ }++ /// One scheme as the core takes it: its JSON object, unchanged.+ fun json(name: String): String? = byName[name]++ /// The background of a scheme, for the picker's swatches.+ fun background(name: String): Color? = backgrounds[name]++ /// A scheme's own foreground, so "Aa" shows on a light swatch too.+ fun foreground(name: String): Color? = foregrounds[name]+}++/// "#rrggbb", "#rgb" or "#rrggbbaa"; null for anything else.+fun parseHex(value: String): Color? {+ var s = value.trim().removePrefix("#")+ if (s.length == 3) s = s.map { "$it$it" }.joinToString("")+ return try {+ when (s.length) {+ 6 -> Color(0xFF000000L or s.toLong(16))+ 8 -> Color(s.toLong(16))+ else -> null+ }+ } catch (e: Throwable) {+ null+ }+}diff --git a/android/app/src/main/java/com/roversx/thinkterm/SettingsScreen.kt b/android/app/src/main/java/com/roversx/thinkterm/SettingsScreen.ktnew file mode 100644index 00000000..273eaed5--- /dev/null+++ b/android/app/src/main/java/com/roversx/thinkterm/SettingsScreen.kt@@ -0,0 +1,532 @@+package com.roversx.thinkterm++import android.content.pm.PackageManager+import androidx.activity.compose.BackHandler+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.widthIn+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScroll+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.automirrored.filled.ArrowBack+import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight+import androidx.compose.material.icons.filled.Add+import androidx.compose.material.icons.filled.Check+import androidx.compose.material.icons.filled.DesktopWindows+import androidx.compose.material.icons.filled.Remove+import androidx.compose.material.icons.filled.Search+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButton+import androidx.compose.material3.ListItem+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.OutlinedTextField+import androidx.compose.material3.Scaffold+import androidx.compose.material3.SegmentedButton+import androidx.compose.material3.SegmentedButtonDefaults+import androidx.compose.material3.SingleChoiceSegmentedButtonRow+import androidx.compose.material3.Switch+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.material3.TopAppBar+import androidx.compose.runtime.Composable+import androidx.compose.runtime.MutableState+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.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Shape+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import java.util.Locale+import kotlin.math.round++/// The app's preferences, in the prototype's eight sections (the iOS+/// SettingsSheet one to one). The Settings tab shows it with no terminal;+/// a terminal's menu shows it with one, and then the text size is the+/// live pane's and the log is offered.+@Composable+fun SettingsScreen(model: TerminalModel?, showLog: MutableState<Boolean>?, onDone: (() -> Unit)?) {+ val settings = AppSettings.get(LocalContext.current)+ // Reading the tag subscribes the screen: a language change relabels it.+ AppLanguage.tag+ var pushed by remember { mutableStateOf<String?>(null) }+ val back: () -> Unit = { pushed = null }+ BackHandler(enabled = pushed != null, onBack = back)++ when (pushed) {+ "language" -> OptionScreen(tr("language"), languages(), settings.language, back) { settings.language = it }+ "theme" -> ThemeScreen(settings, back)+ "font.family" -> OptionScreen(tr("font.family"), fonts(), settings.fontFamily, back) { settings.fontFamily = it }+ "contrast" -> OptionScreen(tr("contrast"), contrasts(), settings.contrast, back) { settings.contrast = it }+ "cursor" -> OptionScreen(tr("cursor"), cursors(), settings.cursorStyle, back) { settings.cursorStyle = it }+ "resize.mode" -> OptionScreen(tr("resize.mode"), resizes(), settings.resizeMode, back) { settings.resizeMode = it }+ "k.keybar" -> KeyCapsScreen(back)+ else -> SettingsList(settings, model, showLog, onDone) { pushed = it }+ }+}++@Composable+private fun SettingsList(+ settings: AppSettings,+ model: TerminalModel?,+ showLog: MutableState<Boolean>?,+ onDone: (() -> Unit)?,+ onPush: (String) -> Unit,+) {+ Screen(tr("settings"), onBack = null, onDone = onDone) { padding ->+ Column(+ Modifier+ .padding(padding)+ .verticalScroll(rememberScrollState())+ ) {+ Section(tr("sec.general"))+ PushRow(tr("language"), label(languages(), settings.language)) { onPush("language") }++ Section(tr("sec.appearance"))+ val scheme = settings.schemeName+ PushRow(+ tr("theme"),+ if (scheme == Schemes.FOLLOW_DESKTOP) tr("followhost") else scheme,+ swatch = Schemes.background(scheme),+ ) { onPush("theme") }+ if (model != null) LiveTextSize(model, settings) else TextSizeStepper(settings)+ PushRow(tr("font.family"), label(fonts(), settings.fontFamily)) { onPush("font.family") }+ PushRow(tr("contrast"), label(contrasts(), settings.contrast)) { onPush("contrast") }++ Section(tr("sec.terminal"))+ SegmentRow(+ tr("scroll.mode"),+ listOf(tr("scroll.stepped"), tr("scroll.smooth")),+ if (settings.smoothScroll) 1 else 0,+ ) { settings.smoothScroll = it == 1 }+ SwitchRow(tr("scrollbar"), settings.scrollbar) { settings.scrollbar = it }+ PushRow(tr("cursor"), label(cursors(), settings.cursorStyle)) { onPush("cursor") }+ SwitchRow(tr("cursor.blink"), settings.cursorBlink) { settings.cursorBlink = it }+ SwitchRow(tr("bell"), settings.bell) { settings.bell = it }+ PushRow(tr("resize.mode"), label(resizes(), settings.resizeMode)) { onPush("resize.mode") }++ Section(tr("sec.interface"))+ SegmentRow(+ tr("i.tabbar"),+ listOf(tr("i.onelevel"), tr("i.twolevel")),+ if (settings.tabBarLevels == "two") 1 else 0,+ ) { settings.tabBarLevels = if (it == 1) "two" else "one" }+ SwitchRow(tr("i.panebars"), settings.paneBars) { settings.paneBars = it }++ Section(tr("sec.keyboard"))+ PushRow(tr("k.keybar"), keyCaps.size.toString()) { onPush("k.keybar") }+ SwitchRow(tr("k.haptics"), settings.hapticKeys) { settings.hapticKeys = it }+ SwitchRow(tr("k.autopanel"), settings.autoKeyPanel) { settings.autoKeyPanel = it }++ Section(tr("sec.gestures"))+ SwitchRow(tr("g.pinch"), settings.pinchZoom) { settings.pinchZoom = it }+ SwitchRow(tr("g.twofinger"), settings.twoFingerHidesKeyboard) { settings.twoFingerHidesKeyboard = it }+ SwitchRow(tr("g.longpress"), settings.longPressSelects) { settings.longPressSelects = it }++ Section(tr("sec.connection"))+ SwitchRow(tr("c.autoreconnect"), settings.autoReconnect) { settings.autoReconnect = it }+ val keepAlive = settings.keepAliveSeconds+ StepperRow(+ tr("c.keepalive"),+ if (keepAlive == 0) tr("off") else "$keepAlive s",+ onMinus = { settings.keepAliveSeconds = (settings.keepAliveSeconds - 15).coerceIn(0, 300) },+ onPlus = { settings.keepAliveSeconds = (settings.keepAliveSeconds + 15).coerceIn(0, 300) },+ )+ SwitchRow(tr("c.background"), settings.keepSessionInBackground) { settings.keepSessionInBackground = it }++ if (showLog != null) {+ Section(tr("diagnostics"))+ SwitchRow(tr("showlog"), showLog.value) {+ showLog.value = it+ model?.wantsStats = it || settings.devMode+ }+ SwitchRow(tr("devmode"), settings.devMode) {+ settings.devMode = it+ model?.wantsStats = showLog.value || it+ }+ Footer(tr("showlog.foot"))+ }++ Section(tr("sec.about"))+ ValueRow(tr("version"), appVersion())+ Spacer(Modifier.height(24.dp))+ }+ }+}++// MARK: the pushed screens++/// The screen a push row opens: the choices, the current one ticked.+@Composable+private fun OptionScreen(+ title: String,+ options: List<Choice>,+ selected: String,+ onBack: () -> Unit,+ onPick: (String) -> Unit,+) {+ Screen(title, onBack = onBack, onDone = null) { padding ->+ Column(+ Modifier+ .padding(padding)+ .verticalScroll(rememberScrollState())+ ) {+ for (option in options) {+ ListItem(+ headlineContent = { Text(option.label) },+ trailingContent = {+ if (option.value == selected) {+ Icon(Icons.Default.Check, null, tint = MaterialTheme.colorScheme.primary)+ }+ },+ modifier = Modifier.clickable { onPick(option.value) },+ )+ }+ }+ }+}++/// The colour schemes by name, searchable, each with its background as a+/// swatch; the host's own scheme first.+@Composable+private fun ThemeScreen(settings: AppSettings, onBack: () -> Unit) {+ var query by remember { mutableStateOf("") }+ val names = remember(query) {+ if (query.isBlank()) Schemes.names else Schemes.names.filter { it.contains(query.trim(), ignoreCase = true) }+ }+ Screen(tr("theme"), onBack = onBack, onDone = null) { padding ->+ Column(Modifier.padding(padding)) {+ OutlinedTextField(+ value = query,+ onValueChange = { query = it },+ placeholder = { Text(tr("theme.search")) },+ leadingIcon = { Icon(Icons.Default.Search, null) },+ singleLine = true,+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 16.dp, vertical = 8.dp),+ )+ LazyColumn {+ if (query.isBlank()) {+ item {+ ThemeRow(+ tr("followhost"),+ null,+ settings.schemeName == Schemes.FOLLOW_DESKTOP,+ ) { settings.schemeName = Schemes.FOLLOW_DESKTOP }+ }+ }+ items(names, key = { it }) { name ->+ ThemeRow(name, Schemes.background(name), settings.schemeName == name) {+ settings.schemeName = name+ }+ }+ }+ }+ }+}++@Composable+private fun ThemeRow(label: String, color: Color?, chosen: Boolean, onPick: () -> Unit) {+ ListItem(+ leadingContent = {+ if (color != null) {+ Swatch(color, RoundedCornerShape(4.dp), 22.dp)+ } else {+ Icon(Icons.Default.DesktopWindows, null, modifier = Modifier.size(22.dp))+ }+ },+ headlineContent = { Text(label, maxLines = 1, overflow = TextOverflow.Ellipsis) },+ trailingContent = {+ if (chosen) Icon(Icons.Default.Check, null, tint = MaterialTheme.colorScheme.primary)+ },+ modifier = Modifier.clickable(onClick = onPick),+ )+}++/// What the key bar carries, in its order. Read-only for now: the bar is+/// not editable yet.+@Composable+private fun KeyCapsScreen(onBack: () -> Unit) {+ Screen(tr("k.keybar"), onBack = onBack, onDone = null) { padding ->+ Column(+ Modifier+ .padding(padding)+ .verticalScroll(rememberScrollState())+ ) {+ for (cap in keyCaps) {+ ListItem(headlineContent = { Text(cap, fontFamily = FontFamily.Monospace) })+ }+ Footer(tr("k.keybar.foot"))+ }+ }+}++// MARK: rows++@OptIn(ExperimentalMaterial3Api::class)+@Composable+private fun Screen(+ title: String,+ onBack: (() -> Unit)?,+ onDone: (() -> Unit)?,+ content: @Composable (PaddingValues) -> Unit,+) {+ Scaffold(+ modifier = Modifier.fillMaxSize(),+ topBar = {+ TopAppBar(+ title = { Text(title, maxLines = 1, overflow = TextOverflow.Ellipsis) },+ navigationIcon = {+ if (onBack != null) {+ IconButton(onClick = onBack) {+ Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = tr("back"))+ }+ }+ },+ actions = {+ if (onDone != null) TextButton(onClick = onDone) { Text(tr("done")) }+ },+ )+ },+ content = content,+ )+}++@Composable+private fun Section(title: String) {+ Text(+ title,+ style = MaterialTheme.typography.labelLarge,+ color = MaterialTheme.colorScheme.primary,+ modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 20.dp, bottom = 4.dp),+ )+}++@Composable+private fun Footer(text: String) {+ Text(+ text,+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),+ )+}++/// A row that pushes a one-of-these screen and shows the choice.+@Composable+private fun PushRow(title: String, value: String, swatch: Color? = null, onClick: () -> Unit) {+ ListItem(+ headlineContent = { Text(title) },+ trailingContent = {+ Row(+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ if (swatch != null) Swatch(swatch, CircleShape, 16.dp)+ Secondary(value, Modifier.widthIn(max = 180.dp))+ Icon(+ Icons.AutoMirrored.Filled.KeyboardArrowRight,+ null,+ tint = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ },+ modifier = Modifier.clickable(onClick = onClick),+ )+}++@Composable+private fun ValueRow(title: String, value: String) {+ ListItem(headlineContent = { Text(title) }, trailingContent = { Secondary(value) })+}++@Composable+private fun SwitchRow(title: String, checked: Boolean, onChange: (Boolean) -> Unit) {+ ListItem(+ headlineContent = { Text(title) },+ trailingContent = { Switch(checked = checked, onCheckedChange = onChange) },+ modifier = Modifier.clickable { onChange(!checked) },+ )+}++@Composable+private fun StepperRow(title: String, value: String, onMinus: () -> Unit, onPlus: () -> Unit) {+ ListItem(+ headlineContent = { Text(title) },+ trailingContent = {+ Row(verticalAlignment = Alignment.CenterVertically) {+ IconButton(onClick = onMinus) { Icon(Icons.Default.Remove, contentDescription = "-") }+ Secondary(value, Modifier.widthIn(min = 60.dp), TextAlign.Center)+ IconButton(onClick = onPlus) { Icon(Icons.Default.Add, contentDescription = "+") }+ }+ },+ )+}++/// The prototype's segmented row: a quiet label with the control under it.+@OptIn(ExperimentalMaterial3Api::class)+@Composable+private fun SegmentRow(title: String, options: List<String>, selected: Int, onSelect: (Int) -> Unit) {+ Column(+ Modifier+ .fillMaxWidth()+ .padding(horizontal = 16.dp, vertical = 10.dp)+ ) {+ Text(+ title,+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ Spacer(Modifier.height(7.dp))+ SingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth()) {+ options.forEachIndexed { index, label ->+ SegmentedButton(+ selected = index == selected,+ onClick = { onSelect(index) },+ shape = SegmentedButtonDefaults.itemShape(index, options.size),+ ) { Text(label, maxLines = 1, overflow = TextOverflow.Ellipsis) }+ }+ }+ }+}++@Composable+private fun Secondary(text: String, modifier: Modifier = Modifier, align: TextAlign? = null) {+ Text(+ text,+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ textAlign = align,+ modifier = modifier,+ )+}++@Composable+private fun Swatch(color: Color, shape: Shape, size: Dp) {+ Box(+ Modifier+ .size(size)+ .clip(shape)+ .background(color)+ .border(1.dp, Color.White.copy(alpha = 0.25f), shape)+ )+}++// MARK: the text size++/// The open terminal's text size, stepped live; the size a new+/// connection starts at follows it.+@Composable+private fun LiveTextSize(model: TerminalModel, settings: AppSettings) {+ StepperRow(+ tr("textsize"),+ String.format(Locale.US, "%.1f pt", model.fontPt),+ onMinus = { stepText(model, settings, -1.0) },+ onPlus = { stepText(model, settings, 1.0) },+ )+}++private fun stepText(model: TerminalModel, settings: AppSettings, by: Double) {+ model.stepFont(by)+ settings.fontSize = round(model.fontPt * (1 + 0.1 * by)).coerceIn(6.0, 40.0)+}++@Composable+private fun TextSizeStepper(settings: AppSettings) {+ StepperRow(+ tr("textsize"),+ String.format(Locale.US, "%.0f pt", settings.fontSize),+ onMinus = { settings.fontSize = (settings.fontSize - 1).coerceIn(6.0, 40.0) },+ onPlus = { settings.fontSize = (settings.fontSize + 1).coerceIn(6.0, 40.0) },+ )+}++// MARK: the choices behind the push rows++/// One choice on a pushed picker screen.+private class Choice(val value: String, val label: String)++private fun label(options: List<Choice>, value: String) =+ options.firstOrNull { it.value == value }?.label ?: value++private fun languages(): List<Choice> {+ val names = mapOf(+ "en-US" to "English",+ "zh-CN" to "简体中文",+ "ja-JP" to "日本語",+ "fr-FR" to "Français",+ "de-DE" to "Deutsch",+ )+ val tags = L10n.tags.ifEmpty { names.keys.toList() }+ return listOf(Choice("system", tr("system"))) + tags.map { Choice(it, names[it] ?: it) }+}++// The faces in the assets; the core shapes from font files, not the+// system's fonts. Changing one reconnects, since the glyph atlas is+// built for a face at connect time.+private fun fonts(): List<Choice> = listOf("JetBrains Mono", "Fira Code").map { Choice(it, it) }++private fun contrasts(): List<Choice> = listOf(+ Choice("off", tr("contrast.off")),+ Choice("3", tr("contrast.3")),+ Choice("45", tr("contrast.45")),+ Choice("7", tr("contrast.7")),+)++private fun cursors(): List<Choice> = listOf(+ Choice("auto", tr("cursor.auto")),+ Choice("block", tr("cursor.block")),+ Choice("bar", tr("cursor.bar")),+ Choice("underline", tr("cursor.underline")),+)++private fun resizes(): List<Choice> = listOf(+ Choice("auto", tr("resize.auto")),+ Choice("live", tr("resize.live")),+ Choice("release", tr("resize.release")),+)++/// The key bar's caps, in its order; KeyBar.kt sends them.+private val keyCaps: List<String> get() = KeyCaps.bar.map { it.label }++@Composable+private fun appVersion(): String {+ val context = LocalContext.current+ return remember(context) {+ runCatching {+ val info = context.packageManager.getPackageInfo(+ context.packageName,+ PackageManager.PackageInfoFlags.of(0),+ )+ "${info.versionName} (${info.longVersionCode})"+ }.getOrDefault("0 (0)")+ }+}diff --git a/android/app/src/main/java/com/roversx/thinkterm/Snippets.kt b/android/app/src/main/java/com/roversx/thinkterm/Snippets.ktnew file mode 100644index 00000000..b761a73f--- /dev/null+++ b/android/app/src/main/java/com/roversx/thinkterm/Snippets.kt@@ -0,0 +1,128 @@+package com.roversx.thinkterm++import android.content.Context+import android.content.SharedPreferences+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import org.json.JSONArray+import org.json.JSONObject+import java.util.UUID++/// A command the user saved. Tapped in the key panel it goes to the pane+/// as typed text; `runs` adds the Enter that runs it.+data class Snippet(val id: String = UUID.randomUUID().toString(), val text: String, val runs: Boolean = true)++/// The saved snippets, as JSON in the preferences under "keypanel.snippets".+/// A handful of short strings: kept whole in memory, rewritten on change.+class SnippetStore private constructor(private val prefs: SharedPreferences) {+ companion object {+ private const val KEY = "keypanel.snippets"+ @Volatile private var instance: SnippetStore? = null++ fun get(context: Context): SnippetStore = instance ?: synchronized(this) {+ instance ?: SnippetStore(+ context.applicationContext.getSharedPreferences("thinkterm-settings", Context.MODE_PRIVATE)+ ).also { instance = it }+ }++ /// What a fresh install starts with, from the prototype's list.+ private val starter = listOf(+ Snippet(text = "git status -sb"),+ Snippet(text = "thinkterm cli --prefer-mux list"),+ Snippet(text = "journalctl -u thinkterm-mux -f"),+ Snippet(text = "btop"),+ )+ }++ var items: List<Snippet> by mutableStateOf(load())+ private set++ fun add(text: String, runs: Boolean) {+ val clean = text.trim()+ if (clean.isEmpty()) return+ items = items + Snippet(text = clean, runs = runs)+ save()+ }++ fun replace(snippet: Snippet) {+ val at = items.indexOfFirst { it.id == snippet.id }+ if (at < 0) return+ val clean = snippet.text.trim()+ items = if (clean.isEmpty()) items.filterIndexed { i, _ -> i != at }+ else items.toMutableList().also { it[at] = snippet.copy(text = clean) }+ save()+ }++ fun remove(snippet: Snippet) {+ items = items.filter { it.id != snippet.id }+ save()+ }++ private fun load(): List<Snippet> {+ val json = prefs.getString(KEY, null) ?: return starter+ return try {+ val arr = JSONArray(json)+ (0 until arr.length()).mapNotNull { i ->+ val o = arr.optJSONObject(i) ?: return@mapNotNull null+ Snippet(o.optString("id", UUID.randomUUID().toString()), o.optString("text"), o.optBoolean("runs", true))+ }+ } catch (e: Throwable) {+ starter+ }+ }++ private fun save() {+ val arr = JSONArray()+ for (s in items) arr.put(JSONObject().put("id", s.id).put("text", s.text).put("runs", s.runs))+ prefs.edit().putString(KEY, arr.toString()).apply()+ }+}++/// The last commands the key panel sent, newest first. Only what went+/// through the key bar and the panel; it outlives the app in the+/// preferences.+class KeyHistory private constructor(private val prefs: SharedPreferences) {+ companion object {+ private const val KEY = "keypanel.history"+ private const val LIMIT = 50+ @Volatile private var instance: KeyHistory? = null++ fun get(context: Context): KeyHistory = instance ?: synchronized(this) {+ instance ?: KeyHistory(+ context.applicationContext.getSharedPreferences("thinkterm-settings", Context.MODE_PRIVATE)+ ).also { instance = it }+ }+ }++ var lines: List<String> by mutableStateOf(load())+ private set++ fun record(text: String) {+ val line = text.trim()+ // A lone bracket or pipe from the key grid is not worth keeping;+ // a snippet or a pasted command is.+ if (line.length <= 1) return+ lines = (listOf(line) + lines.filter { it != line }).take(LIMIT)+ save()+ }++ fun clear() {+ lines = emptyList()+ prefs.edit().remove(KEY).apply()+ }++ private fun load(): List<String> {+ val json = prefs.getString(KEY, null) ?: return emptyList()+ return try {+ val arr = JSONArray(json)+ (0 until arr.length()).map { arr.optString(it) }.filter { it.isNotEmpty() }+ } catch (e: Throwable) {+ emptyList()+ }+ }++ private fun save() {+ prefs.edit().putString(KEY, JSONArray(lines).toString()).apply()+ }+}diff --git a/android/app/src/main/java/com/roversx/thinkterm/Strings.kt b/android/app/src/main/java/com/roversx/thinkterm/Strings.ktnew file mode 100644index 00000000..c4007b9c--- /dev/null+++ b/android/app/src/main/java/com/roversx/thinkterm/Strings.kt@@ -0,0 +1,79 @@+package com.roversx.thinkterm++import android.content.Context+import android.util.Log+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import org.json.JSONObject+import java.util.Locale++/// The app's text in five languages, from assets/strings.json (the same+/// tables the iOS app ships; ios/tools/gen-strings.py builds them).+/// English stands in for a key a table has not got.+object L10n {+ private const val FALLBACK = "en-US"++ /// language tag -> key -> text.+ private var tables: Map<String, Map<String, String>> = emptyMap()++ fun load(context: Context) {+ if (tables.isNotEmpty()) return+ tables = try {+ val text = context.assets.open("strings.json").bufferedReader().use { it.readText() }+ val root = JSONObject(text)+ root.keys().asSequence().associateWith { tag ->+ val table = root.getJSONObject(tag)+ table.keys().asSequence().associateWith { table.getString(it) }+ }+ } catch (e: Throwable) {+ Log.w("thinkterm", "strings.json is missing: the app shows its keys ($e)")+ emptyMap()+ }+ }++ /// The tags with a table, in the order of the settings' picker.+ val tags: List<String> get() = listOf("en-US", "zh-CN", "ja-JP", "fr-FR", "de-DE").filter { tables.containsKey(it) }++ /// The phone's own language, matched against the tables.+ val systemTag: String+ get() {+ val locale = Locale.getDefault()+ return match(locale.toLanguageTag()) ?: match(locale.language) ?: FALLBACK+ }++ /// "zh-Hans-CN" and "zh" both find the "zh-CN" table.+ private fun match(language: String): String? {+ if (tables.containsKey(language)) return language+ val code = language.substringBefore('-')+ return tables.keys.sorted().firstOrNull { it.substringBefore('-') == code }+ }++ /// The tag in force: the phone's own when the setting is "system".+ fun currentTag(setting: String): String = if (setting == "system") systemTag else (match(setting) ?: FALLBACK)++ fun text(key: String, setting: String): String {+ val tag = currentTag(setting)+ return tables[tag]?.get(key) ?: tables[FALLBACK]?.get(key) ?: key+ }+}++/// What the views follow to relabel themselves: reading `tag` in a+/// composable subscribes it, so a change in the settings relabels the+/// screen without a relaunch. Main thread only.+object AppLanguage {+ var tag: String by mutableStateOf("system")+}++/// One string by key; extra arguments fill its %@ and %d, the iOS way.+fun tr(key: String, vararg args: Any): String {+ val format = L10n.text(key, AppLanguage.tag)+ if (args.isEmpty()) return format+ var out = format+ for (arg in args) {+ val at = out.indexOfAny(listOf("%@", "%d", "%s"))+ if (at < 0) break+ out = out.substring(0, at) + arg.toString() + out.substring(at + 2)+ }+ return out+}diff --git a/android/app/src/main/java/com/roversx/thinkterm/TerminalModel.kt b/android/app/src/main/java/com/roversx/thinkterm/TerminalModel.ktindex c9410308..9e546b57 100644--- a/android/app/src/main/java/com/roversx/thinkterm/TerminalModel.kt+++ b/android/app/src/main/java/com/roversx/thinkterm/TerminalModel.kt@@ -12,6 +12,7 @@ import android.os.VibratorManagerimport android.util.Logimport android.view.Choreographerimport androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateMapOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.setValueimport androidx.compose.ui.graphics.Color@@ -23,26 +24,100 @@ import java.util.concurrent.atomic.AtomicBoolean/// 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.+///+/// One model per connection: the screen that shows a host makes one and+/// shuts it down when it goes. The shape follows ios/Sources/TerminalModel.swift.class TerminalModel(private val context: Context,- private val store: HostStore,- val host: Host,+ val store: HostStore,+ host: Host,) {val core: Core+ val settings = AppSettings.get(context)- // What the screen shows, as Compose state (written on the main thread).+ /// The host this screen shows; edited in place from the failure card.+ var host by mutableStateOf(host)++ // The App's views, refreshed when the core says something changed.var tabs by mutableStateOf<TabsView?>(null)private set+ var threads by mutableStateOf<ThreadsView?>(null)+ private set+ var sidebar by mutableStateOf<SidebarView?>(null)+ private set+ var navs by mutableStateOf<List<NavView>>(emptyList())+ private setvar status by mutableStateOf<StatusView?>(null)private set+ /// The last rows of panes the overview asked about, by pane.+ val previews = mutableStateMapOf<Int, List<PreviewRow>>()var title by mutableStateOf("")private setvar connection by mutableStateOf("")private set- var background by mutableStateOf(Color(0xFF1C1C1C))+ var attached by mutableStateOf(false)private set+ var composing by mutableStateOf<String?>(null)var ctrlSticky by mutableStateOf(false)var altSticky by mutableStateOf(false)+ var logText by mutableStateOf("")+ private set+ var stats by mutableStateOf("")+ private set+ /// A selection was just copied; the status line says so for a moment.+ var copied by mutableStateOf(false)+ private set+ /// The App's remark for the status line: a passing one goes after a+ /// few seconds, a sticky one (the connection is down) stays until the+ /// App takes it back.+ var toastText by mutableStateOf<String?>(null)+ private set+ /// The App says its connection is down and it is redialing.+ var reconnecting by mutableStateOf(false)+ private set+ /// The terminal's background, as the App paints it: the chrome around+ /// the terminal takes the same colour.+ var background by mutableStateOf(Color(0xFF1C1C1C))+ private set+ /// The App's font size in points, from its layout view.+ var fontPt by mutableStateOf(11.0)+ private set+ /// The focused pane's place in its scrollback: rows above the bottom,+ /// and rows there are; changes for a moment show the scrollbar.+ var scrollAbove by mutableStateOf(0)+ private set+ var scrollMax by mutableStateOf(0)+ private set+ var scrollShown by mutableStateOf(false)+ private set+ /// The App's cell size in dp, from its layout view.+ var cellWidth = 8.0+ private set+ var cellHeight = 20.0+ private set+ /// The log view is open: the stats are worth refreshing.+ var wantsStats = false+ /// Where the caret is, in dp from the terminal's origin (the App's+ /// IME anchor), for the selection handles and the composition popup.+ var cursorLeft = 8.0+ var cursorTop = 8.0+ var cursorWidth = 2.0+ var cursorHeight = 20.0++ /// 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++ /// The view sets these so the core can ask for the keyboard and the+ /// selection can be redrawn when the screen changes.+ var onFocusRequested: (() -> Unit)? = null+ var onScreenChanged: (() -> Unit)? = null+ var onHideKeyboard: (() -> Unit)? = null+ /// A selection stands: where its copy chip goes, in dp from the+ /// terminal's origin (the head cell's top-left), or null for none.+ var selectionMenuAt by mutableStateOf<Pair<Double, Double>?>(null)++ val smoothScroll: Boolean get() = settings.smoothScrollprivate val frameNeeded = AtomicBoolean(false)private val changePending = AtomicBoolean(false)@@ -50,10 +125,9 @@ class TerminalModel(private val choreographer = Choreographer.getInstance()private var running = trueprivate 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 logLines = ArrayDeque<String>()+ private var toastShown: String? = null+ private var appliedFamily = ""private val tick = object : Choreographer.FrameCallback {override fun doFrame(frameTimeNanos: Long) {@@ -64,34 +138,71 @@ class TerminalModel(}}+ private val statsTick = object : Runnable {+ override fun run() {+ if (!running) return+ if (wantsStats || settings.devMode) {+ val s = core.stats()+ if (s != stats) stats = s+ }+ main.postDelayed(this, 500)+ }+ }+init {core = Core(Sink())choreographer.postFrameCallback(tick)+ main.postDelayed(statsTick, 500)+ applyScheme()+ applyScrollMode()+ applyTerminalPrefs()+ appliedFamily = settings.fontFamily+ }++ /// The preferences the open terminal follows: the screen calls this+ /// when any of them changes (a snapshot read in a composable).+ fun settingsChanged() {+ applyScheme()+ applyScrollMode()+ applyTerminalPrefs()+ // A face is shaped at connect time: the connection is made again.+ if (settings.fontFamily != appliedFamily) {+ appliedFamily = settings.fontFamily+ if (connection.startsWith("pane ")) {+ disconnect()+ connect()+ }+ }}// MARK: connection- /// Connect once; the surface must be attached first so the core has a- /// size to lay the panes out in.+ /// The chosen face first, the symbols fallback after it.+ private fun fontPaths(): List<String> {+ val face = if (settings.fontFamily == "Fira Code") "FiraCode-Regular.ttf" else "JetBrainsMono-Regular.ttf"+ return Assets.fontPaths(context, face)+ }++ /// Connect to the model's host with the secret from the store.fun connect() {- if (connected) returnconnected = 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")+ val h = host+ val secret = if (h.id == Host.PROBE_ID) probeKey() else store.secret(h.id)+ val passphrase = if (h.id == Host.PROBE_ID) null else store.passphrase(h.id)+ log("shell: connecting ${h.address}, ${secret.length} chars of secret")core.connect(- host = host.hostname,- port = host.port.toUShort(),- user = host.user,- authKind = host.auth,+ host = h.hostname,+ port = h.port.toUShort(),+ user = h.user,+ authKind = h.auth,secret = secret,passphrase = passphrase,- knownHost = host.knownHost,- remoteCommand = host.remoteCommand,+ knownHost = h.knownHost,+ remoteCommand = h.remoteCommand,deviceId = store.deviceId,- keepaliveSecs = 15u,- fontPaths = Assets.fontPaths(context),- sizePt = 11.0,+ keepaliveSecs = settings.keepAliveSeconds.coerceAtLeast(0).toUInt(),+ fontPaths = fontPaths(),+ sizePt = settings.fontSize,painter = AndroidGlyphPainter(),)}@@ -109,14 +220,32 @@ class TerminalModel(core.disconnect()}+ val isConnected: Boolean+ get() = connection.isNotEmpty() && !connection.startsWith("disconnected") && !connection.startsWith("failed")+/// Leaving the screen for good: the frame loop stops, then the core.fun shutdown() {running = falsechoreographer.removeFrameCallback(tick)+ main.removeCallbacks(statsTick)core.disconnect()core.shutdown()}+ /// The app left the screen. The socket lives as long as the process+ /// does; with the setting off, it is dropped now and redialed on return.+ fun enteredBackground() {+ if (!settings.keepSessionInBackground && connection.startsWith("pane ")) {+ disconnect()+ }+ }++ fun enteredForeground() {+ if (!settings.keepSessionInBackground && connection.startsWith("disconnected")) {+ connect()+ }+ }+// MARK: inputfun key(name: String, ctrl: Boolean = false, alt: Boolean = false, shift: Boolean = false) {@@ -133,25 +262,170 @@ class TerminalModel(core.text(text)}+ fun pasteFromClipboard() {+ val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager ?: return+ val text = cm.primaryClip?.getItemAt(0)?.coerceToText(context)?.toString() ?: return+ if (text.isNotEmpty()) core.paste(text)+ }++ fun copyToClipboard(text: String) {+ val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager ?: return+ cm.setPrimaryClip(ClipData.newPlainText("thinkterm", text))+ showCopied()+ }+private fun takeCtrl(): Boolean = ctrlSticky.also { if (it) ctrlSticky = false }private fun takeAlt(): Boolean = altSticky.also { if (it) altSticky = false }+ fun pointer(kind: String, x: Double, y: Double) = core.pointer(kind, x, y)++ fun wheel(x: Double, y: Double, lines: Double) = core.wheel(x, y, lines)++ fun wheelPx(x: Double, y: Double, px: Double) = core.wheelPx(x, y, px)++ fun stepFont(by: Double) = core.stepFont(by)++ /// The tab `by` places along the strip from the current one, shown.+ fun switchTab(by: Int) {+ val list = tabs?.tabs ?: return+ val at = list.indexOfFirst { it.current }+ if (at < 0) return+ val next = at + by+ if (next !in list.indices) return+ chromeClick("pane", pane = list[next].target)+ }++ /// The last rows of a pane, for a thumbnail; `previews` fills in.+ fun requestPreview(pane: Int, rows: Int = 8) = core.requestPreview(pane.toUInt(), rows.toUInt())++ // MARK: the App's chrome+fun chromeClick(action: String, pane: Int? = null, tab: Int? = null) {core.chromeClick(action, pane?.toUInt(), tab?.toUInt())}+ fun sideClick(kind: String, id: String? = null, flag: Boolean? = null) = core.sideClick(kind, id, flag)++ fun sideKey(key: String, value: String) = core.sideKey(key, value)++ fun contextMenu(kind: String, id: String): List<MenuItem> = Views.menu(core.contextMenu(kind, id))++ /// Run a menu row. Copy and paste are the shell's to do.+ fun menuAction(id: String) {+ val outcome = Views.menuOutcome(core.menuAction(id)) ?: return+ outcome.copy?.let { copyToClipboard(it) }+ if (outcome.paste) pasteFromClipboard()+ }++ fun takeOver() = core.takeOver()++ /// The selected text to the clipboard, and the selection put away.+ fun copySelection() {+ core.selectedText()?.takeIf { it.isNotEmpty() }?.let { copyToClipboard(it) }+ clearSelection()+ }++ fun clearSelection() {+ core.clearSelection()+ selectionMenuAt = null+ }++ fun showCopied() {+ copied = true+ main.postDelayed({ copied = false }, 1200)+ }+// 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() {+ /// Assigned only on a change: a state write redraws the screen, and+ /// the core reports changes as often as output comes.+ fun refreshViews() {+ onScreenChanged?.invoke()val tabs = Views.tabs(core.view("tabs"))if (tabs != this.tabs) this.tabs = tabs+ val sidebar = Views.sidebar(core.view("sidebar"))+ if (sidebar != this.sidebar) this.sidebar = sidebar+ val threads = Views.threads(core.view("threads"))+ if (threads != this.threads) this.threads = threads+ val navs = Views.navs(core.view("navs"))+ if (navs != this.navs) this.navs = navsval status = Views.status(core.view("status"))- if (status != this.status) this.status = status+ if (status != this.status) {+ this.status = status+ showToast(status?.toast)+ }+ Views.layout(core.view("layout"))?.let { layout ->+ if (layout.cellH > 0) cellHeight = layout.cellH+ if (layout.cellW > 0) cellWidth = layout.cellW+ if (layout.fontPt > 0 && layout.fontPt != fontPt) fontPt = layout.fontPt+ if (layout.scrollAbove != scrollAbove || layout.scrollMax != scrollMax) {+ scrollAbove = layout.scrollAbove+ scrollMax = layout.scrollMax+ scrollShown = true+ main.removeCallbacks(hideScrollbar)+ main.postDelayed(hideScrollbar, 1000)+ }+ }+ }++ private val hideScrollbar = Runnable { scrollShown = false }++ private fun showToast(toast: Toast?) {+ main.removeCallbacks(expireToast)+ val sticky = toast?.sticky ?: false+ if (reconnecting != sticky) reconnecting = sticky+ if (toast == null || toast.text.isEmpty()) {+ if (toastText != null) toastText = null+ return+ }+ toastText = toast.text+ toastShown = toast.text+ if (!sticky) main.postDelayed(expireToast, 4000)}- // MARK: what the core tells the shell+ private val expireToast = Runnable { if (toastText == toastShown) toastText = null }++ // MARK: the preferences the App honours++ private fun applyScheme() {+ val name = settings.schemeName+ val json = Schemes.json(name)+ if (name == Schemes.FOLLOW_DESKTOP || json == null) {+ core.setSetting("terminal-scheme", "\"desktop\"")+ core.setPalette(null)+ } else {+ core.setSetting("terminal-scheme", "\"" + name.replace("\"", "\\\"") + "\"")+ core.setPalette(json)+ }+ }++ private fun applyScrollMode() {+ core.setSetting("scroll-mode", if (settings.smoothScroll) "\"smooth\"" else "\"stepped\"")+ }++ private fun applyTerminalPrefs() {+ val style = settings.cursorStyle.takeIf { it in listOf("auto", "block", "bar", "underline") } ?: "auto"+ core.setSetting("cursor-style", "\"$style\"")+ core.setSetting("cursor-blink", settings.cursorBlink.toString())+ val contrast = when (settings.contrast) { "3" -> 3.0; "45" -> 4.5; "7" -> 7.0; else -> 0.0 }+ core.setSetting("min-contrast", contrast.toString())+ core.setSetting("resize-mode", if (settings.resizeMode == "release") "\"release\"" else "\"live\"")+ core.setSetting("auto-reconnect", settings.autoReconnect.toString())+ core.setSetting("pane-bars", settings.paneBars.toString())+ }++ // MARK: the log++ fun log(line: String) {+ Log.i("thinkterm", line)+ logLines.addLast(line)+ while (logLines.size > 60) logLines.removeFirst()+ logText = logLines.joinToString("\n")+ }++ // MARK: what the core tells the shell (core thread)private inner class Sink : Notify {override fun onFrameNeeded() {@@ -159,15 +433,26 @@ class TerminalModel(}override fun onStatus(status: String) {- main.post { connection = status }+ main.post {+ connection = status+ log("status: $status")+ if (status.startsWith("pane ")) {+ attached = true+ if (host.id != Host.PROBE_ID) store.touchConnected(host.id)+ }+ if (status.startsWith("connecting") || status.contains("reconnect") || status.startsWith("disconnected")) {+ composing = null+ }+ changePending.set(true)+ }}override fun onLog(line: String) {- Log.i("thinkterm", line)+ main.post { log("core: $line") }}override fun onTitle(title: String) {- main.post { [email protected] = title }+ main.post { if ([email protected] != title) [email protected] = title }}override fun onChange() {@@ -175,10 +460,7 @@ class TerminalModel(}override fun onClipboard(text: String) {- main.post {- val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager- cm?.setPrimaryClip(ClipData.newPlainText("thinkterm", text))- }+ main.post { copyToClipboard(text) }}override fun onFocusInput() {@@ -186,11 +468,19 @@ class TerminalModel(}override fun onImeAnchor(left: Double, top: Double, width: Double, height: Double) {- // Nothing yet: the Android IME is not asked where the caret is.+ main.post {+ cursorLeft = left+ cursorTop = top+ cursorWidth = width+ cursorHeight = height+ }}override fun onHostKey(fingerprint: String) {- main.post { store.rememberHostKey(host.id, fingerprint) }+ main.post {+ log("host key $fingerprint")+ if (host.id != Host.PROBE_ID) store.rememberHostKey(host.id, fingerprint)+ }}override fun onPublished(key: String, value: String) {@@ -200,17 +490,15 @@ class TerminalModel(}override fun onBell() {- main.post { buzz() }+ main.post { if (settings.bell) buzz() }}override fun onPreview(pane: UInt, rows: String) {- // The overview is not built yet.+ val decoded = Views.previewRows(rows)+ main.post { previews[pane.toInt()] = decoded }}}- /// 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) {@@ -224,17 +512,6 @@ class TerminalModel(// 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@@ -254,9 +531,9 @@ object Assets {}}- /// The base face first, the symbols fallback after it.- fun fontPaths(context: Context): List<String> =- listOf("JetBrainsMono-Regular.ttf", "SymbolsNerdFontMono-Regular.ttf")+ /// The chosen face first, the symbols fallback after it.+ fun fontPaths(context: Context, face: String = "JetBrainsMono-Regular.ttf"): List<String> =+ listOf(face, "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.ktindex 684e469d..ab102ee7 100644--- a/android/app/src/main/java/com/roversx/thinkterm/TerminalScreen.kt+++ b/android/app/src/main/java/com/roversx/thinkterm/TerminalScreen.kt@@ -1,163 +1,940 @@package com.roversx.thinktermimport androidx.activity.compose.BackHandler+import androidx.compose.animation.core.Animatable+import androidx.compose.animation.core.spring+import androidx.compose.animation.core.tween+import androidx.compose.foundation.ExperimentalFoundationApiimport androidx.compose.foundation.background+import androidx.compose.foundation.borderimport androidx.compose.foundation.clickable+import androidx.compose.foundation.combinedClickable+import androidx.compose.foundation.gestures.detectDragGestures+import androidx.compose.foundation.gestures.detectTransformGesturesimport androidx.compose.foundation.horizontalScrollimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxScopeimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.WindowInsetsimport androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.imePadding-import androidx.compose.foundation.layout.safeDrawingPaddingimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.ime+import androidx.compose.foundation.layout.imePadding+import androidx.compose.foundation.layout.offsetimport androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.safeDrawingPadding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.widthimport androidx.compose.foundation.layout.widthInimport androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.CircleShapeimport androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScroll+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.automirrored.filled.ArrowBack+import androidx.compose.material.icons.filled.Add+import androidx.compose.material.icons.filled.Close+import androidx.compose.material.icons.filled.GridView+import androidx.compose.material.icons.filled.MoreVert+import androidx.compose.material.icons.filled.Warning+import androidx.compose.material.icons.filled.CheckCircle+import androidx.compose.material.icons.outlined.Circle+import androidx.compose.material.icons.outlined.PowerOff+import androidx.compose.material3.Button+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.DropdownMenu+import androidx.compose.material3.DropdownMenuItem+import androidx.compose.material3.HorizontalDivider+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButton+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.OutlinedButtonimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.runtime.DisposableEffectimport androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateMapOf+import androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.runtime.snapshotFlowimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.drawWithContent+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rectimport androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.TransformOrigin+import androidx.compose.ui.graphics.drawscope.clipRect+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.boundsInRoot+import androidx.compose.ui.layout.onGloballyPositioned+import androidx.compose.ui.layout.positionInParentimport androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.platform.LocalLifecycleOwner+import androidx.compose.ui.text.font.FontFamilyimport androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlignimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dpimport androidx.compose.ui.unit.spimport androidx.compose.ui.viewinterop.AndroidView+import androidx.compose.ui.zIndex+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleEventObserver+import kotlinx.coroutines.flow.drop+import kotlinx.coroutines.launch+import kotlin.math.max+import kotlin.math.min-/// 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.+/// One host: its terminal, the two strips (threads over the current+/// thread's tabs), the bars over the panes, the key bar with the soft+/// keyboard, and the tree, overview, settings and menus over it. Every+/// piece of chrome takes the terminal's own background, as on iOS.+@OptIn(ExperimentalFoundationApi::class)@Composablefun TerminalScreen(host: Host, store: HostStore, onBack: () -> Unit) {val context = LocalContext.currentval model = remember(host.id) { TerminalModel(context, store, host) }+ val settings = model.settings+ val density = LocalDensity.current+ val scope = rememberCoroutineScope()+ val lang = AppLanguage.tag++ var showTree by remember { mutableStateOf(false) }+ var showSettings by remember { mutableStateOf(false) }+ val showLog = remember { mutableStateOf(false) }+ var editingHost by remember { mutableStateOf<Host?>(null) }+ var moreOpen by remember { mutableStateOf(false) }+ var paneMenuOpen by remember { mutableStateOf(false) }+ var hostView by remember { mutableStateOf<TerminalHostView?>(null) }++ // The overview: the terminal shrinks into its thread's card and the+ // cards fade in around it, as the desktop's Live Overview zooms out.+ var overviewShown by remember { mutableStateOf(false) }+ var terminalBounds by remember { mutableStateOf(Rect.Zero) }+ var cardBounds by remember { mutableStateOf<Rect?>(null) }+ val zoom = remember { Animatable(0f) }+ val overviewOpen = overviewShown && zoom.value > 0f+ var zoomTarget by remember { mutableStateOf<Rect?>(null) }++ val keyboardUp = WindowInsets.ime.getBottom(density) > 0+ val twoLevel = settings.tabBarLevels == "two" && !(model.threads?.threads.isNullOrEmpty())+ val currentThread = model.threads?.current// 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() } }++ // The open terminal follows the preferences as they change.+ LaunchedEffect(model) {+ snapshotFlow {+ listOf(+ settings.schemeName, settings.smoothScroll, settings.cursorStyle, settings.cursorBlink,+ settings.contrast, settings.resizeMode, settings.autoReconnect, settings.paneBars, settings.fontFamily,+ )+ }.drop(1).collect { model.settingsChanged() }+ }+ LaunchedEffect(showLog.value, settings.devMode) { model.wantsStats = showLog.value || settings.devMode }- DisposableEffect(model) {- onDispose { model.shutdown() }+ // Leaving the screen (Home, another app) with the setting off drops+ // the connection; coming back redials.+ val lifecycle = LocalLifecycleOwner.current.lifecycle+ DisposableEffect(lifecycle, model) {+ val observer = LifecycleEventObserver { _, event ->+ when (event) {+ Lifecycle.Event.ON_STOP -> model.enteredBackground()+ Lifecycle.Event.ON_START -> model.enteredForeground()+ else -> {}+ }+ }+ lifecycle.addObserver(observer)+ onDispose { lifecycle.removeObserver(observer) }+ }++ fun closeOverview() {+ if (!overviewShown) return+ scope.launch {+ zoom.animateTo(0f, spring(dampingRatio = 0.9f, stiffness = 400f))+ overviewShown = false+ zoomTarget = null+ cardBounds = null+ hostView?.input?.touchOverride = null+ }+ }++ fun openOverview() {+ if (overviewShown) return+ model.refreshViews()+ model.onHideKeyboard?.invoke()+ cardBounds = null+ zoomTarget = null+ overviewShown = true+ hostView?.input?.touchOverride = { closeOverview() }+ // Without a card of its own (no threads, or none current) the+ // terminal only fades.+ if (currentThread == null) {+ scope.launch { zoom.animateTo(1f, tween(250)) }+ }+ }++ // The card's thumbnail is laid out: the terminal goes there. Only the+ // first report counts; later ones must not restart the animation.+ fun cardLaidOut(frame: Rect?) {+ cardBounds = frame+ if (frame == null || !overviewShown || zoomTarget != null || terminalBounds.width <= 0f) return+ zoomTarget = frame+ scope.launch { zoom.animateTo(1f, spring(dampingRatio = 0.85f, stiffness = 300f)) }}BackHandler {- model.disconnect()- onBack()+ when {+ showSettings -> showSettings = false+ editingHost != null -> editingHost = null+ overviewShown -> closeOverview()+ else -> { model.disconnect(); onBack() }+ }}- Column(+ Box(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.+ .background(if (overviewOpen) Color(0xFF0F0F0F) else model.background).safeDrawingPadding()- .imePadding()) {- TopBar(model, onBack = {- model.disconnect()- onBack()- })- TabStrip(model)- Box(Modifier.fillMaxWidth().weight(1f)) {- AndroidView(- factory = { TerminalHostView(it, model) },- modifier = Modifier.fillMaxSize(),- )+ if (overviewShown) {+ Box(Modifier.fillMaxSize().graphicsLayer { alpha = zoom.value }) {+ OverviewScreen(+ model = model,+ liveThread = currentThread?.id,+ onCardBounds = { cardLaidOut(it) },+ onDismiss = { closeOverview() },+ )+ }+ }++ // Above the cards, so the shrunken terminal shows in its card. The+ // strips and bars leave while the overview is up, so the cards get+ // the taps; the terminal's own touches close it.+ Column(Modifier.fillMaxSize().zIndex(1f).imePadding()) {+ if (!overviewOpen) {+ TopBar(+ model = model,+ twoLevel = twoLevel,+ onBack = { model.disconnect(); onBack() },+ onTree = { showTree = true },+ onOverview = { openOverview() },+ onMore = { moreOpen = true },+ moreMenu = {+ MoreMenu(+ model = model,+ expanded = moreOpen,+ onDismiss = { moreOpen = false },+ onTree = { showTree = true },+ onOverview = { openOverview() },+ onSettings = { showSettings = true },+ onPaneMenu = { paneMenuOpen = true },+ )+ AppContextMenu(+ model = model,+ kind = "pane",+ id = (model.tabs?.current?.target ?: 0).toString(),+ expanded = paneMenuOpen,+ onDismiss = { paneMenuOpen = false },+ )+ },+ )+ if (twoLevel) TabSubstrip(model, onPinchOut = { openOverview() })+ } else {+ // Their room stays, so the terminal's own place does not+ // move under the zoom that was measured from it.+ Spacer(Modifier.height(if (twoLevel) 80.dp else 48.dp))+ }++ // The terminal, scaled and moved into the card and clipped to+ // its height as the zoom goes from 0 to 1.+ Box(+ Modifier+ .fillMaxWidth()+ .weight(1f)+ .onGloballyPositioned { if (!overviewShown) terminalBounds = it.boundsInRoot() }+ .graphicsLayer {+ val t = zoom.value+ val target = zoomTarget+ transformOrigin = TransformOrigin(0f, 0f)+ if (target != null && terminalBounds.width > 0) {+ val s = target.width / terminalBounds.width+ val scale = 1f + (s - 1f) * t+ scaleX = scale+ scaleY = scale+ translationX = (target.left - terminalBounds.left) * t+ translationY = (target.top - terminalBounds.top) * t+ } else {+ scaleX = 1f+ scaleY = 1f+ translationX = 0f+ translationY = 0f+ if (target == null && overviewShown) alpha = 1f - t+ }+ clip = true+ }+ .drawWithContent {+ val target = zoomTarget+ if (target != null && terminalBounds.width > 0) {+ val s = target.width / terminalBounds.width+ val full = size.height+ val clipped = target.height / s+ val h = full + (clipped - full) * zoom.value+ clipRect(bottom = h) { [email protected]() }+ } else {+ drawContent()+ }+ }+ .background(model.background)+ ) {+ AndroidView(+ factory = { TerminalHostView(it, model).also { v -> hostView = v } },+ modifier = Modifier.fillMaxSize(),+ )+ if (!overviewOpen) {+ TerminalOverlays(model, showLog.value, onEditHost = { editingHost = model.host }, onBack = { model.disconnect(); onBack() })+ }+ }++ if (!overviewOpen) {+ StatusLine(model)+ if (keyboardUp) {+ KeyBar(model = model, keyboardUp = keyboardUp, onOpenSettings = { showSettings = true })+ }+ }+ }++ if (showTree) {+ TreeSheet(model = model, onDismiss = { showTree = false })+ }+ if (showSettings) {+ Box(Modifier.fillMaxSize().zIndex(3f).background(MaterialTheme.colorScheme.background)) {+ SettingsScreen(model = model, showLog = showLog, onDone = { showSettings = false })+ }+ }+ editingHost?.let { h ->+ Box(Modifier.fillMaxSize().zIndex(3f).background(MaterialTheme.colorScheme.background)) {+ HostEditScreen(+ store = store,+ host = h,+ onSave = { edited, secret, passphrase ->+ if (secret.isNotEmpty() || store.secret(edited.id).isEmpty()) store.putSecret(edited.id, secret, passphrase)+ store.upsert(edited)+ model.host = edited+ editingHost = null+ model.connect()+ },+ onCancel = { editingHost = null },+ )+ }}- StatusLine(model)- KeyBar(model)}}+// MARK: the bar++/// The desktop's two layers, as two rows: threads (the sidebar's layer)+/// in the bar between the back button and the menu, the current thread's+/// tabs in a strip under it. A server without threads shows its tabs in+/// the bar instead.+@OptIn(ExperimentalFoundationApi::class)@Composable-private fun TopBar(model: TerminalModel, onBack: () -> Unit) {+private fun TopBar(+ model: TerminalModel,+ twoLevel: Boolean,+ onBack: () -> Unit,+ onTree: () -> Unit,+ onOverview: () -> Unit,+ onMore: () -> Unit,+ moreMenu: @Composable () -> Unit,+) {Row(- Modifier- .fillMaxWidth()- .height(44.dp)- .padding(horizontal = 10.dp),+ Modifier.fillMaxWidth().height(48.dp).padding(start = 2.dp, end = 2.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),- )+ IconButton(onClick = onBack) {+ Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = tr("back"), tint = Color.White)+ }+ Box(Modifier.size(7.dp).clip(CircleShape).background(statusColor(model)))+ Spacer(Modifier.width(6.dp))+ val scroll = rememberScrollState()+ val positions = remember { mutableStateMapOf<String, Int>() }+ val currentKey = if (twoLevel) model.threads?.current?.id?.let { "thread:$it" } else model.tabs?.current?.tab?.let { "tab:$it" }+ ScrollToCurrent(scroll, positions, currentKey)+ Row(+ Modifier.weight(1f).horizontalScroll(scroll),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(4.dp),+ ) {+ if (twoLevel) {+ for (thread in model.threads?.threads ?: emptyList()) {+ Box(Modifier.onGloballyPositioned { positions["thread:" + thread.id] = it.positionInParent().x.toInt() }) {+ ThreadPill(model, thread, onTree)+ }+ }+ PlusButton { model.sideClick("new-thread") }+ } else {+ TabPills(model, size = 12.sp, height = 26.dp, positions = positions)+ PlusButton { model.chromeClick("new-tab") }+ }+ }+ IconButton(onClick = onOverview) {+ Icon(Icons.Default.GridView, contentDescription = tr("overview"), tint = Color.White)+ }+ Box {+ IconButton(onClick = onMore) {+ Icon(Icons.Default.MoreVert, contentDescription = tr("more"), tint = Color.White)+ }+ moreMenu()+ }}}+@OptIn(ExperimentalFoundationApi::class)@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) {+private fun ThreadPill(model: TerminalModel, thread: ThreadView, onTree: () -> Unit) {+ var menu by remember { mutableStateOf(false) }+ Box {+ Row(+ Modifier+ .clip(RoundedCornerShape(50))+ .background(Color.White.copy(alpha = if (thread.current) 0.18f else 0.06f))+ .combinedClickable(+ // The one on show opens the tree; another is shown.+ onClick = { if (thread.current) onTree() else model.sideClick("thread", thread.id) },+ onLongClick = { menu = true },+ )+ .widthIn(min = 64.dp)+ .height(26.dp)+ .padding(horizontal = 10.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(5.dp),+ ) {+ Box(Modifier.size(6.dp).clip(CircleShape).background(threadColor(thread.status, thread.live)))Text(- text = tab.label.ifEmpty { "Tab ${tab.tab}" },- color = if (tab.current) Color.White else Color.White.copy(alpha = 0.62f),+ thread.name,+ color = Color.White,fontSize = 12.sp,+ fontWeight = if (thread.current) FontWeight.SemiBold else FontWeight.Normal,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ }+ AppContextMenu(model, "thread", thread.id, expanded = menu, onDismiss = { menu = false })+ }+}++/// The strip follows the current pill: it scrolls so the pill sits a+/// third of the way in, as the iOS strips do.+@Composable+private fun ScrollToCurrent(scroll: androidx.compose.foundation.ScrollState, positions: Map<String, Int>, key: String?) {+ val x = key?.let { positions[it] }+ LaunchedEffect(key, x) {+ if (x != null) scroll.animateScrollTo((x - scroll.viewportSize / 3).coerceAtLeast(0))+ }+}++@OptIn(ExperimentalFoundationApi::class)+@Composable+private fun TabPills(+ model: TerminalModel,+ size: androidx.compose.ui.unit.TextUnit,+ height: androidx.compose.ui.unit.Dp,+ positions: MutableMap<String, Int>,+) {+ for (tab in model.tabs?.tabs ?: emptyList()) {+ var menu by remember(tab.tab) { mutableStateOf(false) }+ Box(Modifier.onGloballyPositioned { positions["tab:" + tab.tab] = it.positionInParent().x.toInt() }) {+ Text(+ text = tab.label.ifEmpty { tr("tab.num", tab.tab) },+ color = if (tab.current) Color.White else Color.White.copy(alpha = 0.62f),+ fontSize = size,fontWeight = if (tab.current) FontWeight.SemiBold else FontWeight.Normal,maxLines = 1,overflow = TextOverflow.Ellipsis,+ textAlign = TextAlign.Center,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),+ .combinedClickable(+ onClick = { model.chromeClick("pane", pane = tab.target) },+ onLongClick = { menu = true },+ )+ .widthIn(min = 76.dp, max = 140.dp)+ .heightIn(min = height)+ .padding(horizontal = 10.dp, vertical = 4.dp),)+ AppContextMenu(model, "tab", tab.tab.toString(), expanded = menu, onDismiss = { menu = false })+ }+ }+}++@Composable+private fun PlusButton(onClick: () -> Unit) {+ Icon(+ Icons.Default.Add,+ contentDescription = tr("newtab"),+ tint = Color.White.copy(alpha = 0.62f),+ modifier = Modifier.size(28.dp).clip(CircleShape).clickable(onClick = onClick).padding(5.dp),+ )+}++/// The current thread's tabs, under the bar. Pinching the strip in zooms+/// out to the overview.+@Composable+private fun TabSubstrip(model: TerminalModel, onPinchOut: () -> Unit) {+ var pinch by remember { mutableStateOf(1f) }+ val scroll = rememberScrollState()+ val positions = remember { mutableStateMapOf<String, Int>() }+ ScrollToCurrent(scroll, positions, model.tabs?.current?.tab?.let { "tab:$it" })+ Row(+ Modifier+ .fillMaxWidth()+ .height(32.dp)+ .background(model.background)+ .pointerInput(Unit) {+ detectTransformGestures { _, _, zoom, _ ->+ pinch *= zoom+ if (pinch < 0.8f) {+ pinch = 1f+ onPinchOut()+ }+ }+ }+ .padding(horizontal = 8.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Row(+ Modifier.weight(1f).horizontalScroll(scroll),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(4.dp),+ ) {+ TabPills(model, size = 11.5.sp, height = 22.dp, positions = positions)}+ PlusButton { model.chromeClick("new-tab") }+ }+}++private fun statusColor(model: TerminalModel): Color = when {+ model.reconnecting -> Color(0xFFFF9F0A)+ model.isConnected -> Color(0xFF34C759)+ model.connection.startsWith("connecting") || model.connection.contains("reconnect") -> Color(0xFFFF9F0A)+ else -> Color(0xFFFF453A)+}++/// The ⋯ menu: the host's connection, the splits, the pane's own menu,+/// the tree and the overview, paste, settings, and closing the pane.+@Composable+private fun MoreMenu(+ model: TerminalModel,+ expanded: Boolean,+ onDismiss: () -> Unit,+ onTree: () -> Unit,+ onOverview: () -> Unit,+ onSettings: () -> Unit,+ onPaneMenu: () -> Unit,+) {+ DropdownMenu(expanded = expanded, onDismissRequest = onDismiss) {+ val connected = model.isConnected+ Text(+ model.host.display,+ style = MaterialTheme.typography.labelSmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 6.dp),+ )+ DropdownMenuItem(+ text = { Text(if (connected) tr("disconnect") else tr("reconnect")) },+ onClick = { if (connected) model.disconnect() else model.connect(); onDismiss() },+ )+ HorizontalDivider()+ DropdownMenuItem(text = { Text(tr("split.right")) }, onClick = { model.chromeClick("split-right"); onDismiss() })+ DropdownMenuItem(text = { Text(tr("split.below")) }, onClick = { model.chromeClick("split-below"); onDismiss() })+ DropdownMenuItem(text = { Text(tr("zoom")) }, onClick = { model.chromeClick("zoom"); onDismiss() })+ DropdownMenuItem(text = { Text(tr("pane")) }, onClick = { onDismiss(); onPaneMenu() })+ HorizontalDivider()+ DropdownMenuItem(text = { Text(tr("m.threadstabs")) }, onClick = { onDismiss(); onTree() })+ DropdownMenuItem(text = { Text(tr("m.overview")) }, onClick = { onDismiss(); onOverview() })+ DropdownMenuItem(text = { Text(tr("paste")) }, onClick = { model.pasteFromClipboard(); onDismiss() })+ HorizontalDivider()+ DropdownMenuItem(text = { Text(tr("m.settings")) }, onClick = { onDismiss(); onSettings() })+ DropdownMenuItem(+ text = { Text(tr("closepane"), color = MaterialTheme.colorScheme.error) },+ onClick = { model.chromeClick("close"); onDismiss() },+ )+ }+}++// MARK: over the terminal++/// The bars over split panes, the scrollbar, the stats, the composition,+/// the take-over card, the log, the selection's copy chip, and the card+/// while there is no terminal to show.+@Composable+private fun BoxScope.TerminalOverlays(model: TerminalModel, showLog: Boolean, onEditHost: () -> Unit, onBack: () -> Unit) {+ val settings = model.settings+ if (model.navs.size > 1 && settings.paneBars) {+ NavBars(model)+ }+ if (settings.scrollbar && model.scrollMax > 0 && model.scrollShown) {+ Scrollbar(model)+ }+ if (settings.devMode) {Text(- "+",- color = Color.White.copy(alpha = 0.62f),- fontSize = 16.sp,+ model.stats,+ fontSize = 8.sp,+ fontFamily = FontFamily.Monospace,+ color = Color.White.copy(alpha = 0.7f),+ modifier = Modifier.align(Alignment.BottomStart).background(Color.Black.copy(alpha = 0.5f)).padding(4.dp),+ )+ }+ model.composing?.let { composing ->+ Text(+ composing,+ fontSize = 14.sp,+ fontFamily = FontFamily.Monospace,+ color = Color.Black,+ modifier = Modifier+ .padding(8.dp)+ .clip(RoundedCornerShape(4.dp))+ .background(Color(0xE6FFEB3B))+ .padding(4.dp),+ )+ }+ model.selectionMenuAt?.let { (x, y) ->+ // The chip sits over the head cell, a row above it when it fits.+ val top = (y - 40).coerceAtLeast(0.0)+ Text(+ if (model.copied) tr("copied") else tr("copy"),+ color = Color.White,+ fontSize = 13.sp,modifier = Modifier- .clickable { model.chromeClick("new-tab") }- .padding(horizontal = 10.dp, vertical = 4.dp),+ .offset(x = x.dp, y = top.dp)+ .clip(RoundedCornerShape(8.dp))+ .background(Color(0xFF2C2C2E))+ .clickable { model.copySelection() }+ .padding(horizontal = 12.dp, vertical = 7.dp),)}+ model.status?.card?.let { card ->+ Column(+ Modifier+ .align(Alignment.Center)+ .widthIn(max = 320.dp)+ .clip(RoundedCornerShape(12.dp))+ .background(Color(0xF0202124))+ .padding(16.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ Text(card.title, color = Color.White, fontWeight = FontWeight.SemiBold)+ Text(card.hint, color = Color.White.copy(alpha = 0.7f), fontSize = 12.sp, textAlign = TextAlign.Center)+ Button(onClick = { model.takeOver() }, enabled = card.state != "taking") { Text(card.action) }+ }+ }+ if (showLog) {+ Text(+ model.logText + "\n" + model.stats,+ fontSize = 9.sp,+ fontFamily = FontFamily.Monospace,+ color = Color.White,+ modifier = Modifier+ .align(Alignment.BottomStart)+ .fillMaxWidth()+ .heightIn(max = 220.dp)+ .background(Color.Black.copy(alpha = 0.8f))+ .verticalScroll(rememberScrollState())+ .padding(6.dp),+ )+ }+ val phase = ConnectionPhase.of(model.connection)+ if (model.reconnecting && !settings.autoReconnect && phase == null) {+ // Asked not to redial: the card offers it instead.+ ConnectionCard(ConnectionPhase.Disconnected, model.host.display, canEdit = model.host.id != Host.PROBE_ID) { action ->+ when (action) {+ CardAction.Back -> onBack()+ else -> model.connect()+ }+ }+ }+ if (phase != null) {+ ConnectionCard(phase, model.host.display, canEdit = model.host.id != Host.PROBE_ID) { action ->+ when (action) {+ CardAction.Retry -> model.connect()+ CardAction.ForgetKeyAndRetry -> {+ model.store.forgetHostKey(model.host.id)+ model.host = model.host.copy(knownHost = null)+ model.connect()+ }+ CardAction.Edit -> onEditHost()+ CardAction.Back -> onBack()+ }+ }+ }}-/// The connection's own line while it is not yet a pane, and whatever-/// the App wants said on top of it.+/// The App leaves rows above each pane for its bar; these draw it where+/// the App says (dp, from the terminal's origin). Dragging a bar drags+/// the divider it sits under (or beside): the press lands just outside+/// the bar, and the App does the rest.+@OptIn(ExperimentalFoundationApi::class)+@Composable+private fun BoxScope.NavBars(model: TerminalModel) {+ val density = LocalDensity.current+ for (nav in model.navs) {+ val r = nav.rect+ var menu by remember(r.pane) { mutableStateOf(false) }+ Box(+ Modifier+ .offset(x = r.left.dp, y = r.top.dp)+ .width(r.width.dp)+ .height(r.height.dp)+ .background(model.background)+ .background(Color.White.copy(alpha = if (nav.focused) 0.1f else 0.04f))+ .pointerInput(nav.rect) {+ var origin: Offset? = null+ detectDragGestures(+ onDragStart = { start ->+ val s = Offset(start.x / density.density, start.y / density.density)+ origin = when {+ r.top > 0 -> Offset((r.left + s.x).toFloat(), (r.top - 2).toFloat())+ r.left > 0 -> Offset((r.left - 2).toFloat(), (r.top + s.y).toFloat())+ else -> null+ }+ origin?.let { model.pointer("down", it.x.toDouble(), it.y.toDouble()) }+ },+ onDrag = { change, _ ->+ val o = origin ?: return@detectDragGestures+ val p = change.position+ model.pointer("move", (o.x + p.x / density.density).toDouble(), (o.y + p.y / density.density).toDouble())+ },+ onDragEnd = {+ origin?.let { model.pointer("up", it.x.toDouble(), it.y.toDouble()) }+ origin = null+ },+ onDragCancel = { origin = null },+ )+ }+ .combinedClickable(onClick = {}, onLongClick = { menu = true })+ .padding(horizontal = 6.dp),+ ) {+ Row(Modifier.fillMaxSize(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {+ val tint = if (nav.focused) Color.White else Color(0xFF9E9E9E)+ for (member in nav.members) {+ Row(+ Modifier+ .clip(RoundedCornerShape(50))+ .background(if (member.current) Color.White.copy(alpha = if (nav.focused) 0.22f else 0.12f) else Color.Transparent)+ .clickable { model.chromeClick("pane", pane = member.pane) }+ .padding(horizontal = 6.dp, vertical = 2.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(4.dp),+ ) {+ if (member.busy) CircularProgressIndicator(Modifier.size(9.dp), strokeWidth = 1.5.dp, color = tint)+ Text(+ member.title.ifEmpty { "shell" },+ color = tint,+ fontSize = 11.sp,+ fontWeight = if (member.current) FontWeight.SemiBold else FontWeight.Normal,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ }+ }+ Spacer(Modifier.weight(1f))+ Icon(Icons.Default.Add, contentDescription = null, tint = tint, modifier = Modifier.size(16.dp).clickable { model.chromeClick("new-pane", pane = r.pane) })+ Icon(Icons.Default.Close, contentDescription = null, tint = tint, modifier = Modifier.size(16.dp).clickable { model.chromeClick("close-pane", pane = r.pane) })+ }+ AppContextMenu(model, "pane", r.pane.toString(), expanded = menu, onDismiss = { menu = false })+ }+ }+}++/// A thin bar at the right: where the view is in the scrollback.+@Composable+private fun BoxScope.Scrollbar(model: TerminalModel) {+ var height by remember { mutableStateOf(0f) }+ val density = LocalDensity.current+ Box(+ Modifier+ .fillMaxSize()+ .onGloballyPositioned { height = it.size.height / density.density }+ ) {+ val rowsVisible = height / max(model.cellHeight, 1.0).toFloat()+ val total = model.scrollMax + rowsVisible+ val thumb = max(height * rowsVisible / max(total, 1f), 24f)+ val track = height - thumb+ val y = track * (1f - model.scrollAbove.toFloat() / max(model.scrollMax, 1).toFloat())+ Box(+ Modifier+ .align(Alignment.TopEnd)+ .offset(x = (-3).dp, y = y.dp)+ .size(3.dp, thumb.dp)+ .clip(RoundedCornerShape(2.dp))+ .background(Color.White.copy(alpha = 0.35f))+ )+ }+}++/// The App's remark, "copied", or the connection's own line while it is+/// not yet a pane.@Composableprivate fun StatusLine(model: TerminalModel) {- val toast = model.status?.toast- val connection = model.connection.takeIf { it.isNotEmpty() && !it.startsWith("pane ") }- val line = toast ?: connection ?: return+ val text = if (model.copied) tr("copied") else (model.toastText ?: "")+ val c = model.connection+ val showing = text.isNotEmpty() || c.startsWith("connecting") || c.startsWith("disconnected") || c.startsWith("failed") || c.contains("reconnect")+ if (!showing) returnText(- line,- color = Color.White.copy(alpha = 0.7f),+ text.ifEmpty { c },+ color = Color.White,fontSize = 11.sp,+ fontFamily = FontFamily.Monospace,maxLines = 2,- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = 10.dp, vertical = 4.dp),+ modifier = Modifier.fillMaxWidth().background(Color(0xFF333333)).padding(horizontal = 8.dp, vertical = 4.dp),)}++// MARK: the connection card++/// Where a connection is, read off the core's status line.+sealed class ConnectionPhase {+ data class Connecting(val target: String) : ConnectionPhase()+ object Attaching : ConnectionPhase()+ object Reconnecting : ConnectionPhase()+ data class Failed(val reason: String) : ConnectionPhase()+ object Disconnected : ConnectionPhase()++ companion object {+ fun of(status: String): ConnectionPhase? = when {+ status.startsWith("pane ") -> null+ status.startsWith("connecting") -> Connecting(status.removePrefix("connecting to ").removePrefix("connecting"))+ status.startsWith("connected") -> Attaching+ status.contains("reconnect") -> Reconnecting+ status.startsWith("failed: ") -> Failed(status.removePrefix("failed: "))+ status.startsWith("attach failed: ") -> Failed(status.removePrefix("attach failed: "))+ status.startsWith("disconnected: ") -> Failed(status.removePrefix("disconnected: "))+ status.startsWith("disconnected") -> Disconnected+ // "idle", or nothing yet: the connection is about to start.+ else -> Connecting("")+ }+ }+}++enum class CardAction { Retry, ForgetKeyAndRetry, Edit, Back }++/// The card over the terminal while there is no terminal to show: the+/// steps of a connection, or what stopped it and what to do about it.+@Composable+private fun BoxScope.ConnectionCard(phase: ConnectionPhase, hostName: String, canEdit: Boolean, act: (CardAction) -> Unit) {+ Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.4f)), contentAlignment = Alignment.Center) {+ Column(+ Modifier+ .widthIn(max = 340.dp)+ .clip(RoundedCornerShape(16.dp))+ .background(Color(0xF5202124))+ .padding(20.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(14.dp),+ ) {+ when (phase) {+ is ConnectionPhase.Connecting -> {+ CircularProgressIndicator()+ Text(tr("card.connecting", hostName), color = Color.White, fontWeight = FontWeight.SemiBold)+ if (phase.target.isNotEmpty()) {+ Text(phase.target, color = Color.White.copy(alpha = 0.6f), fontSize = 12.sp, fontFamily = FontFamily.Monospace)+ }+ Steps(done = 0)+ }+ ConnectionPhase.Attaching -> {+ CircularProgressIndicator()+ Text(tr("card.attaching", hostName), color = Color.White, fontWeight = FontWeight.SemiBold)+ Steps(done = 1)+ }+ ConnectionPhase.Reconnecting -> {+ CircularProgressIndicator()+ Text(tr("card.reconnecting", hostName), color = Color.White, fontWeight = FontWeight.SemiBold)+ }+ ConnectionPhase.Disconnected -> {+ Icon(Icons.Outlined.PowerOff, contentDescription = null, tint = Color.White.copy(alpha = 0.6f), modifier = Modifier.size(34.dp))+ Text(tr("conn.disconnected"), color = Color.White, fontWeight = FontWeight.SemiBold)+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ OutlinedButton(onClick = { act(CardAction.Back) }) { Text(tr("back")) }+ Button(onClick = { act(CardAction.Retry) }) { Text(tr("reconnect")) }+ }+ }+ is ConnectionPhase.Failed -> {+ Icon(Icons.Default.Warning, contentDescription = null, tint = Color(0xFFFF9F0A), modifier = Modifier.size(34.dp))+ Text(tr("card.failed", hostName), color = Color.White, fontWeight = FontWeight.SemiBold, textAlign = TextAlign.Center)+ Text(+ phase.reason,+ color = Color.White.copy(alpha = 0.6f),+ fontSize = 12.sp,+ fontFamily = FontFamily.Monospace,+ textAlign = TextAlign.Center,+ maxLines = 6,+ overflow = TextOverflow.Ellipsis,+ )+ hintFor(phase.reason)?.let { Text(it, color = Color.White, fontSize = 13.sp, textAlign = TextAlign.Center) }+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ OutlinedButton(onClick = { act(CardAction.Back) }) { Text(tr("back")) }+ if (canEdit) OutlinedButton(onClick = { act(CardAction.Edit) }) { Text(tr("edithost")) }+ if (phase.reason.contains("key changed") && canEdit) {+ Button(onClick = { act(CardAction.ForgetKeyAndRetry) }) { Text(tr("forgetretry")) }+ } else {+ Button(onClick = { act(CardAction.Retry) }) { Text(tr("retry")) }+ }+ }+ }+ }+ }+ }+}++@Composable+private fun Steps(done: Int) {+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {+ Step(tr("conn.step1"), state = if (done > 0) 2 else 1)+ Step(tr("conn.step2"), state = if (done > 1) 2 else if (done == 1) 1 else 0)+ }+}++@Composable+private fun Step(label: String, state: Int) {+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ Icon(+ if (state == 2) Icons.Default.CheckCircle else Icons.Outlined.Circle,+ contentDescription = null,+ tint = if (state == 2) Color(0xFF34C759) else Color.White.copy(alpha = 0.5f),+ modifier = Modifier.size(16.dp),+ )+ Text(label, color = if (state == 0) Color.White.copy(alpha = 0.5f) else Color.White, fontSize = 13.sp)+ }+}++/// What the reason usually means, in plain words.+private fun hintFor(reason: String): String? {+ val r = reason.lowercase()+ return when {+ r.contains("refused the login") || r.contains("auth") -> tr("hint.auth")+ r.contains("key changed") -> tr("hint.keychanged")+ r.contains("timed out") || r.contains("connection refused") || r.contains("unreachable") || r.contains("no route") -> tr("hint.unreachable")+ r.contains("not found") || r.contains("exit 127") || r.contains("no such file") -> tr("hint.notfound")+ r.contains("codec") || r.contains("version") -> tr("hint.version")+ else -> null+ }+}diff --git a/android/app/src/main/java/com/roversx/thinkterm/TerminalView.kt b/android/app/src/main/java/com/roversx/thinkterm/TerminalView.ktindex e7464283..cb4c5413 100644--- a/android/app/src/main/java/com/roversx/thinkterm/TerminalView.kt+++ b/android/app/src/main/java/com/roversx/thinkterm/TerminalView.kt@@ -2,12 +2,17 @@ package com.roversx.thinktermimport android.annotation.SuppressLintimport android.content.Context+import android.graphics.SurfaceTexture+import android.os.Handler+import android.os.Looperimport android.util.Log+import android.view.HapticFeedbackConstantsimport android.view.KeyEventimport android.view.MotionEventimport android.view.ScaleGestureDetector-import android.view.SurfaceHolder-import android.view.SurfaceView+import android.view.Surface+import android.view.TextureView+import android.view.VelocityTrackerimport android.view.Viewimport android.view.ViewConfigurationimport android.view.inputmethod.BaseInputConnection@@ -15,49 +20,44 @@ import android.view.inputmethod.EditorInfoimport android.view.inputmethod.InputConnectionimport android.view.inputmethod.InputMethodManagerimport android.widget.FrameLayout+import android.widget.OverScroller+import kotlin.math.abs+import kotlin.math.floor-/// The terminal itself: a SurfaceView the core draws on, with a+/// The terminal itself: a TextureView the core draws on (a plain view, so+/// the overview can scale and clip it like any other), 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 val texture = TextureView(context)+ val input = TerminalInputView(context, model)+ private var surface: Surface? = nullprivate var window: Long = 0private var lastSize = Triple(0, 0, 0.0)init {- addView(surfaceView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))+ texture.isOpaque = true+ addView(texture, 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)+ model.onHideKeyboard = { input.hideKeyboard() }+ texture.surfaceTextureListener = object : TextureView.SurfaceTextureListener {+ override fun onSurfaceTextureAvailable(st: SurfaceTexture, width: Int, height: Int) {+ val s = Surface(st)+ surface = s+ window = NativeWindow.fromSurface(s)Log.i("thinkterm", "shell: native window $window")+ attachOrResize(width, height)}- 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 onSurfaceTextureSizeChanged(st: SurfaceTexture, width: Int, height: Int) {+ attachOrResize(width, height)}- override fun surfaceDestroyed(holder: SurfaceHolder) {+ override fun onSurfaceTextureDestroyed(st: SurfaceTexture): Boolean {// The handshake: detach must return before the surface is// released, or the core would draw into freed memory.if (model.generation != 0uL) {@@ -68,33 +68,88 @@ class TerminalHostView(context: Context, private val model: TerminalModel) : FraNativeWindow.release(window)window = 0}+ surface?.release()+ surface = nulllastSize = Triple(0, 0, 0.0)+ return true}- })++ override fun onSurfaceTextureUpdated(st: SurfaceTexture) {}+ }+ }++ private fun attachOrResize(width: Int, height: Int) {+ if (window == 0L || width <= 0 || height <= 0) 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")+ // Keys go to the terminal from the start; the keyboard waits+ // for a tap.+ input.requestFocus()+ } else if (lastSize != Triple(width, height, density)) {+ lastSize = Triple(width, height, density)+ model.core.resize(model.generation, width.toUInt(), height.toUInt(), density)+ }}}/// Touches, hardware keys and the IME. Invisible: it only takes input.+/// A tap raises the keyboard, one finger scrolls (smooth with a fling, or+/// by whole rows), a horizontal flick switches tabs, a pinch steps the+/// text size, two fingers swiped down put the keyboard away, and a long+/// press starts a selection the finger then extends.@SuppressLint("ViewConstructor")class TerminalInputView(context: Context, private val model: TerminalModel) : View(context) {+ private val settings get() = model.settingsprivate val slop = ViewConfiguration.get(context).scaledTouchSlopprivate val tapTimeout = ViewConfiguration.getTapTimeout().toLong() * 2+ private val longPressTimeout = ViewConfiguration.getLongPressTimeout().toLong()+ private val minFling = ViewConfiguration.get(context).scaledMinimumFlingVelocity * 4+ private val main = Handler(Looper.getMainLooper())private var downX = 0fprivate var downY = 0fprivate var lastY = 0fprivate var downAt = 0Lprivate var dragging = false+ private var pinching = falseprivate var pinchStart = 1f+ private var rowRemainder = 0f+ private var velocity: VelocityTracker? = null+ private val scroller = OverScroller(context)+ private var flingLast = 0+ /// Two fingers: their mean y when they landed, for the swipe down.+ private var twoFingerStartY: Float? = null+ private var twoFingerDone = false++ // MARK: selection++ /// The end the finger moves while selecting; null while not selecting.+ private var selecting = false+ private var anchor: Pair<Int, Int>? = null+ private var head: Pair<Int, Int>? = null+ private var screen: ScreenText? = null+ private val longPress = Runnable { startSelection() }/// 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+ /// While the overview is up the shrunken terminal is a card: any+ /// touch on it is a tap on the card, not input.+ var touchOverride: (() -> Unit)? = null+private val density: Float get() = resources.displayMetrics.densityprivate val pinch = ScaleGestureDetector(context, object : ScaleGestureDetector.SimpleOnScaleGestureListener() {override fun onScaleBegin(d: ScaleGestureDetector): Boolean {+ if (!settings.pinchZoom) return falsepinchStart = 1f+ pinching = true+ dropLongPress()return true}@@ -102,20 +157,25 @@ class TerminalInputView(context: Context, private val model: TerminalModel) : Vi// 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)+ model.stepFont(1.0)}while (d.scaleFactor < pinchStart / 1.15f) {pinchStart /= 1.15f- model.core.stepFont(-1.0)+ model.stepFont(-1.0)}return true}++ override fun onScaleEnd(d: ScaleGestureDetector) {+ pinching = false+ }})init {isFocusable = trueisFocusableInTouchMode = trueisClickable = true+ model.onScreenChanged = { if (anchor != null) screen = null }}fun focusAndShowKeyboard() {@@ -124,23 +184,63 @@ class TerminalInputView(context: Context, private val model: TerminalModel) : Viimm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)}+ fun hideKeyboard() {+ val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager+ imm.hideSoftInputFromWindow(windowToken, 0)+ }+// MARK: touches@SuppressLint("ClickableViewAccessibility")override fun onTouchEvent(event: MotionEvent): Boolean {+ touchOverride?.let {+ if (event.actionMasked == MotionEvent.ACTION_UP) it()+ return true+ }pinch.onTouchEvent(event)when (event.actionMasked) {MotionEvent.ACTION_DOWN -> {+ scroller.forceFinished(true)+ velocity?.recycle()+ velocity = VelocityTracker.obtain().also { it.addMovement(event) }downX = event.xdownY = event.ylastY = event.ydownAt = event.eventTimedragging = false+ selecting = false+ twoFingerStartY = null+ twoFingerDone = false+ // A press on an end of a standing selection moves that end.+ if (anchor != null && grabEnd(event.x, event.y)) {+ selecting = true+ } else if (settings.longPressSelects) {+ main.postDelayed(longPress, longPressTimeout)+ }+ }++ MotionEvent.ACTION_POINTER_DOWN -> {+ dropLongPress()+ if (event.pointerCount == 2 && !selecting) {+ twoFingerStartY = (event.getY(0) + event.getY(1)) / 2+ }}MotionEvent.ACTION_MOVE -> {- if (event.pointerCount > 1) return true- if (!dragging && Math.abs(event.y - downY) > slop) dragging = true+ velocity?.addMovement(event)+ if (selecting) {+ extendSelection(event.x, event.y)+ return true+ }+ if (event.pointerCount > 1) {+ twoFinger(event)+ return true+ }+ if (pinching) return true+ if (!dragging && (abs(event.y - downY) > slop || abs(event.x - downX) > slop)) {+ dragging = true+ dropLongPress()+ }if (dragging) {// A busy main thread gets the moves coalesced: the// samples in between ride along as history.@@ -150,20 +250,52 @@ class TerminalInputView(context: Context, private val model: TerminalModel) : Vi}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()+ dropLongPress()+ if (selecting) {+ selecting = false+ finishSelection()+ return true}+ if (dragging) {+ scrollTo(event.y)+ val dx = event.x - downX+ val dy = event.y - downY+ if (abs(dx) > 80 * density && abs(dx) > 2 * abs(dy)) {+ // A sideways flick: the next tab along.+ model.switchTab(if (dx < 0) 1 else -1)+ } else if (settings.smoothScroll) {+ fling()+ }+ } else if (!pinching && twoFingerStartY == null && event.eventTime - downAt < tapTimeout) {+ tap()+ }+ velocity?.recycle()+ velocity = null+ }++ MotionEvent.ACTION_CANCEL -> {+ dropLongPress()+ selecting = false+ velocity?.recycle()+ velocity = null}}return true}+ private fun tap() {+ if (anchor != null) {+ // A tap outside a selection puts it away; the keyboard stays.+ clearSelection()+ return+ }+ val x = (downX / density).toDouble()+ val y = (downY / density).toDouble()+ model.pointer("down", x, y)+ model.pointer("up", x, y)+ focusAndShowKeyboard()+ }+/// 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.@@ -171,11 +303,113 @@ class TerminalInputView(context: Context, private val model: TerminalModel) : Vival px = (lastY - y) / densitylastY = yif (px == 0f) return- model.core.wheelPx(- (width / 2f / density).toDouble(),- (height / 2f / density).toDouble(),- px.toDouble(),- )+ val cx = (width / 2f / density).toDouble()+ val cy = (height / 2f / density).toDouble()+ if (settings.smoothScroll) {+ model.wheelPx(cx, cy, px.toDouble())+ } else {+ // Whole rows, at the App's own row height.+ val row = model.cellHeight.toFloat().coerceAtLeast(1f)+ rowRemainder += px+ val rows = (rowRemainder / row).toInt()+ if (rows != 0) {+ rowRemainder -= rows * row+ model.wheel(cx, cy, -rows.toDouble())+ }+ }+ }++ /// The finger lifted at speed: the scroll carries on and slows.+ private fun fling() {+ val v = velocity ?: return+ v.computeCurrentVelocity(1000)+ val vy = v.yVelocity+ if (abs(vy) < minFling) return+ flingLast = 0+ scroller.fling(0, 0, 0, (-vy).toInt(), 0, 0, Int.MIN_VALUE / 2, Int.MAX_VALUE / 2)+ postOnAnimation(flingStep)+ }++ private val flingStep = object : Runnable {+ override fun run() {+ if (!scroller.computeScrollOffset()) return+ val y = scroller.currY+ val dy = y - flingLast+ flingLast = y+ if (dy != 0) {+ model.wheelPx((width / 2f / density).toDouble(), (height / 2f / density).toDouble(), (dy / density).toDouble())+ }+ postOnAnimation(this)+ }+ }++ /// Two fingers moving together, down: the keyboard goes away.+ private fun twoFinger(event: MotionEvent) {+ val start = twoFingerStartY ?: return+ if (twoFingerDone || !settings.twoFingerHidesKeyboard || event.pointerCount < 2) return+ val y = (event.getY(0) + event.getY(1)) / 2+ if (y - start > 48 * density) {+ twoFingerDone = true+ hideKeyboard()+ }+ }++ // MARK: selection++ private fun dropLongPress() = main.removeCallbacks(longPress)++ private fun cellAt(x: Float, y: Float): Pair<Int, Int>? {+ val s = screen ?: Views.screenText(model.core.screenText())?.also { screen = it } ?: return null+ if (s.rows <= 0 || s.cols <= 0) return null+ val col = floor((x / density - s.originX) / s.cellW).toInt().coerceIn(0, s.cols - 1)+ val row = floor((y / density - s.originY) / s.cellH).toInt().coerceIn(0, s.rows - 1)+ return Pair(row, col)+ }++ private fun startSelection() {+ if (dragging || pinching || twoFingerStartY != null) return+ val cell = cellAt(downX, downY) ?: return+ selecting = true+ anchor = cell+ head = cell+ performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)+ model.core.setSelection(cell.first.toUInt(), cell.second.toUInt(), cell.first.toUInt(), cell.second.toUInt())+ model.selectionMenuAt = null+ }++ private fun extendSelection(x: Float, y: Float) {+ val a = anchor ?: return+ val cell = cellAt(x, y) ?: return+ if (cell == head) return+ head = cell+ model.core.setSelection(a.first.toUInt(), a.second.toUInt(), cell.first.toUInt(), cell.second.toUInt())+ }++ /// A press within a cell of an end takes that end along; the other+ /// end becomes the anchor.+ private fun grabEnd(x: Float, y: Float): Boolean {+ val cell = cellAt(x, y) ?: return false+ val a = anchor ?: return false+ val h = head ?: return false+ fun near(p: Pair<Int, Int>) = abs(p.first - cell.first) <= 1 && abs(p.second - cell.second) <= 1+ return when {+ near(h) -> true+ near(a) -> { anchor = h; head = a; true }+ else -> false+ }+ }++ private fun finishSelection() {+ val s = screen ?: return+ val h = head ?: return+ model.selectionMenuAt = Pair(s.originX + h.second * s.cellW, s.originY + h.first * s.cellH)+ }++ fun clearSelection() {+ anchor = null+ head = null+ screen = null+ model.clearSelection()}// MARK: hardware keys (and `adb shell input text`)@@ -213,6 +447,18 @@ class TerminalInputView(context: Context, private val model: TerminalModel) : ViKeyEvent.KEYCODE_PAGE_UP -> "PageUp"KeyEvent.KEYCODE_PAGE_DOWN -> "PageDown"KeyEvent.KEYCODE_INSERT -> "Insert"+ KeyEvent.KEYCODE_F1 -> "F1"+ KeyEvent.KEYCODE_F2 -> "F2"+ KeyEvent.KEYCODE_F3 -> "F3"+ KeyEvent.KEYCODE_F4 -> "F4"+ KeyEvent.KEYCODE_F5 -> "F5"+ KeyEvent.KEYCODE_F6 -> "F6"+ KeyEvent.KEYCODE_F7 -> "F7"+ KeyEvent.KEYCODE_F8 -> "F8"+ KeyEvent.KEYCODE_F9 -> "F9"+ KeyEvent.KEYCODE_F10 -> "F10"+ KeyEvent.KEYCODE_F11 -> "F11"+ KeyEvent.KEYCODE_F12 -> "F12"else -> null}@@ -244,18 +490,21 @@ class TerminalInputView(context: Context, private val model: TerminalModel) : Vi// The IME cleared the composition (backspaced it away).if (composing != null) {composing = null+ model.composing = nullmodel.core.setComposing(false)}return true}if (composing == null) model.core.setComposing(true)composing = s+ model.composing = sreturn true}override fun finishComposingText(): Boolean {val s = composingcomposing = null+ model.composing = nullif (s != null) {model.core.setComposing(false)if (s.isNotEmpty()) model.text(s)@@ -283,6 +532,7 @@ class TerminalInputView(context: Context, private val model: TerminalModel) : Viprivate fun endComposing() {if (composing == null) returncomposing = null+ model.composing = nullmodel.core.setComposing(false)}}diff --git a/android/app/src/main/java/com/roversx/thinkterm/TreeSheet.kt b/android/app/src/main/java/com/roversx/thinkterm/TreeSheet.ktnew file mode 100644index 00000000..1a2bce99--- /dev/null+++ b/android/app/src/main/java/com/roversx/thinkterm/TreeSheet.kt@@ -0,0 +1,752 @@+@file:OptIn(ExperimentalFoundationApi::class, ExperimentalMaterial3Api::class)++package com.roversx.thinkterm++import androidx.compose.foundation.ExperimentalFoundationApi+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.combinedClickable+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.gestures.calculateZoom+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.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScroll+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight+import androidx.compose.material.icons.filled.Add+import androidx.compose.material.icons.filled.Check+import androidx.compose.material.icons.filled.KeyboardArrowDown+import androidx.compose.material.icons.filled.Layers+import androidx.compose.material.icons.filled.PushPin+import androidx.compose.material.icons.filled.Terminal+import androidx.compose.material.icons.filled.Window+import androidx.compose.material3.AlertDialog+import androidx.compose.material3.DropdownMenu+import androidx.compose.material3.DropdownMenuItem+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButton+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.ModalBottomSheet+import androidx.compose.material3.OutlinedTextField+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.material3.rememberModalBottomSheetState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateListOf+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.draw.clip+import androidx.compose.ui.draw.clipToBounds+import androidx.compose.ui.draw.rotate+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.input.pointer.PointerInputScope+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.boundsInRoot+import androidx.compose.ui.layout.onGloballyPositioned+import androidx.compose.ui.text.AnnotatedString+import androidx.compose.ui.text.SpanStyle+import androidx.compose.ui.text.buildAnnotatedString+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.text.withStyle+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import kotlinx.coroutines.delay++/// The desktop's sidebar and tab strip in one sheet, the way both are on+/// screen at once there: the Space, its threads by project, under an+/// opened thread its tabs, and under a tab with several panes, its panes.+/// Everything is named as the desktop names it: thread, tab, pane.+@Composable+fun TreeSheet(model: TerminalModel, onDismiss: () -> Unit) {+ val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)+ val open = remember { TreeOpen() }+ var spaceMenu by remember { mutableStateOf<List<MenuItem>>(emptyList()) }+ var spacesShown by remember { mutableStateOf(false) }+ var renaming by remember { mutableStateOf<Pair<String, String>?>(null) }+ var renameText by remember { mutableStateOf("") }+ val threads = model.threads?.threads ?: emptyList()+ val rows = model.sidebar?.rows ?: emptyList()+ val error = model.sidebar?.newProjectError+ val editing = model.sidebar?.editing++ LaunchedEffect(Unit) {+ model.refreshViews()+ spaceMenu = model.contextMenu("space", "")+ // The current thread starts open: its tabs are what the strip shows.+ model.threads?.current?.let { if (!open.threads.contains(it.id)) open.threads.add(it.id) }+ }+ LaunchedEffect(editing) {+ val id = editing?.id+ if (editing == null || editing.kind == "none" || id == null || renaming != null) return@LaunchedEffect+ renameText = ""+ renaming = editing.kind to id+ }++ ModalBottomSheet(+ onDismissRequest = onDismiss,+ sheetState = sheetState,+ modifier = Modifier.fillMaxSize(),+ ) {+ Row(+ Modifier.fillMaxWidth().padding(start = 8.dp, end = 4.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ TextButton(onClick = onDismiss) { Text(tr("done")) }+ Spacer(Modifier.width(8.dp))+ Text(tr("threads"), style = MaterialTheme.typography.titleMedium)+ Spacer(Modifier.weight(1f))+ Box {+ IconButton(onClick = {+ spaceMenu = model.contextMenu("space", "")+ spacesShown = true+ }) {+ Icon(Icons.Default.Layers, contentDescription = tr("workspaces"))+ }+ DropdownMenu(expanded = spacesShown, onDismissRequest = { spacesShown = false }) {+ for (item in spaceMenu) {+ if (item.kind != "item") continue+ DropdownMenuItem(+ text = { Text(item.label) },+ enabled = item.enabled,+ leadingIcon = if (item.checked) ({ Icon(Icons.Default.Check, contentDescription = null) }) else null,+ onClick = {+ model.menuAction(item.id)+ spaceMenu = model.contextMenu("space", "")+ spacesShown = false+ },+ )+ }+ }+ }+ IconButton(onClick = { model.chromeClick("new-tab") }) {+ Icon(Icons.Default.Add, contentDescription = tr("thread.new"))+ }+ }+ LazyColumn(Modifier.fillMaxWidth().weight(1f)) {+ items(rows) { row -> SideRowView(model, row, threads, open, onDismiss) }+ if (!error.isNullOrEmpty()) {+ item {+ Text(+ error,+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.error,+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),+ )+ }+ }+ }+ }++ if (renaming != null) {+ AlertDialog(+ onDismissRequest = {+ model.sideKey("Escape", "")+ renaming = null+ },+ title = { Text(tr("rename")) },+ text = {+ OutlinedTextField(+ value = renameText,+ onValueChange = { renameText = it },+ singleLine = true,+ label = { Text(tr("f.name")) },+ )+ },+ confirmButton = {+ TextButton(onClick = {+ model.sideKey("Enter", renameText)+ renaming = null+ }) { Text(tr("save")) }+ },+ dismissButton = {+ TextButton(onClick = {+ model.sideKey("Escape", "")+ renaming = null+ }) { Text(tr("cancel")) }+ },+ )+ }+}++/// Which threads and tabs are unfolded, for as long as the sheet is up.+private class TreeOpen {+ val threads = mutableStateListOf<String>()+ val tabs = mutableStateListOf<String>()++ fun toggleThread(id: String) { if (!threads.remove(id)) threads.add(id) }++ fun toggleTab(key: String) { if (!tabs.remove(key)) tabs.add(key) }+}++@Composable+private fun SideRowView(+ model: TerminalModel,+ row: SideRow,+ threads: List<ThreadView>,+ open: TreeOpen,+ onDismiss: () -> Unit,+) {+ val accent = MaterialTheme.colorScheme.primary+ val secondary = MaterialTheme.colorScheme.onSurfaceVariant+ when (row) {+ is SideRow.Space -> Text(+ row.name,+ style = MaterialTheme.typography.titleMedium,+ modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 10.dp, bottom = 4.dp),+ )+ is SideRow.NewThread -> Row(+ Modifier+ .fillMaxWidth()+ .clickable { model.sideClick("new-thread") }+ .padding(horizontal = 16.dp, vertical = 10.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ Icon(Icons.Default.Add, contentDescription = null, tint = accent, modifier = Modifier.size(18.dp))+ Text(tr("thread.new"), color = accent)+ }+ is SideRow.Pinned -> TreeCaption(tr("pinned"))+ is SideRow.Workspaces -> TreeCaption(tr("workspaces"))+ is SideRow.Others -> TreeCaption(tr("otherwindows"))+ is SideRow.Project -> ProjectRow(model, row)+ is SideRow.Thread -> {+ val thread = threads.firstOrNull { it.id == row.row.id }+ if (thread == null) {+ Text(row.row.name, modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp))+ } else {+ ThreadRows(model, thread, if (row.row.project.isEmpty()) 0.dp else 14.dp, open, onDismiss)+ }+ }+ is SideRow.Archived -> Row(+ Modifier+ .fillMaxWidth()+ .clickable { model.sideClick("toggle-archived", flag = !row.open) }+ .padding(horizontal = 16.dp, vertical = 8.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(6.dp),+ ) {+ Icon(+ Icons.AutoMirrored.Filled.KeyboardArrowRight,+ contentDescription = null,+ tint = secondary,+ modifier = Modifier.size(14.dp).rotate(if (row.open) 90f else 0f),+ )+ Text("${row.label} (${row.count})", style = MaterialTheme.typography.bodySmall, color = secondary)+ }+ is SideRow.Window -> Row(+ Modifier+ .fillMaxWidth()+ .background(if (row.selected) accent.copy(alpha = 0.2f) else Color.Transparent)+ .clickable { model.sideClick("window", row.id.toString()) }+ .padding(horizontal = 16.dp, vertical = 8.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ Icon(Icons.Default.Window, contentDescription = null, tint = secondary, modifier = Modifier.size(16.dp))+ Text(+ row.title.ifEmpty { tr("window.n", row.id) },+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ }+ }+}++@Composable+private fun TreeCaption(text: String) {+ Text(+ text.uppercase(),+ style = MaterialTheme.typography.labelSmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 12.dp, bottom = 2.dp),+ )+}++@Composable+private fun ProjectRow(model: TerminalModel, row: SideRow.Project) {+ val accent = MaterialTheme.colorScheme.primary+ val secondary = MaterialTheme.colorScheme.onSurfaceVariant+ var menu by remember { mutableStateOf(false) }+ Box {+ Row(+ Modifier+ .fillMaxWidth()+ .combinedClickable(+ onClick = { model.sideClick("toggle-project", row.id) },+ onLongClick = { menu = true },+ )+ .padding(start = 8.dp, end = 8.dp, top = 4.dp, bottom = 4.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ IconButton(onClick = { model.sideClick("toggle-project", row.id) }, modifier = Modifier.size(28.dp)) {+ Icon(+ Icons.AutoMirrored.Filled.KeyboardArrowRight,+ contentDescription = null,+ tint = secondary,+ modifier = Modifier.size(16.dp).rotate(if (row.collapsed) 0f else 90f),+ )+ }+ Column(Modifier.weight(1f).padding(start = 4.dp)) {+ Text(+ row.name,+ style = MaterialTheme.typography.titleSmall,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ Text(+ row.path,+ style = MaterialTheme.typography.labelSmall,+ color = secondary,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ }+ if (!row.archived) {+ IconButton(onClick = { model.sideClick("new-thread", row.id) }, modifier = Modifier.size(28.dp)) {+ Icon(Icons.Default.Add, contentDescription = null, tint = accent, modifier = Modifier.size(18.dp))+ }+ }+ }+ AppContextMenu(+ model = model,+ kind = if (row.archived) "archived-project" else "project",+ id = row.id,+ expanded = menu,+ onDismiss = { menu = false },+ )+ }+}++/// A thread, and when open, its tabs under it.+@Composable+private fun ThreadRows(+ model: TerminalModel,+ thread: ThreadView,+ indent: Dp,+ open: TreeOpen,+ onDismiss: () -> Unit,+) {+ val accent = MaterialTheme.colorScheme.primary+ val secondary = MaterialTheme.colorScheme.onSurfaceVariant+ val opened = open.threads.contains(thread.id)+ var menu by remember { mutableStateOf(false) }+ Column {+ Box {+ Row(+ Modifier+ .fillMaxWidth()+ .background(if (thread.current) accent.copy(alpha = 0.18f) else Color.Transparent)+ .combinedClickable(+ onClick = {+ model.sideClick("thread", thread.id)+ onDismiss()+ },+ onLongClick = { menu = true },+ )+ .padding(start = 16.dp + indent, end = 8.dp, top = 6.dp, bottom = 6.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ Box(Modifier.size(8.dp).background(threadColor(thread.status, thread.live), CircleShape))+ Text(+ thread.name,+ fontWeight = if (thread.unread) FontWeight.SemiBold else FontWeight.Normal,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.weight(1f),+ )+ if (thread.pinned) {+ Icon(Icons.Default.PushPin, contentDescription = null, tint = secondary, modifier = Modifier.size(14.dp))+ }+ Text(+ if (thread.live) tr(if (thread.tabs.size == 1) "tab.one" else "tab.n", thread.tabs.size) else tr("thread.off"),+ style = MaterialTheme.typography.labelSmall,+ color = secondary,+ )+ if (thread.tabs.isNotEmpty()) {+ IconButton(onClick = { open.toggleThread(thread.id) }, modifier = Modifier.size(28.dp)) {+ Icon(+ Icons.Default.KeyboardArrowDown,+ contentDescription = null,+ tint = secondary,+ modifier = Modifier.size(18.dp).rotate(if (opened) 0f else -90f),+ )+ }+ }+ }+ AppContextMenu(model = model, kind = "thread", id = thread.id, expanded = menu, onDismiss = { menu = false })+ }+ if (opened) {+ for (tab in thread.tabs) TabRows(model, thread, tab, indent + 20.dp, open, onDismiss)+ }+ }+}++/// A tab, and when open, its panes.+@Composable+private fun TabRows(+ model: TerminalModel,+ thread: ThreadView,+ tab: ThreadTab,+ indent: Dp,+ open: TreeOpen,+ onDismiss: () -> Unit,+) {+ val accent = MaterialTheme.colorScheme.primary+ val secondary = MaterialTheme.colorScheme.onSurfaceVariant+ val key = thread.id + ":" + tab.tab+ val opened = open.tabs.contains(key)+ val current = thread.current && tab.current+ var menu by remember { mutableStateOf(false) }+ Box {+ Row(+ Modifier+ .fillMaxWidth()+ .combinedClickable(+ onClick = {+ model.chromeClick("pane", pane = tab.target)+ onDismiss()+ },+ onLongClick = { menu = true },+ )+ .padding(start = 16.dp + indent, end = 8.dp, top = 5.dp, bottom = 5.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ Icon(+ Icons.Default.Terminal,+ contentDescription = null,+ tint = if (current) accent else secondary,+ modifier = Modifier.size(16.dp),+ )+ Row(+ Modifier.weight(1f),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(6.dp),+ ) {+ Text(+ tab.title.ifEmpty { tr("tab.num", tab.tab) },+ style = MaterialTheme.typography.bodyMedium,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ val first = tab.panes.firstOrNull()+ if (first != null && first.title.isNotEmpty() && first.title != tab.title) {+ Text(+ first.title,+ style = MaterialTheme.typography.labelSmall,+ color = secondary,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ }+ }+ if (current) {+ Icon(Icons.Default.Check, contentDescription = null, tint = accent, modifier = Modifier.size(16.dp))+ }+ if (tab.panes.size > 1) {+ Text(tr("panes.n", tab.panes.size), style = MaterialTheme.typography.labelSmall, color = secondary)+ IconButton(onClick = { open.toggleTab(key) }, modifier = Modifier.size(28.dp)) {+ Icon(+ Icons.Default.KeyboardArrowDown,+ contentDescription = null,+ tint = secondary,+ modifier = Modifier.size(18.dp).rotate(if (opened) 0f else -90f),+ )+ }+ }+ }+ AppContextMenu(model = model, kind = "tab", id = tab.tab.toString(), expanded = menu, onDismiss = { menu = false })+ }+ if (opened) {+ val focused = model.tabs?.current?.panes?.firstOrNull { it.current }?.pane+ for (pane in tab.panes) {+ Row(+ Modifier+ .fillMaxWidth()+ .clickable {+ model.chromeClick("pane", pane = pane.pane)+ onDismiss()+ }+ .padding(start = 16.dp + indent + 22.dp, end = 16.dp, top = 5.dp, bottom = 5.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ Box(Modifier.size(6.dp).background(secondary, RoundedCornerShape(1.dp)))+ Text(+ pane.title.ifEmpty { "shell" },+ style = MaterialTheme.typography.bodyMedium,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.weight(1f),+ )+ if (thread.current && focused == pane.pane) {+ Icon(Icons.Default.Check, contentDescription = null, tint = accent, modifier = Modifier.size(16.dp))+ }+ }+ }+ }+}++private const val OVERVIEW_DOTS = 4+private const val OVERVIEW_ROWS = 9+private const val OVERVIEW_COLS = 38++/// The desktop's Live Overview as a layer under the terminal: a card per+/// thread, grouped by project, two to a row. The thread on show leaves+/// its thumbnail empty and reports the box, for the screen above to zoom+/// the live terminal into it.+@Composable+fun OverviewScreen(+ model: TerminalModel,+ liveThread: String?,+ onCardBounds: (Rect?) -> Unit,+ onDismiss: () -> Unit,+) {+ val threads = model.threads?.threads ?: emptyList()+ val groups = threads.groupBy { it.project }.toList()++ DisposableEffect(Unit) { onDispose { onCardBounds(null) } }+ // Every live thread's current tab, asked for its last rows.+ LaunchedEffect(Unit) {+ model.refreshViews()+ while (true) {+ for (thread in model.threads?.threads ?: emptyList()) {+ if (!thread.live || thread.id == liveThread) continue+ previewPane(thread)?.let { model.requestPreview(it, OVERVIEW_ROWS) }+ }+ delay(2000)+ }+ }++ Box(+ Modifier+ .fillMaxSize()+ .background(Color(0xFF0F0F0F))+ // Pinching out returns to the terminal.+ .pointerInput(Unit) { awaitPinchOut { onDismiss() } }+ ) {+ Column(+ Modifier+ .fillMaxSize()+ .verticalScroll(rememberScrollState())+ .padding(horizontal = 12.dp, vertical = 8.dp)+ ) {+ if (threads.isEmpty()) {+ Box(Modifier.fillMaxWidth().padding(top = 60.dp), contentAlignment = Alignment.TopCenter) {+ Text(tr("overview.none"), color = overviewSecondary)+ }+ } else {+ for ((project, group) in groups) {+ GroupHeader(model.threads?.space ?: "", project, group.size)+ for (pair in group.chunked(2)) {+ Row(+ Modifier.fillMaxWidth().padding(bottom = 10.dp),+ horizontalArrangement = Arrangement.spacedBy(10.dp),+ ) {+ for (thread in pair) {+ ThreadCard(+ model = model,+ thread = thread,+ live = thread.id == liveThread,+ onCardBounds = onCardBounds,+ onDismiss = onDismiss,+ modifier = Modifier.weight(1f),+ )+ }+ if (pair.size == 1) Spacer(Modifier.weight(1f))+ }+ }+ }+ }+ }+ }+}++private val overviewSecondary = Color.White.copy(alpha = 0.55f)++@Composable+private fun GroupHeader(space: String, project: String, count: Int) {+ Row(+ Modifier.fillMaxWidth().padding(top = 10.dp, bottom = 8.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(6.dp),+ ) {+ Text(space, fontSize = 12.sp, color = Color.White, maxLines = 1, overflow = TextOverflow.Ellipsis)+ Text("·", fontSize = 12.sp, color = overviewSecondary)+ Text(project, fontSize = 12.sp, color = Color.White, maxLines = 1, overflow = TextOverflow.Ellipsis)+ Box(Modifier.weight(1f).height(1.dp).background(Color.White.copy(alpha = 0.08f)))+ Text("$count", fontSize = 12.sp, color = overviewSecondary)+ }+}++@Composable+private fun ThreadCard(+ model: TerminalModel,+ thread: ThreadView,+ live: Boolean,+ onCardBounds: (Rect?) -> Unit,+ onDismiss: () -> Unit,+ modifier: Modifier = Modifier,+) {+ val accent = MaterialTheme.colorScheme.primary+ val shown = thread.tabs.take(OVERVIEW_DOTS)+ val folded = thread.tabs.size - shown.size+ val currentTab = thread.tabs.firstOrNull { it.current } ?: thread.tabs.firstOrNull()+ val shape = RoundedCornerShape(13.dp)+ Column(+ modifier+ .clip(shape)+ .background(Color(0xFF1A1C21))+ .border(if (live) 2.dp else 1.dp, if (live) accent else Color.White.copy(alpha = 0.07f), shape)+ .clickable {+ if (!live) model.sideClick("thread", thread.id)+ onDismiss()+ }+ ) {+ Row(+ Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, top = 10.dp, bottom = 6.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(7.dp),+ ) {+ Box(Modifier.size(7.dp).background(threadColor(thread.status, thread.live), CircleShape))+ Text(+ thread.name,+ fontSize = 13.5.sp,+ fontWeight = FontWeight.SemiBold,+ color = Color.White,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ }+ Row(+ Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, bottom = 7.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(4.dp),+ ) {+ for (tab in shown) {+ Box(+ Modifier+ .size(6.dp)+ .background(+ if (thread.current && tab.current) accent else Color.White.copy(alpha = 0.28f),+ CircleShape,+ )+ )+ }+ if (folded > 0) Text("+$folded", fontSize = 9.5.sp, color = overviewSecondary)+ Text(+ currentTab?.title ?: "",+ fontSize = 10.sp,+ fontFamily = FontFamily.Monospace,+ color = overviewSecondary,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.weight(1f).padding(start = 3.dp),+ )+ if (!thread.live) {+ Text(+ tr("offline"),+ fontSize = 9.sp,+ fontWeight = FontWeight.SemiBold,+ color = overviewSecondary,+ modifier = Modifier+ .background(Color.Gray.copy(alpha = 0.22f), CircleShape)+ .padding(horizontal = 6.dp, vertical = 2.dp),+ )+ }+ }+ Box(+ Modifier+ .fillMaxWidth()+ .height(92.dp)+ .background(if (thread.live) model.background else Color.Black.copy(alpha = 0.4f))+ .clipToBounds()+ ) {+ if (live) {+ // The terminal itself lands here; the box reports where.+ Box(Modifier.fillMaxSize().onGloballyPositioned { onCardBounds(it.boundsInRoot()) })+ } else {+ Text(+ previewText(model, thread),+ fontSize = 7.sp,+ lineHeight = 8.5.sp,+ fontFamily = FontFamily.Monospace,+ color = Color.White,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 7.dp),+ )+ }+ }+ }+}++private fun previewPane(thread: ThreadView): Int? =+ (thread.tabs.firstOrNull { it.current } ?: thread.tabs.firstOrNull())?.target++/// The rows fetched for the thread's pane in their colours, trailing+/// blank rows dropped, each cut at about a half-width card's worth.+private fun previewText(model: TerminalModel, thread: ThreadView): AnnotatedString {+ val pane = previewPane(thread) ?: return AnnotatedString("")+ val fetched = model.previews[pane] ?: return AnnotatedString("")+ val kept = fetched.dropLastWhile { it.runs.isEmpty() }.takeLast(OVERVIEW_ROWS)+ return buildAnnotatedString {+ for ((i, row) in kept.withIndex()) {+ var used = 0+ for (run in row.runs) {+ val room = OVERVIEW_COLS - used+ if (room <= 0) break+ val piece = run.text.take(room)+ withStyle(SpanStyle(color = parseHex(run.fg) ?: Color.White)) { append(piece) }+ used += piece.length+ }+ if (i < kept.size - 1) append("\n")+ }+ }+}++/// Two fingers spreading, the zoom multiplied over the gesture. One+/// finger is left alone, so the list under it still scrolls.+private suspend fun PointerInputScope.awaitPinchOut(onPinchOut: () -> Unit) {+ awaitEachGesture {+ awaitFirstDown(requireUnconsumed = false)+ var zoom = 1f+ var fired = false+ do {+ val event = awaitPointerEvent()+ if (event.changes.size >= 2) {+ zoom *= event.calculateZoom()+ if (!fired && zoom > 1.25f) {+ fired = true+ onPinchOut()+ }+ }+ } while (event.changes.any { it.pressed })+ }+}diff --git a/android/app/src/main/java/com/roversx/thinkterm/Views.kt b/android/app/src/main/java/com/roversx/thinkterm/Views.ktindex d3bbe453..8ba77c97 100644--- a/android/app/src/main/java/com/roversx/thinkterm/Views.kt+++ b/android/app/src/main/java/com/roversx/thinkterm/Views.kt@@ -4,52 +4,367 @@ import android.util.Logimport org.json.JSONArrayimport 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.+// The App's views, as its JSON names them (thinkterm-web/src/views.rs,+// chrome.rs, navbar.rs and app.rs are the reference; ios/Sources/Views.swift+// is the same set in Swift). org.json is in the platform, so no codegen.++data class PaneView(val pane: Int, val title: String, val current: Boolean)data class TabEntry(val tab: Int,+ val window: Int,+ val title: String,val label: String,+ val target: Int,+ val current: Boolean,+ val panes: List<PaneView>,+)++data class Controls(val following: Boolean, val fit: Boolean, val closing: Int?)++data class TabsView(val tabs: List<TabEntry>, val controls: Controls) {+ val current: TabEntry? get() = tabs.firstOrNull { it.current }+}++data class NavRect(val pane: Int, val left: Double, val top: Double, val width: Double, val height: Double)++data class CapsuleView(val pane: Int, val title: String, val busy: Boolean, val current: Boolean)++data class NavView(+ val rect: NavRect,+ val members: List<CapsuleView>,+ val focused: Boolean,+ val zoomed: Boolean,+ val closing: Boolean,+)++/// The desktop's sidebar layer with its tabs: `App::threads_view`.+data class ThreadsView(val space: String, val threads: List<ThreadView>) {+ val current: ThreadView? get() = threads.firstOrNull { it.current }+}++data class ThreadView(+ val id: String,+ val name: String,+ val project: String,+ val projectId: String,+ val status: String,+ val dot: String,+ val live: Boolean,+ val pinned: Boolean,+ val unread: Boolean,+ val current: Boolean,+ val window: Int?,+ val tabs: List<ThreadTab>,+)++data class ThreadTab(+ val tab: Int,val title: String,val target: Int,val current: Boolean,+ val panes: List<PaneRef>,)-data class TabsView(val tabs: List<TabEntry>)+data class PaneRef(val pane: Int, val title: String)++/// A thumbnail row: `App::PreviewRow`.+data class PreviewRow(val runs: List<PreviewRun>)++data class PreviewRun(val text: String, val fg: String)++data class Toast(val text: String, val sticky: Boolean, val at: Double)++data class Card(val title: String, val hint: String, val state: String, val action: String)++data class StatusView(val toast: Toast?, val card: Card?, val summary: String)++/// One row of the sidebar, tagged by `kind` in the JSON.+sealed class SideRow {+ abstract val key: String++ data class Space(val id: String, val name: String) : SideRow() {+ override val key get() = "space:$id"+ }++ object NewThread : SideRow() {+ override val key get() = "new-thread"+ }++ object Pinned : SideRow() {+ override val key get() = "pinned"+ }++ object Workspaces : SideRow() {+ override val key get() = "workspaces"+ }++ data class Project(val id: String, val name: String, val path: String, val collapsed: Boolean, val archived: Boolean) : SideRow() {+ override val key get() = "project:$id"+ }++ data class Thread(val row: ThreadRow) : SideRow() {+ override val key get() = "thread:${row.id}"+ }++ data class Archived(val count: Int, val open: Boolean, val label: String) : SideRow() {+ override val key get() = "archived"+ }++ object Others : SideRow() {+ override val key get() = "others"+ }++ data class Window(val id: Int, val title: String, val selected: Boolean) : SideRow() {+ override val key get() = "window:$id"+ }+}++data class ThreadRow(+ val id: String,+ val project: String,+ val name: String,+ val status: String,+ val dot: String,+ val pinned: Boolean,+ val unread: Boolean,+ val live: Boolean,+ val selected: Boolean,+ val deleting: Boolean,+)++data class Editing(val kind: String, val id: String?)++data class SidebarView(+ val rows: List<SideRow>,+ val editing: Editing,+ val space: String?,+ val newProjectError: String?,+)++data class MenuItem(+ val id: String,+ val label: String,+ val icon: String?,+ val kind: String,+ val enabled: Boolean,+ val checked: Boolean,+ val submenu: List<MenuItem>,+) {+ /// Separators and headers share an empty id; rows need a stable one.+ val rowId: String get() = if (id.isEmpty()) "$kind:$label" else id+}++data class MenuOutcome(val handled: Boolean, val copy: String?, val paste: Boolean)-data class StatusView(- val summary: String,- val toast: String?,- val sticky: Boolean,+/// The focused pane's text, for a selection: `App::screen_text`.+data class ScreenText(+ val cols: Int,+ val rows: Int,+ val text: String,+ val originX: Double,+ val originY: Double,+ val cellW: Double,+ val cellH: Double,+ /// (row, col) of both ends, ordered, inclusive; null for none.+ val selection: Pair<Pair<Int, Int>, Pair<Int, Int>>?,+)++/// What the layout view carries that the shell reads.+data class LayoutView(+ val cellW: Double,+ val cellH: Double,+ val fontPt: Double,+ /// Rows above the bottom, and rows there are to scroll through.+ val scrollAbove: Int,+ val scrollMax: Int,+ val focused: Int,)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"),+ val tabs = root.optJSONArray("tabs").map { t ->+ TabEntry(+ tab = t.optInt("tab"),+ window = t.optInt("window"),+ title = t.optString("title"),+ label = t.optString("label"),+ target = t.optInt("target"),+ current = t.optBoolean("current"),+ panes = t.optJSONArray("panes").map { p ->+ PaneView(p.optInt("pane"), p.optString("title"), p.optBoolean("current"))+ },+ )+ }+ val c = root.optJSONObject("controls")+ val controls = Controls(+ following = c?.optBoolean("following") ?: false,+ fit = c?.optBoolean("fit") ?: false,+ closing = c?.takeIf { it.has("closing") && !it.isNull("closing") }?.optInt("closing"),+ )+ return TabsView(tabs, controls)+ }++ fun navs(json: String): List<NavView> {+ val arr = array(json) ?: return emptyList()+ return arr.map { n ->+ val r = n.optJSONObject("rect") ?: JSONObject()+ NavView(+ rect = NavRect(r.optInt("pane"), r.optDouble("left"), r.optDouble("top"), r.optDouble("width"), r.optDouble("height")),+ members = n.optJSONArray("members").map { m ->+ CapsuleView(m.optInt("pane"), m.optString("title"), m.optBoolean("busy"), m.optBoolean("current"))+ },+ focused = n.optBoolean("focused"),+ zoomed = n.optBoolean("zoomed"),+ closing = n.optBoolean("closing"),+ )+ }+ }++ fun threads(json: String): ThreadsView? {+ val root = obj(json) ?: return null+ return ThreadsView(+ space = root.optString("space"),+ threads = root.optJSONArray("threads").map { t ->+ ThreadView(+ id = t.optString("id"),+ name = t.optString("name"),+ project = t.optString("project"),+ projectId = t.optString("project_id"),+ status = t.optString("status"),+ dot = t.optString("dot"),+ live = t.optBoolean("live"),+ pinned = t.optBoolean("pinned"),+ unread = t.optBoolean("unread"),current = t.optBoolean("current"),+ window = t.takeIf { it.has("window") && !it.isNull("window") }?.optInt("window"),+ tabs = t.optJSONArray("tabs").map { tab ->+ ThreadTab(+ tab = tab.optInt("tab"),+ title = tab.optString("title"),+ target = tab.optInt("target"),+ current = tab.optBoolean("current"),+ panes = tab.optJSONArray("panes").map { p -> PaneRef(p.optInt("pane"), p.optString("title")) },+ )+ },)- )+ },+ )+ }++ fun previewRows(json: String): List<PreviewRow> {+ val arr = array(json) ?: return emptyList()+ return arr.map { row ->+ PreviewRow(row.optJSONArray("runs").map { run -> PreviewRun(run.optString("text"), run.optString("fg")) })}- 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,+ val toast = root.optJSONObject("toast")?.let {+ Toast(it.optString("text"), it.optBoolean("sticky"), it.optDouble("at"))+ }+ val card = root.optJSONObject("card")?.let {+ Card(it.optString("title"), it.optString("hint"), it.optString("state"), it.optString("action"))+ }+ return StatusView(toast, card, root.optString("summary"))+ }++ fun sidebar(json: String): SidebarView? {+ val root = obj(json) ?: return null+ val rows = root.optJSONArray("rows").mapNotNull { r ->+ when (r.optString("kind")) {+ "space" -> SideRow.Space(r.optString("id"), r.optString("name"))+ "new-thread" -> SideRow.NewThread+ "pinned" -> SideRow.Pinned+ "workspaces" -> SideRow.Workspaces+ "project" -> SideRow.Project(+ r.optString("id"), r.optString("name"), r.optString("path"),+ r.optBoolean("collapsed"), r.optBoolean("archived"),+ )+ "thread" -> SideRow.Thread(+ ThreadRow(+ id = r.optString("id"),+ project = r.optString("project"),+ name = r.optString("name"),+ status = r.optString("status"),+ dot = r.optString("dot"),+ pinned = r.optBoolean("pinned"),+ unread = r.optBoolean("unread"),+ live = r.optBoolean("live"),+ selected = r.optBoolean("selected"),+ deleting = r.optBoolean("deleting"),+ )+ )+ "archived" -> SideRow.Archived(r.optInt("count"), r.optBoolean("open"), r.optString("label"))+ "others" -> SideRow.Others+ "window" -> SideRow.Window(r.optInt("id"), r.optString("title"), r.optBoolean("selected"))+ else -> null+ }+ }+ val e = root.optJSONObject("editing")+ return SidebarView(+ rows = rows,+ editing = Editing(e?.optString("kind") ?: "none", e?.takeIf { it.has("id") && !it.isNull("id") }?.optString("id")),+ space = root.takeIf { it.has("space") && !it.isNull("space") }?.optString("space"),+ newProjectError = root.takeIf { it.has("new_project_error") && !it.isNull("new_project_error") }?.optString("new_project_error"),+ )+ }++ fun menu(json: String): List<MenuItem> = array(json)?.map { menuItem(it) } ?: emptyList()++ private fun menuItem(o: JSONObject): MenuItem = MenuItem(+ id = o.optString("id"),+ label = o.optString("label"),+ icon = o.takeIf { it.has("icon") && !it.isNull("icon") }?.optString("icon"),+ kind = o.optString("kind", "item"),+ enabled = o.optBoolean("enabled", true),+ checked = o.optBoolean("checked"),+ submenu = o.optJSONArray("submenu").map { menuItem(it) },+ )++ fun menuOutcome(json: String): MenuOutcome? {+ val root = obj(json) ?: return null+ return MenuOutcome(+ handled = root.optBoolean("handled"),+ copy = root.takeIf { it.has("copy") && !it.isNull("copy") }?.optString("copy"),+ paste = root.optBoolean("paste"),+ )+ }++ fun screenText(json: String): ScreenText? {+ val root = obj(json) ?: return null+ val origin = root.optJSONArray("origin")+ val cell = root.optJSONArray("cell")+ val sel = root.optJSONArray("selection")?.let { s ->+ val a = s.optJSONArray(0) ?: return@let null+ val b = s.optJSONArray(1) ?: return@let null+ Pair(Pair(a.optInt(0), a.optInt(1)), Pair(b.optInt(0), b.optInt(1)))+ }+ return ScreenText(+ cols = root.optInt("cols"),+ rows = root.optInt("rows"),+ text = root.optString("text"),+ originX = origin?.optDouble(0) ?: 0.0,+ originY = origin?.optDouble(1) ?: 0.0,+ cellW = cell?.optDouble(0) ?: 1.0,+ cellH = cell?.optDouble(1) ?: 1.0,+ selection = sel,+ )+ }++ fun layout(json: String): LayoutView? {+ val root = obj(json) ?: return null+ val cell = root.optJSONArray("cell")+ val scroll = root.optJSONArray("scroll")+ return LayoutView(+ cellW = cell?.optDouble(0) ?: 0.0,+ cellH = cell?.optDouble(1) ?: 0.0,+ fontPt = root.optDouble("font_pt"),+ scrollAbove = scroll?.optInt(0) ?: 0,+ scrollMax = scroll?.optInt(1) ?: 0,+ focused = root.optInt("focused"),)}@@ -62,4 +377,34 @@ object Views {null}}++ private fun array(json: String): JSONArray? {+ if (json.isEmpty() || json == "null") return null+ return try {+ JSONArray(json)+ } catch (e: Throwable) {+ Log.w("thinkterm", "view decode failed: ${json.take(200)}")+ null+ }+ }++ private inline fun <T> JSONArray?.map(f: (JSONObject) -> T): List<T> {+ if (this == null) return emptyList()+ val out = ArrayList<T>(length())+ for (i in 0 until length()) {+ val o = optJSONObject(i) ?: continue+ out.add(f(o))+ }+ return out+ }++ private inline fun <T> JSONArray?.mapNotNull(f: (JSONObject) -> T?): List<T> {+ if (this == null) return emptyList()+ val out = ArrayList<T>(length())+ for (i in 0 until length()) {+ val o = optJSONObject(i) ?: continue+ f(o)?.let { out.add(it) }+ }+ return out+ }}diff --git a/android/build.sh b/android/build.shindex 483aab63..c0390b28 100755--- a/android/build.sh+++ b/android/build.sh@@ -33,7 +33,7 @@ cargo run -q -p thinkterm-mobile --bin uniffi-bindgen -- generate \echo "== assets"mkdir -p android/app/src/main/assetscp 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/+cp thinkterm-web/www/schemes.json ios/Resources/strings.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