Skip to content

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

mobile: the first round of feedback from the iPhone

RoversX8cd61050f286
diff --git a/android/app/src/main/java/com/roversx/thinkterm/HostsScreen.kt b/android/app/src/main/java/com/roversx/thinkterm/HostsScreen.kt
index db3b554a..b9b9198f 100644
--- a/android/app/src/main/java/com/roversx/thinkterm/HostsScreen.kt
+++ b/android/app/src/main/java/com/roversx/thinkterm/HostsScreen.kt
@@ -24,6 +24,8 @@ 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.PowerSettingsNew
+import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.Delete
@@ -143,6 +145,8 @@ fun HostsScreen(store: HostStore, showProbe: Boolean, onOpen: (Host) -> Unit) {
items(section.hosts, key = { it.id }) { host ->
HostListRow(
host = host,
+ connected = Sessions.isConnected(host.id),
+ onDisconnect = { Sessions.close(host.id) },
onOpen = { onOpen(host) },
onEdit = { editing = host },
onDuplicate = { store.duplicate(host, tr("host.copysuffix")) },
@@ -160,7 +164,14 @@ fun HostsScreen(store: HostStore, showProbe: Boolean, onOpen: (Host) -> Unit) {
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) },
+ headlineContent = {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ if (Sessions.isConnected(Host.PROBE_ID)) {
+ Box(Modifier.size(8.dp).background(Color(0xFF4CAF50), CircleShape))
+ }
+ Text(tr("thismac"), fontWeight = FontWeight.SemiBold)
+ }
+ },
supportingContent = {
Text("probe sshd on ${Host.probe.hostname}:${Host.probe.port}")
},
@@ -176,7 +187,7 @@ fun HostsScreen(store: HostStore, showProbe: Boolean, onOpen: (Host) -> Unit) {
title = { Text(tr("host.delete.title")) },
text = { Text(tr("host.delete.body")) },
confirmButton = {
- TextButton(onClick = { store.remove(host); pendingDelete = null }) {
+ TextButton(onClick = { Sessions.close(host.id); store.remove(host); pendingDelete = null }) {
Text(tr("host.delete.confirm", host.display), color = MaterialTheme.colorScheme.error)
}
},
@@ -222,6 +233,8 @@ private fun HostGroupHeader(title: String) {
@Composable
private fun HostListRow(
host: Host,
+ connected: Boolean,
+ onDisconnect: () -> Unit,
onOpen: () -> Unit,
onEdit: () -> Unit,
onDuplicate: () -> Unit,
@@ -235,7 +248,13 @@ private fun HostListRow(
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)
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ if (connected) {
+ // Connected: the session is open behind the list.
+ Box(Modifier.size(8.dp).background(Color(0xFF4CAF50), CircleShape))
+ }
+ Text(host.title, maxLines = 1, overflow = TextOverflow.Ellipsis, fontWeight = FontWeight.SemiBold)
+ }
},
supportingContent = {
Column {
@@ -266,6 +285,13 @@ private fun HostListRow(
leadingIcon = { Icon(Icons.Filled.Bolt, contentDescription = null) },
onClick = { menu = false; onOpen() },
)
+ if (connected) {
+ DropdownMenuItem(
+ text = { Text(tr("disconnect")) },
+ leadingIcon = { Icon(Icons.Filled.PowerSettingsNew, contentDescription = null) },
+ onClick = { menu = false; onDisconnect() },
+ )
+ }
DropdownMenuItem(
text = { Text(tr("edit")) },
leadingIcon = { Icon(Icons.Filled.Edit, contentDescription = null) },
diff --git a/android/app/src/main/java/com/roversx/thinkterm/KeyBar.kt b/android/app/src/main/java/com/roversx/thinkterm/KeyBar.kt
index 345c2900..3017cdac 100644
--- a/android/app/src/main/java/com/roversx/thinkterm/KeyBar.kt
+++ b/android/app/src/main/java/com/roversx/thinkterm/KeyBar.kt
@@ -48,12 +48,11 @@ fun KeyBar(
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 panel joins the soft keyboard when the setting asks it to.
+ // The keyboard coming up takes the panel's place: the two never stack.
LaunchedEffect(keyboardUp) {
- if (model.settings.autoKeyPanel) panelOpen = keyboardUp
+ if (keyboardUp) model.panelOpen = false
}
Column(modifier.fillMaxWidth().background(model.background)) {
@@ -75,12 +74,15 @@ fun KeyBar(
}
}
}
- MoreButton(open = panelOpen) {
- panelOpen = !panelOpen
+ MoreButton(open = model.panelOpen) {
+ // Opening the panel puts the keyboard away: the panel is
+ // its stand-in, not a shelf on top of it.
+ if (!model.panelOpen) model.onHideKeyboard?.invoke()
+ model.panelOpen = !model.panelOpen
tap()
}
}
- if (panelOpen) {
+ if (model.panelOpen) {
KeyPanel(model, tab, { tab = it }, onOpenSettings)
}
}
diff --git a/android/app/src/main/java/com/roversx/thinkterm/MainActivity.kt b/android/app/src/main/java/com/roversx/thinkterm/MainActivity.kt
index 69dfe6ba..948794e7 100644
--- a/android/app/src/main/java/com/roversx/thinkterm/MainActivity.kt
+++ b/android/app/src/main/java/com/roversx/thinkterm/MainActivity.kt
@@ -53,6 +53,20 @@ class MainActivity : ComponentActivity() {
private fun Root(store: HostStore, debuggable: Boolean) {
// Reading the tag here relabels the tabs with the rest of the app.
AppLanguage.tag
+ // Leaving the app (Home, another app) with the setting off drops
+ // every connection; coming back redials them.
+ val lifecycle = androidx.compose.ui.platform.LocalLifecycleOwner.current.lifecycle
+ androidx.compose.runtime.DisposableEffect(lifecycle) {
+ val observer = androidx.lifecycle.LifecycleEventObserver { _, event ->
+ when (event) {
+ androidx.lifecycle.Lifecycle.Event.ON_STOP -> Sessions.enteredBackground()
+ androidx.lifecycle.Lifecycle.Event.ON_START -> Sessions.enteredForeground()
+ else -> {}
+ }
+ }
+ lifecycle.addObserver(observer)
+ onDispose { lifecycle.removeObserver(observer) }
+ }
var open by remember { mutableStateOf<Host?>(null) }
var tab by remember { mutableIntStateOf(0) }
diff --git a/android/app/src/main/java/com/roversx/thinkterm/Sessions.kt b/android/app/src/main/java/com/roversx/thinkterm/Sessions.kt
new file mode 100644
index 00000000..095126b3
--- /dev/null
+++ b/android/app/src/main/java/com/roversx/thinkterm/Sessions.kt
@@ -0,0 +1,29 @@
+package com.roversx.thinkterm
+
+import android.content.Context
+import androidx.compose.runtime.mutableStateMapOf
+
+/// The open connections, one per host, outliving the terminal screen:
+/// leaving the screen takes the picture away and nothing else, so a
+/// host list visited in between, or another host opened, finds them
+/// where they were. A host is closed from the list, or with the app.
+object Sessions {
+ private val models = mutableStateMapOf<String, TerminalModel>()
+
+ fun get(context: Context, store: HostStore, host: Host): TerminalModel =
+ models.getOrPut(host.id) { TerminalModel(context.applicationContext, store, host) }
+
+ fun existing(hostId: String): TerminalModel? = models[hostId]
+
+ fun isConnected(hostId: String): Boolean = models[hostId]?.isConnected == true
+
+ fun close(hostId: String) {
+ models.remove(hostId)?.shutdown()
+ }
+
+ val all: Collection<TerminalModel> get() = models.values
+
+ /// The app left the screen or came back: every connection hears.
+ fun enteredBackground() = all.forEach { it.enteredBackground() }
+ fun enteredForeground() = all.forEach { it.enteredForeground() }
+}
diff --git a/android/app/src/main/java/com/roversx/thinkterm/SettingsScreen.kt b/android/app/src/main/java/com/roversx/thinkterm/SettingsScreen.kt
index 0009d2c1..7b5ac618 100644
--- a/android/app/src/main/java/com/roversx/thinkterm/SettingsScreen.kt
+++ b/android/app/src/main/java/com/roversx/thinkterm/SettingsScreen.kt
@@ -142,7 +142,6 @@ private fun SettingsList(
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 }
diff --git a/android/app/src/main/java/com/roversx/thinkterm/Sidebar.kt b/android/app/src/main/java/com/roversx/thinkterm/Sidebar.kt
index ab7ebb82..1c15b5dd 100644
--- a/android/app/src/main/java/com/roversx/thinkterm/Sidebar.kt
+++ b/android/app/src/main/java/com/roversx/thinkterm/Sidebar.kt
@@ -27,6 +27,7 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.MoreHoriz
+import androidx.compose.material.icons.filled.GridView
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.Window
@@ -66,6 +67,7 @@ fun SidebarDrawer(
onDismiss: () -> Unit,
onEditHost: () -> Unit,
onSettings: () -> Unit,
+ onOverview: () -> Unit,
) {
BackHandler(enabled = visible) { onDismiss() }
Box(Modifier.fillMaxSize()) {
@@ -76,7 +78,7 @@ fun SidebarDrawer(
// A Surface, not a Box: it sets the content colour, so text with
// no colour of its own is readable on every theme.
Surface(Modifier.fillMaxHeight().width(300.dp), color = MaterialTheme.colorScheme.surface) {
- SidebarTree(model, onDismiss, onEditHost, onSettings)
+ SidebarTree(model, onDismiss, onEditHost, onSettings, onOverview)
}
}
}
@@ -94,7 +96,7 @@ private class Folded(model: TerminalModel) {
@OptIn(ExperimentalFoundationApi::class)
@Composable
-private fun SidebarTree(model: TerminalModel, onDismiss: () -> Unit, onEditHost: () -> Unit, onSettings: () -> Unit) {
+private fun SidebarTree(model: TerminalModel, onDismiss: () -> Unit, onEditHost: () -> Unit, onSettings: () -> Unit, onOverview: () -> Unit) {
val folded = remember(model) { Folded(model) }
var connectionMenu by remember { mutableStateOf(false) }
/// The Space whose menu is up, if any: one flag for all of them
@@ -292,6 +294,15 @@ private fun SidebarTree(model: TerminalModel, onDismiss: () -> Unit, onEditHost:
}
}
HorizontalDivider()
+ // The desktop's footer actions: the overview, then settings.
+ Row(
+ Modifier.fillMaxWidth().clickable { onDismiss(); onOverview() }.padding(horizontal = 16.dp, vertical = 12.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ ) {
+ Icon(Icons.Default.GridView, contentDescription = null, tint = secondary, modifier = Modifier.size(18.dp))
+ Text(tr("overview"), color = secondary)
+ }
Row(
Modifier.fillMaxWidth().clickable { onDismiss(); onSettings() }.padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
diff --git a/android/app/src/main/java/com/roversx/thinkterm/TerminalModel.kt b/android/app/src/main/java/com/roversx/thinkterm/TerminalModel.kt
index 63d67ed4..db279709 100644
--- a/android/app/src/main/java/com/roversx/thinkterm/TerminalModel.kt
+++ b/android/app/src/main/java/com/roversx/thinkterm/TerminalModel.kt
@@ -86,7 +86,7 @@ class TerminalModel(
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)
+ var scrollAbove by mutableStateOf(0.0)
private set
var scrollMax by mutableStateOf(0)
private set
@@ -119,6 +119,12 @@ class TerminalModel(
/// The keyboard's options changed: the view starts its input over so
/// the IME reads them again.
var onImeOptionsChanged: (() -> Unit)? = null
+ /// The key panel is up in the keyboard's place.
+ var panelOpen by mutableStateOf(false)
+ /// A thread this phone was on last time it was in this host, put
+ /// back once the threads are listed after a connect.
+ private var restoredThread = false
+ private val lastThreads = context.getSharedPreferences("thinkterm.threads", Context.MODE_PRIVATE)
private var appliedIncognito = settings.incognitoKeyboard
var onScreenChanged: (() -> Unit)? = null
var onHideKeyboard: (() -> Unit)? = null
@@ -197,7 +203,41 @@ class TerminalModel(
}
/// Connect to the model's host with the secret from the store.
+ /// The thread on show is written down for the next connect; the first
+ /// listing after a connect puts the phone back on the one it left.
+ private fun rememberThread(threads: ThreadsView?) {
+ val list = threads?.threads ?: return
+ val current = list.firstOrNull { it.current }?.id ?: return
+ val key = "last." + host.id
+ if (!restoredThread) {
+ restoredThread = true
+ val saved = lastThreads.getString(key, null)
+ if (saved != null && saved != current && list.any { it.id == saved }) {
+ openThread(saved, null)
+ return
+ }
+ }
+ if (lastThreads.getString(key, null) != current) lastThreads.edit().putString(key, current).apply()
+ }
+
+ /// The screen went away but the connection stays: the frame loop
+ /// rests until the screen is back, and the views catch up then.
+ fun leaveScreen() {
+ running = false
+ choreographer.removeFrameCallback(tick)
+ main.removeCallbacks(statsTick)
+ }
+
+ fun enterScreen() {
+ if (running) return
+ running = true
+ choreographer.postFrameCallback(tick)
+ main.postDelayed(statsTick, 500)
+ changePending.set(true)
+ }
+
fun connect() {
+ restoredThread = false
connected = true
val h = host
val secret = if (h.id == Host.PROBE_ID) probeKey() else store.secret(h.id)
@@ -375,6 +415,7 @@ class TerminalModel(
if (sidebar != this.sidebar) this.sidebar = sidebar
val threads = Views.threads(core.view("threads"))
if (threads != this.threads) this.threads = threads
+ rememberThread(threads)
val tree = Views.tree(core.view("tree"))
if (tree != this.tree) this.tree = tree
val navs = Views.navs(core.view("navs"))
diff --git a/android/app/src/main/java/com/roversx/thinkterm/TerminalScreen.kt b/android/app/src/main/java/com/roversx/thinkterm/TerminalScreen.kt
index fbc0d5c5..475bf991 100644
--- a/android/app/src/main/java/com/roversx/thinkterm/TerminalScreen.kt
+++ b/android/app/src/main/java/com/roversx/thinkterm/TerminalScreen.kt
@@ -87,7 +87,6 @@ import androidx.compose.ui.layout.positionInParent
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
-import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
@@ -96,8 +95,6 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import 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
@@ -111,7 +108,9 @@ import kotlin.math.min
@Composable
fun TerminalScreen(host: Host, store: HostStore, onBack: () -> Unit) {
val context = LocalContext.current
- val model = remember(host.id) { TerminalModel(context, store, host) }
+ // The connection is the host's, not the screen's: it lives in
+ // `Sessions` and is picked up again on the way back.
+ val model = remember(host.id) { Sessions.get(context, store, host) }
val settings = model.settings
val density = LocalDensity.current
val scope = rememberCoroutineScope()
@@ -148,8 +147,13 @@ fun TerminalScreen(host: Host, store: HostStore, onBack: () -> Unit) {
// 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() } }
+ LaunchedEffect(model) {
+ model.enterScreen()
+ if (!model.isConnected) model.connect()
+ }
+ // Leaving takes the picture, not the connection: the frame loop
+ // rests, the surface goes with the view, the socket stays.
+ DisposableEffect(model) { onDispose { model.leaveScreen() } }
// The open terminal follows the preferences as they change.
LaunchedEffect(model) {
@@ -163,20 +167,6 @@ fun TerminalScreen(host: Host, store: HostStore, onBack: () -> Unit) {
}
LaunchedEffect(showLog.value, settings.devMode) { model.wantsStats = showLog.value || settings.devMode }
- // 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) }
- }
/// Back to the terminal. A tapped card hands over its thread and its
/// frames: the terminal grows out of that card, not the one it came
@@ -272,9 +262,9 @@ fun TerminalScreen(host: Host, store: HostStore, onBack: () -> Unit) {
TopBar(
model = model,
twoLevel = twoLevel,
- onBack = { model.disconnect(); onBack() },
- onTree = { showTree = true },
- onOverview = { if (overviewShown) closeOverview() else openOverview() },
+ onBack = onBack,
+ // The keyboard goes first, or the panel sits on it.
+ onTree = { model.onHideKeyboard?.invoke(); showTree = true },
)
// The tab strip fades with the zoom and stops taking touches;
// its room stays, so the terminal's own place does not move
@@ -346,7 +336,7 @@ fun TerminalScreen(host: Host, store: HostStore, onBack: () -> Unit) {
if (!overviewOpen) {
StatusLine(model)
- if (keyboardUp) {
+ if (keyboardUp || model.panelOpen) {
KeyBar(model = model, keyboardUp = keyboardUp, onOpenSettings = { showSettings = true })
}
}
@@ -426,6 +416,7 @@ fun TerminalScreen(host: Host, store: HostStore, onBack: () -> Unit) {
onDismiss = { showTree = false },
onEditHost = { showTree = false; editingHost = model.host },
onSettings = { showSettings = true },
+ onOverview = { if (overviewShown) closeOverview() else openOverview() },
)
}
if (showSettings) {
@@ -465,7 +456,6 @@ private fun TopBar(
twoLevel: Boolean,
onBack: () -> Unit,
onTree: () -> Unit,
- onOverview: () -> Unit,
) {
Row(
Modifier.fillMaxWidth().height(48.dp).padding(start = 2.dp, end = 2.dp),
@@ -499,9 +489,6 @@ private fun TopBar(
NewTabButton(model)
}
}
- IconButton(onClick = onOverview) {
- Icon(Icons.Default.GridView, contentDescription = tr("overview"), tint = Color.White)
- }
}
}
diff --git a/android/app/src/main/java/com/roversx/thinkterm/Views.kt b/android/app/src/main/java/com/roversx/thinkterm/Views.kt
index 19464654..e554f9ca 100644
--- a/android/app/src/main/java/com/roversx/thinkterm/Views.kt
+++ b/android/app/src/main/java/com/roversx/thinkterm/Views.kt
@@ -182,8 +182,9 @@ 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,
+ /// Rows above the bottom (with the fraction a smooth scroll is part
+ /// way through), and rows there are to scroll through.
+ val scrollAbove: Double,
val scrollMax: Int,
val focused: Int,
)
@@ -403,7 +404,7 @@ object Views {
cellW = cell?.optDouble(0) ?: 0.0,
cellH = cell?.optDouble(1) ?: 0.0,
fontPt = root.optDouble("font_pt"),
- scrollAbove = scroll?.optInt(0) ?: 0,
+ scrollAbove = scroll?.optDouble(0) ?: 0.0,
scrollMax = scroll?.optInt(1) ?: 0,
focused = root.optInt("focused"),
)
diff --git a/ios/Sources/HostsView.swift b/ios/Sources/HostsView.swift
index 8e95a36c..85dc67c8 100644
--- a/ios/Sources/HostsView.swift
+++ b/ios/Sources/HostsView.swift
@@ -4,6 +4,7 @@ import SwiftUI
/// its own so the automated flows and a quick check need no setup.
struct HostsView: View {
@EnvironmentObject var store: HostStore
+ @EnvironmentObject var sessions: Sessions
@ObservedObject private var lang = AppLanguage.shared
@State private var editing: Host?
@State private var adding = false
@@ -67,15 +68,15 @@ struct HostsView: View {
.searchable(text: $search, placement: .navigationBarDrawer, prompt: tr("hosts.search"))
.navigationDestination(for: Host.self) { host in
if host.name == "probe" {
- TerminalScreen(host: nil, store: store)
+ TerminalScreen(model: sessions.model(for: nil, store: store))
} else {
- TerminalScreen(host: host, store: store)
+ TerminalScreen(model: sessions.model(for: host, store: store))
}
}
// A separate destination type so the context menu's Connect can push
// without fighting the value-based destination above.
.navigationDestination(item: $connecting) { target in
- TerminalScreen(host: target.host, store: store)
+ TerminalScreen(model: sessions.model(for: target.host, store: store))
}
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
@@ -105,7 +106,7 @@ struct HostsView: View {
titleVisibility: .visible,
presenting: pendingDelete
) { host in
- Button(tr("host.delete.confirm", host.display), role: .destructive) { store.remove(host) }
+ Button(tr("host.delete.confirm", host.display), role: .destructive) { sessions.close(host.id); store.remove(host) }
Button(tr("cancel"), role: .cancel) {}
} message: { _ in
Text(tr("host.delete.body"))
@@ -115,7 +116,7 @@ struct HostsView: View {
@ViewBuilder
private func row(_ host: Host) -> some View {
NavigationLink(value: host) {
- HostRow(host: host)
+ HostRow(host: host, session: sessions.existing(host.id))
}
.swipeActions(edge: .trailing) {
Button(role: .destructive) { pendingDelete = host } label: { Label(tr("delete"), systemImage: "trash") }
@@ -124,6 +125,9 @@ struct HostsView: View {
}
.contextMenu {
Button { connecting = ConnectTarget(host: host) } label: { Label(tr("connect"), systemImage: "bolt.horizontal") }
+ if let session = sessions.existing(host.id), session.isConnected {
+ Button { sessions.close(host.id) } label: { Label(tr("disconnect"), systemImage: "power") }
+ }
Button { editing = host } label: { Label(tr("edit"), systemImage: "pencil") }
Button { duplicate(host) } label: { Label(tr("duplicate"), systemImage: "plus.square.on.square") }
if host.knownHost != nil {
@@ -191,6 +195,8 @@ private struct ConnectTarget: Hashable {
struct HostRow: View {
let host: Host
+ /// The host's open session, if any: a dot says so.
+ var session: TerminalModel? = nil
@ObservedObject private var lang = AppLanguage.shared
var body: some View {
@@ -201,6 +207,7 @@ struct HostRow: View {
subtitle: host.address
) {
HStack(spacing: 6) {
+ if let session { ConnectionDot(model: session) }
Text(host.lastConnectedText)
.font(.caption)
.foregroundStyle(.tertiary)
diff --git a/ios/Sources/KeyBar.swift b/ios/Sources/KeyBar.swift
index ea8bc324..cce94953 100644
--- a/ios/Sources/KeyBar.swift
+++ b/ios/Sources/KeyBar.swift
@@ -8,9 +8,6 @@ import UIKit
/// sent, and the colours, as the prototype's `.keybar` + `.kpanel`.
struct KeyBar: View {
@ObservedObject var model: TerminalModel
- /// `--keypanel` on the command line starts with the panel open: the
- /// simulator cannot be tapped, and a screenshot needs it showing.
- @State private var panelOpen = ProcessInfo.processInfo.arguments.contains("--keypanel")
@State private var tab: KeyPanelTab = KeyBar.debugTab
@ObservedObject private var settings = AppSettings.shared
@@ -36,22 +33,18 @@ struct KeyBar: View {
more
}
.frame(height: 38)
- if panelOpen {
+ if model.panelOpen {
KeyPanel(model: model, tab: $tab)
}
}
.background(model.background)
.onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)) { note in
- guard settings.autoKeyPanel else { return }
- // A hardware keyboard (the simulator's) posts a zero-height
- // frame: no keys on screen, so nothing for the panel to join.
+ // The keyboard coming up takes the panel's place: the two
+ // never stack. A hardware keyboard (the simulator's) posts a
+ // zero-height frame and takes nothing.
let frame = note.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect
guard (frame?.height ?? 0) > 0 else { return }
- withAnimation(.easeOut(duration: 0.16)) { panelOpen = true }
- }
- .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)) { _ in
- guard settings.autoKeyPanel else { return }
- withAnimation(.easeOut(duration: 0.16)) { panelOpen = false }
+ withAnimation(.easeOut(duration: 0.16)) { model.panelOpen = false }
}
}
@@ -79,13 +72,16 @@ struct KeyBar: View {
private var more: some View {
Button {
- withAnimation(.easeOut(duration: 0.16)) { panelOpen.toggle() }
+ // Opening the panel puts the keyboard away: the panel is its
+ // stand-in, not a shelf on top of it.
+ if !model.panelOpen { model.dismissKeyboard() }
+ withAnimation(.easeOut(duration: 0.16)) { model.panelOpen.toggle() }
KeyCaps.tap()
} label: {
- Image(systemName: panelOpen ? "chevron.down" : "square.grid.2x2")
+ Image(systemName: model.panelOpen ? "chevron.down" : "square.grid.2x2")
.font(.system(size: 14, weight: .semibold))
.frame(width: 40, height: 28)
- .background(panelOpen ? Color.accentColor : Color.white.opacity(0.14))
+ .background(model.panelOpen ? Color.accentColor : Color.white.opacity(0.14))
.clipShape(RoundedRectangle(cornerRadius: 7))
}
.buttonStyle(.plain)
diff --git a/ios/Sources/Sessions.swift b/ios/Sources/Sessions.swift
new file mode 100644
index 00000000..f2cf248c
--- /dev/null
+++ b/ios/Sources/Sessions.swift
@@ -0,0 +1,43 @@
+import SwiftUI
+
+/// The open connections, one per host, outliving the terminal screen:
+/// leaving the screen takes the picture away and nothing else, so a host
+/// list visited in between, or another host opened, finds them where
+/// they were. A host is closed from the list, or with the app.
+final class Sessions: ObservableObject {
+ @Published private(set) var models: [UUID: TerminalModel] = [:]
+
+ /// The probe has no host row; it keeps a slot of its own.
+ static let probeId = UUID(uuidString: "00000000-0000-0000-0000-0000000000BE")!
+
+ func model(for host: Host?, store: HostStore) -> TerminalModel {
+ let key = host?.id ?? Self.probeId
+ if let model = models[key] { return model }
+ let model = TerminalModel(host: host, store: store)
+ models[key] = model
+ return model
+ }
+
+ func existing(_ id: UUID) -> TerminalModel? { models[id] }
+
+ func close(_ id: UUID) {
+ models.removeValue(forKey: id)?.shutdown()
+ }
+
+ var all: [TerminalModel] { Array(models.values) }
+
+ /// The app left the screen or came back: every connection hears.
+ func detachForBackground() { all.forEach { $0.detachForBackground() } }
+ func reattachAfterBackground() { all.forEach { $0.reattachAfterBackground() } }
+}
+
+/// A green dot for a host whose session is open behind the list.
+struct ConnectionDot: View {
+ @ObservedObject var model: TerminalModel
+
+ var body: some View {
+ if model.isConnected {
+ Circle().fill(Color.green).frame(width: 8, height: 8)
+ }
+ }
+}
diff --git a/ios/Sources/SettingsSheet.swift b/ios/Sources/SettingsSheet.swift
index 169deb1c..f0f23aad 100644
--- a/ios/Sources/SettingsSheet.swift
+++ b/ios/Sources/SettingsSheet.swift
@@ -71,7 +71,6 @@ struct SettingsView: View {
}
}
Toggle(tr("k.haptics"), isOn: $settings.hapticKeys)
- Toggle(tr("k.autopanel"), isOn: $settings.autoKeyPanel)
}
Section(tr("sec.gestures")) {
diff --git a/ios/Sources/Sidebar.swift b/ios/Sources/Sidebar.swift
index 15a4178d..fbb31c06 100644
--- a/ios/Sources/Sidebar.swift
+++ b/ios/Sources/Sidebar.swift
@@ -12,6 +12,7 @@ struct SidebarPanel: View {
var connected: Bool
var onEditHost: () -> Void
var onSettings: () -> Void
+ var onOverview: () -> Void
/// Folded nodes; every Space but the one on show starts folded.
@State private var folded: Set<String>?
@State private var renaming: (kind: String, id: String)?
@@ -137,6 +138,14 @@ struct SidebarPanel: View {
.padding(.top, 8)
}
Divider()
+ Button(action: onOverview) {
+ Label(tr("overview"), systemImage: "square.grid.2x2")
+ .foregroundColor(.secondary)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.horizontal, 16)
+ .padding(.vertical, 12)
+ }
+ .buttonStyle(.plain)
Button(action: onSettings) {
Label(tr("settings"), systemImage: "gearshape")
.foregroundColor(.secondary)
diff --git a/ios/Sources/TerminalInputView.swift b/ios/Sources/TerminalInputView.swift
index 8b48c397..bbb74f75 100644
--- a/ios/Sources/TerminalInputView.swift
+++ b/ios/Sources/TerminalInputView.swift
@@ -43,7 +43,9 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDel
private var screen: ScreenText?
/// The system's selection, held so the gesture setting can take it
/// away and put it back while the terminal stays open.
- private let selection = UITextInteraction(for: .editable)
+ /// Non-editable: the system draws handles and a loupe for a selection
+ /// but never a caret -- the terminal's cursor is the only one.
+ private let selection = UITextInteraction(for: .nonEditable)
/// A caret the system placed with a tap: not drawn, but kept, so the
/// loupe and the handles that follow have a position to start from.
private var caret: Int?
@@ -367,10 +369,15 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDel
/// The pane's selection while there is one, else the caret at the
/// end of the marked text (the keyboard's insertion point).
+ /// The system's selection over the rows, as document offsets. It is
+ /// the shell's alone: the core is not told, so it draws no highlight
+ /// of its own under the system's, and the copy reads the rows here.
+ private var selected: (a: Int, b: Int)?
+
var selectedTextRange: UITextRange? {
get {
- if marked == nil, let s = currentScreen(), let sel = s.selection {
- return Range(index(row: sel[0][0], col: sel[0][1]), index(row: sel[1][0], col: sel[1][1]) + 1)
+ if marked == nil, let selected {
+ return Range(selected.a, selected.b)
}
if marked == nil, let caret, caret <= screenLength {
return Range(caret, caret)
@@ -381,27 +388,17 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDel
set {
guard let r = newValue as? Range else {
caret = nil
- model?.core.clearSelection()
- screen = nil
+ selected = nil
return
}
// A non-empty range inside the rows is a selection; a caret
- // inside them is remembered and clears it. The end is
- // exclusive here and inclusive in the core.
- if r.b > r.a, let a = cell(at: r.a), let b = cell(at: r.b - 1) {
+ // inside them is remembered and clears it.
+ if r.b > r.a, r.a < screenLength {
caret = nil
- model?.core.setSelection(anchorRow: UInt32(a.row), anchorCol: UInt32(a.col), headRow: UInt32(b.row), headCol: UInt32(b.col))
- if var s = screen {
- s.selection = [[a.row, a.col], [b.row, b.col]]
- screen = s
- }
+ selected = (r.a, min(r.b, screenLength))
} else {
caret = r.a < screenLength ? r.a : nil
- model?.core.clearSelection()
- if var s = screen {
- s.selection = nil
- screen = s
- }
+ selected = nil
}
}
}
@@ -558,20 +555,33 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDel
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
switch action {
- case #selector(copy(_:)): return currentScreen()?.selection != nil
+ case #selector(copy(_:)): return selected != nil
case #selector(paste(_:)): return UIPasteboard.general.hasStrings
case #selector(selectAll(_:)): return currentScreen() != nil
default: return false
}
}
+ /// The selected rows' text, each row's trailing blanks dropped, as
+ /// a terminal copies: the rows are fixed-width, the words are not.
+ func selectedText() -> String? {
+ guard let selected, let raw = text(in: Range(selected.a, selected.b)) else { return nil }
+ let lines = raw.split(separator: "\n", omittingEmptySubsequences: false).map { line -> String in
+ var s = String(line)
+ while s.last == " " { s.removeLast() }
+ return s
+ }
+ let joined = lines.joined(separator: "\n")
+ return joined.isEmpty ? nil : joined
+ }
+
override func copy(_ sender: Any?) {
- if let text = model?.core.selectedText(), !text.isEmpty {
+ if let text = selectedText() {
UIPasteboard.general.string = text
model?.showCopied()
}
- model?.core.clearSelection()
- screen = nil
+ selected = nil
+ inputDelegate?.selectionDidChange(self)
}
override func paste(_ sender: Any?) {
diff --git a/ios/Sources/TerminalModel.swift b/ios/Sources/TerminalModel.swift
index f583dfff..6b5e7834 100644
--- a/ios/Sources/TerminalModel.swift
+++ b/ios/Sources/TerminalModel.swift
@@ -25,6 +25,16 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {
@Published var status: StatusView?
@Published var title = ""
@Published var connection = ""
+ /// The key panel is up in the keyboard's place.
+ @Published var panelOpen = ProcessInfo.processInfo.arguments.contains("--keypanel")
+ /// A thread this phone was on last time it was in this host, put
+ /// back once the threads are listed after a connect.
+ private var restoredThread = false
+ private var lastThreadKey: String? { host.map { "thread.last." + $0.id.uuidString } }
+
+ var isConnected: Bool {
+ !connection.isEmpty && !connection.hasPrefix("disconnected") && !connection.hasPrefix("failed") && !connection.hasPrefix("idle")
+ }
@Published var attached = false
@Published var composing: String?
@Published var ctrlSticky = false
@@ -48,7 +58,7 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {
@Published private(set) var fontPt: Double = 11
/// The focused pane's place in its scrollback: rows above the bottom,
/// and rows there are; changes for a moment show the scrollbar.
- @Published private(set) var scroll: (Int, Int) = (0, 0)
+ @Published private(set) var scroll: (Double, Int) = (0, 0)
@Published private(set) var scrollShown = false
private var scrollTimer: Timer?
/// The background task that holds the connection after the app leaves
@@ -143,6 +153,11 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {
if args.contains("--uitest") { scheduleUiTest() }
}
+ /// The screen went away but the connection stays: the frame loop
+ /// rests until the screen is back. The surface goes with the view.
+ func leaveScreen() { displayLink?.isPaused = true }
+ func enterScreen() { displayLink?.isPaused = false }
+
func shutdown() {
displayLink?.invalidate()
statsTimer?.invalidate()
@@ -172,6 +187,7 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {
/// Connect to the model's host with the secret from the Keychain.
func connect() {
+ restoredThread = false
guard let host else {
connectProbe()
return
@@ -349,6 +365,22 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {
/// Show a thread, switching the Space on show to its own first when
/// it is in another one, so the strips follow.
+ /// The thread on show is written down for the next connect; the first
+ /// listing after a connect puts the phone back on the one it left.
+ private func rememberThread(_ threads: ThreadsView?) {
+ guard let key = lastThreadKey, let list = threads?.threads,
+ let current = list.first(where: { $0.current })?.id else { return }
+ if !restoredThread {
+ restoredThread = true
+ if let saved = UserDefaults.standard.string(forKey: key), saved != current,
+ list.contains(where: { $0.id == saved }) {
+ openThread(saved, space: nil)
+ return
+ }
+ }
+ UserDefaults.standard.set(current, forKey: key)
+ }
+
func openThread(_ id: String, space: String?) {
if let space, tree?.spaces.first(where: { $0.current })?.id != space { core.setSpace(id: space) }
sideClick("thread", id: id)
@@ -385,6 +417,7 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {
if sidebar != self.sidebar { self.sidebar = sidebar }
let threads = ViewJSON.decode(ThreadsView.self, core.view(name: "threads"))
if threads != self.threads { self.threads = threads }
+ rememberThread(threads)
let tree = ViewJSON.decode(TreeView.self, core.view(name: "tree"))
if tree != self.tree { self.tree = tree }
let navs = ViewJSON.decode([NavView].self, core.view(name: "navs")) ?? []
@@ -403,7 +436,7 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {
if let r = layout.range(of: "\"scroll\":["),
let end = layout[r.upperBound...].firstIndex(of: "]") {
let parts = layout[r.upperBound..<end].split(separator: ",")
- if parts.count == 2, let a = Int(parts[0]), let b = Int(parts[1]), (a, b) != scroll {
+ if parts.count == 2, let a = Double(parts[0]), let b = Int(parts[1]), (a, b) != scroll {
scroll = (a, b)
scrollShown = true
scrollTimer?.invalidate()
@@ -750,8 +783,8 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {
let read = input.text(in: range) ?? ""
self.check("document text", read == "SELECT-ME-PLEASE", read)
q.asyncAfter(deadline: .now() + 0.5) {
- let copied = self.core.selectedText() ?? ""
- self.check("core selection", copied == "SELECT-ME-PLEASE", copied)
+ let copied = input.selectedText() ?? ""
+ self.check("shell selection", copied == "SELECT-ME-PLEASE", copied)
let back = input.selectedTextRange as? TerminalInputView.Range
self.check("selection read back", back?.a == a && back?.b == a + "SELECT-ME-PLEASE".count, "\(back?.a ?? -1)..\(back?.b ?? -1)")
let rects = input.selectionRects(for: range)
diff --git a/ios/Sources/TerminalScreen.swift b/ios/Sources/TerminalScreen.swift
index d4363dae..a2ae9dd2 100644
--- a/ios/Sources/TerminalScreen.swift
+++ b/ios/Sources/TerminalScreen.swift
@@ -3,10 +3,11 @@ import SwiftUI
/// One host: its terminal, the tab strip, the bars over the panes, the
/// key bar, and the sidebar and menus as sheets.
struct TerminalScreen: View {
- @StateObject private var model: TerminalModel
+ /// The host's session, from `Sessions`: the screen shows it and
+ /// gives it back on the way out, connection and all.
+ @ObservedObject var model: TerminalModel
@ObservedObject private var settings = AppSettings.shared
@ObservedObject private var lang = AppLanguage.shared
- @Environment(\.scenePhase) private var scenePhase
@Environment(\.dismiss) private var dismiss
@State private var showTree = false
@State private var showLog = false
@@ -48,10 +49,6 @@ struct TerminalScreen: View {
@State private var livePreview = false
@State private var deletingThread: ThreadView?
- init(host: Host?, store: HostStore?) {
- _model = StateObject(wrappedValue: TerminalModel(host: host, store: store))
- }
-
/// The tabs live in the navigation bar, between the system's own back
/// button and the menu; the keys sit below the terminal, and nothing
/// else. Every piece of chrome takes the terminal's own background.
@@ -63,7 +60,7 @@ struct TerminalScreen: View {
liveThread: currentThreadId, livePreview: livePreview,
onPick: { thread, frames in if let frames { picked = (thread, frames) } }
)
- .opacity(overviewOpen ? 1 : 0)
+ .opacity(gridOpacity)
.onChange(of: overviewShown) { _, shown in if !shown { closeOverview() } }
}
// The card's own header rides along with the terminal: laid out at
@@ -116,12 +113,16 @@ struct TerminalScreen: View {
.zIndex(2)
.allowsHitTesting(!overviewOpen)
statusLine.opacity(overviewOpen ? 0 : 1)
- if keyboardUp && !overviewOpen {
+ if (keyboardUp || model.panelOpen) && !overviewOpen {
+ // With the keyboard down the bar sits on the home
+ // indicator's inset; with it up, on the keyboard.
KeyBar(model: model)
+ .padding(.bottom, keyboardUp ? 0 : Self.bottomInset)
.transition(.move(edge: .bottom).combined(with: .opacity))
}
}
.animation(.easeOut(duration: 0.2), value: keyboardUp)
+ .animation(.easeOut(duration: 0.2), value: model.panelOpen)
.zIndex(1)
.allowsHitTesting(!overviewOpen)
}
@@ -132,7 +133,8 @@ struct TerminalScreen: View {
hostName: hostName,
connected: connected,
onEditHost: { showTree = false; editingHost = model.host },
- onSettings: { showTree = false; showSettings = true }
+ onSettings: { showTree = false; showSettings = true },
+ onOverview: { showTree = false; openOverview() }
)
}
.coordinateSpace(name: "screen")
@@ -149,8 +151,9 @@ struct TerminalScreen: View {
keyboardUp = false
}
.onChange(of: cardFrame) { _, frames in
- // The card's thumbnail is laid out: the terminal goes there.
- if overviewShown, let frames, !overviewOpen { zoom(into: frames) }
+ // The card's thumbnail is laid out: the terminal goes there --
+ // even when it came late and the overview opened without it.
+ if overviewShown, let frames, heroFrames == nil { zoom(into: frames) }
}
.navigationBarTitleDisplayMode(.inline)
.toolbar(.hidden, for: .tabBar)
@@ -159,13 +162,9 @@ struct TerminalScreen: View {
.toolbar {
ToolbarItem(placement: .principal) { tabStrip.frame(width: max(barWidth - 190, 120)) }
ToolbarItem(placement: .topBarLeading) {
- // The desktop's sidebar: the projects and threads, as a sheet.
- Button { showTree = true } label: { Image(systemName: "sidebar.left") }
- }
- ToolbarItem(placement: .topBarTrailing) {
- Button { if overviewShown { overviewShown = false } else { openOverview() } } label: {
- Image(systemName: "square.grid.2x2")
- }
+ // The desktop's sidebar: the projects and threads, as a
+ // panel; the keyboard goes first, or the panel sits on it.
+ Button { model.dismissKeyboard(); showTree = true } label: { Image(systemName: "sidebar.left") }
}
}
.ignoresSafeArea(.container, edges: .bottom)
@@ -204,9 +203,11 @@ struct TerminalScreen: View {
}
}
.onAppear {
- // The automated flows connect on their own schedule.
+ model.enterScreen()
+ // The automated flows connect on their own schedule; a session
+ // found open is simply shown.
let args = ProcessInfo.processInfo.arguments
- if !args.contains(where: { $0.hasSuffix("test") || $0 == "--autoconnect" }) {
+ if !args.contains(where: { $0.hasSuffix("test") || $0 == "--autoconnect" }), !model.isConnected {
model.connect()
}
#if DEBUG
@@ -220,14 +221,8 @@ struct TerminalScreen: View {
#endif
}
.onDisappear {
- model.shutdown()
- }
- .onChange(of: scenePhase) { _, phase in
- switch phase {
- case .background: model.detachForBackground()
- case .active: model.reattachAfterBackground()
- default: break
- }
+ // The picture goes, the connection stays (see Sessions).
+ model.leaveScreen()
}
}
@@ -403,6 +398,25 @@ struct TerminalScreen: View {
private var currentThreadId: String? { model.threads?.threads.first(where: { $0.current })?.id }
+ /// The cards' opacity follows the zoom itself, so no frame shows the
+ /// cards before the terminal has begun to shrink (or after it has
+ /// begun to grow back): one curve for both.
+ private var gridOpacity: Double {
+ guard overviewOpen else { return 0 }
+ guard let hero = heroFrames, terminalFrame.width > 0 else { return 1 }
+ let end = hero.thumb.width / terminalFrame.width
+ guard end < 0.999 else { return 1 }
+ return min(max((1 - zoomScale) / (1 - end), 0), 1)
+ }
+
+ /// The home indicator's inset, for a bar that sits at the bottom
+ /// while the keyboard is down.
+ private static var bottomInset: CGFloat {
+ UIApplication.shared.connectedScenes
+ .compactMap { ($0 as? UIWindowScene)?.keyWindow }
+ .first?.safeAreaInsets.bottom ?? 0
+ }
+
private func openOverview() {
guard !overviewShown else { return }
model.refreshViews()
@@ -423,7 +437,7 @@ struct TerminalScreen: View {
// A card the lazy grid never realises reports nothing; the
// overview must not stay invisible for it. After a moment, the
// terminal only fades.
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) {
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
if overviewShown && !overviewOpen {
withAnimation(.easeOut(duration: 0.25)) { overviewOpen = true }
}
diff --git a/ios/Sources/ThinkTermApp.swift b/ios/Sources/ThinkTermApp.swift
index 695b5a04..7dfbea56 100644
--- a/ios/Sources/ThinkTermApp.swift
+++ b/ios/Sources/ThinkTermApp.swift
@@ -3,18 +3,20 @@ import SwiftUI
@main
struct ThinkTermApp: App {
@StateObject private var store = HostStore()
+ @StateObject private var sessions = Sessions()
var body: some Scene {
WindowGroup {
Group {
if ProcessInfo.processInfo.arguments.contains(where: { $0.hasPrefix("--auto") || $0.hasSuffix("test") }) {
// The automated flows go straight to the probe's host.
- NavigationStack { TerminalScreen(host: nil, store: store) }
+ NavigationStack { TerminalScreen(model: sessions.model(for: nil, store: store)) }
} else {
RootTabs(store: store)
}
}
.environmentObject(store)
+ .environmentObject(sessions)
.preferredColorScheme(.dark)
}
}
@@ -47,6 +49,8 @@ struct ThinkTermApp: App {
/// with the rest of the app.
private struct RootTabs: View {
let store: HostStore
+ @EnvironmentObject private var sessions: Sessions
+ @Environment(\.scenePhase) private var scenePhase
@State private var path = NavigationPath()
@ObservedObject private var lang = AppLanguage.shared
@@ -69,5 +73,13 @@ private struct RootTabs: View {
}
.tabItem { Label(tr("settings"), systemImage: "gearshape") }
}
+ // Every open connection hears about the background, on screen or not.
+ .onChange(of: scenePhase) { _, phase in
+ switch phase {
+ case .background: sessions.detachForBackground()
+ case .active: sessions.reattachAfterBackground()
+ default: break
+ }
+ }
}
}
diff --git a/thinkterm-web/src/app.rs b/thinkterm-web/src/app.rs
index 34e85229..29f5f53f 100644
--- a/thinkterm-web/src/app.rs
+++ b/thinkterm-web/src/app.rs
@@ -2502,7 +2502,17 @@ impl<P: Platform, L: Link> App<P, L> {
// bottom, and rows there are to scroll through.
if let Some(cell) = inner.panes.get(&inner.focused_pane) {
let max = max_scroll(&cell.session.dimensions());
- json.push_str(&format!(",\"scroll\":[{},{}]", cell.scroll_from_bottom, max));
+ // With the fraction of a row a smooth scroll is part way
+ // through, so a bar following it moves as the rows do rather
+ // than a row at a time.
+ let cell_h = inner
+ .pane_fonts
+ .get(&inner.focused_pane)
+ .map(|f| f.glyphs.metrics.cell_size.height as f32)
+ .unwrap_or(inner.glyphs.metrics.cell_size.height as f32)
+ .max(1.0);
+ let above = cell.scroll_from_bottom as f32 + cell.scroll_px / cell_h;
+ json.push_str(&format!(",\"scroll\":[{above:.3},{max}]"));
}
match &inner.tab_layout {
Some(layout) => {