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.

ios: threads over tabs, the overview, the key panel, settings that work, five languages

RoversX872687e81c95
diff --git a/ios/Sources/AppSettings.swift b/ios/Sources/AppSettings.swift
index 4f201fae..796b0400 100644
--- a/ios/Sources/AppSettings.swift
+++ b/ios/Sources/AppSettings.swift
@@ -3,29 +3,157 @@ import Combine
/// 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.
+/// as they change. The sections follow the approved prototype; the rows
+/// marked "not read yet" are stored so the screen is whole, and the code
+/// that honours them comes later.
final class AppSettings: ObservableObject {
static let shared = AppSettings()
+ // MARK: general
+
+ /// A tag of Resources/strings.json, or "system" to follow the phone's.
+ /// The views watch AppLanguage, so a change relabels them at once.
+ @Published var language: String {
+ didSet {
+ defaults.set(language, forKey: "lang")
+ AppLanguage.shared.tag = language
+ }
+ }
+
+ // MARK: appearance
+
/// A scheme name from schemes.json, or "desktop" to follow the host's.
@Published var schemeName: String {
didSet { defaults.set(schemeName, forKey: "scheme.name") }
}
+ /// The text size a connection starts at, in points.
+ @Published var fontSize: Double {
+ didSet { defaults.set(fontSize, forKey: "font.size") }
+ }
+ /// One of the bundled faces; a change reconnects to shape with it.
+ @Published var fontFamily: String {
+ didSet { defaults.set(fontFamily, forKey: "font.family") }
+ }
+ /// "off", "3", "45" or "7": a WCAG floor text is lifted to.
+ @Published var contrast: String {
+ didSet { defaults.set(contrast, forKey: "text.contrast") }
+ }
+
+ // MARK: terminal
+
/// Smooth (by the pixel, with inertia) or stepped (whole rows).
@Published var smoothScroll: Bool {
didSet { defaults.set(smoothScroll, forKey: "scroll.smooth") }
}
- /// The text size a connection starts at, in points.
- @Published var fontSize: Double {
- didSet { defaults.set(fontSize, forKey: "font.size") }
+ /// A thin bar at the right while the scrollback moves.
+ @Published var scrollbar: Bool {
+ didSet { defaults.set(scrollbar, forKey: "scroll.bar") }
+ }
+ /// "auto" (the program's), "block", "bar" or "underline".
+ @Published var cursorStyle: String {
+ didSet { defaults.set(cursorStyle, forKey: "cursor.style") }
+ }
+ /// The core blinks the cursor, or holds it steady.
+ @Published var cursorBlink: Bool {
+ didSet { defaults.set(cursorBlink, forKey: "cursor.blink") }
+ }
+ /// A pane's bell buzzes the phone.
+ @Published var bell: Bool {
+ didSet { defaults.set(bell, forKey: "bell") }
+ }
+ /// "auto" or "live": the server's panes follow a divider drag as it
+ /// goes; "release": once, when the finger lifts.
+ @Published var resizeMode: String {
+ didSet { defaults.set(resizeMode, forKey: "resize.mode") }
+ }
+
+ // MARK: interface
+
+ /// "one" or "two" levels of tabs: threads over tabs, or tabs alone.
+ @Published var tabBarLevels: String {
+ didSet { defaults.set(tabBarLevels, forKey: "ui.tabbar") }
+ }
+ /// The bars over split panes; off, the rows go to the terminal.
+ @Published var paneBars: Bool {
+ didSet { defaults.set(paneBars, forKey: "ui.panebars") }
+ }
+
+ // MARK: keyboard
+
+ /// A tap on a key taps back. The key bar and the key panel read it.
+ @Published var hapticKeys: Bool {
+ didSet { defaults.set(hapticKeys, forKey: "key.haptics") }
+ }
+ /// The key panel opens with the software keyboard.
+ @Published var autoKeyPanel: Bool {
+ didSet { defaults.set(autoKeyPanel, forKey: "key.autopanel") }
+ }
+
+ // MARK: gestures
+
+ /// A pinch on the terminal steps the text size.
+ @Published var pinchZoom: Bool {
+ didSet { defaults.set(pinchZoom, forKey: "gesture.pinch") }
+ }
+ /// A two-finger swipe down puts the keyboard away.
+ @Published var twoFingerHidesKeyboard: Bool {
+ didSet { defaults.set(twoFingerHidesKeyboard, forKey: "gesture.twofinger") }
+ }
+ /// A long press starts the system's text selection.
+ @Published var longPressSelects: Bool {
+ didSet { defaults.set(longPressSelects, forKey: "gesture.longpress") }
+ }
+
+ // MARK: connection
+
+ /// Redial when the connection drops; off, wait to be asked.
+ @Published var autoReconnect: Bool {
+ didSet { defaults.set(autoReconnect, forKey: "conn.autoreconnect") }
+ }
+ /// Seconds between ssh keep-alives, 0 for none; the next connection
+ /// takes it.
+ @Published var keepAliveSeconds: Int {
+ didSet { defaults.set(keepAliveSeconds, forKey: "conn.keepalive") }
+ }
+ /// Hold the connection when the app goes to the background, for as
+ /// long as iOS allows; off, drop it at once and redial on return.
+ @Published var keepSessionInBackground: Bool {
+ didSet { defaults.set(keepSessionInBackground, forKey: "conn.background") }
+ }
+
+ // MARK: diagnostics
+
+ /// The core's counters over the terminal.
+ @Published var devMode: Bool {
+ didSet { defaults.set(devMode, forKey: "dev.mode") }
}
private let defaults = UserDefaults.standard
private init() {
- schemeName = defaults.string(forKey: "scheme.name") ?? Schemes.followDesktop
- smoothScroll = defaults.object(forKey: "scroll.smooth") as? Bool ?? true
- let size = defaults.double(forKey: "font.size")
+ let d = UserDefaults.standard
+ language = d.string(forKey: "lang") ?? "system"
+ schemeName = d.string(forKey: "scheme.name") ?? Schemes.followDesktop
+ let size = d.double(forKey: "font.size")
fontSize = size > 0 ? size : 11
+ fontFamily = d.string(forKey: "font.family") ?? "JetBrains Mono"
+ contrast = d.string(forKey: "text.contrast") ?? "off"
+ smoothScroll = d.object(forKey: "scroll.smooth") as? Bool ?? true
+ scrollbar = d.object(forKey: "scroll.bar") as? Bool ?? false
+ cursorStyle = d.string(forKey: "cursor.style") ?? "block"
+ cursorBlink = d.object(forKey: "cursor.blink") as? Bool ?? true
+ bell = d.object(forKey: "bell") as? Bool ?? false
+ resizeMode = d.string(forKey: "resize.mode") ?? "auto"
+ tabBarLevels = d.string(forKey: "ui.tabbar") ?? "two"
+ paneBars = d.object(forKey: "ui.panebars") as? Bool ?? true
+ hapticKeys = d.object(forKey: "key.haptics") as? Bool ?? true
+ autoKeyPanel = d.object(forKey: "key.autopanel") as? Bool ?? false
+ pinchZoom = d.object(forKey: "gesture.pinch") as? Bool ?? true
+ twoFingerHidesKeyboard = d.object(forKey: "gesture.twofinger") as? Bool ?? true
+ longPressSelects = d.object(forKey: "gesture.longpress") as? Bool ?? true
+ autoReconnect = d.object(forKey: "conn.autoreconnect") as? Bool ?? true
+ keepAliveSeconds = d.object(forKey: "conn.keepalive") as? Int ?? 30
+ keepSessionInBackground = d.object(forKey: "conn.background") as? Bool ?? true
+ devMode = d.object(forKey: "dev.mode") as? Bool ?? false
}
}
diff --git a/ios/Sources/HostEditView.swift b/ios/Sources/HostEditView.swift
index 67f09937..c133b70d 100644
--- a/ios/Sources/HostEditView.swift
+++ b/ios/Sources/HostEditView.swift
@@ -8,6 +8,7 @@ struct HostEditView: View {
@Environment(\.dismiss) private var dismiss
@EnvironmentObject var store: HostStore
@State var host: Host
+ @ObservedObject private var lang = AppLanguage.shared
@State private var secret = ""
@State private var passphrase = ""
@State private var hasStoredSecret = false
@@ -28,12 +29,12 @@ struct HostEditView: View {
}
.scrollContentBackground(.hidden)
.background(Color.black.ignoresSafeArea())
- .navigationTitle(host.hostname.isEmpty ? "New host" : host.display)
+ .navigationTitle(host.hostname.isEmpty ? tr("newhost") : host.display)
.navigationBarTitleDisplayMode(.inline)
.toolbar {
- ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
+ ToolbarItem(placement: .cancellationAction) { Button(tr("cancel")) { dismiss() } }
ToolbarItem(placement: .confirmationAction) {
- Button("Save") {
+ Button(tr("save")) {
save(host, secret, passphrase.isEmpty ? nil : passphrase)
dismiss()
}
@@ -46,10 +47,10 @@ struct HostEditView: View {
importKey(result)
}
.alert(
- "Import failed",
+ tr("key.importfailed"),
isPresented: Binding(get: { importError != nil }, set: { if !$0 { importError = nil } })
) {
- Button("OK", role: .cancel) { importError = nil }
+ Button(tr("ok"), role: .cancel) { importError = nil }
} message: {
Text(importError ?? "")
}
@@ -57,21 +58,21 @@ struct HostEditView: View {
}
private var hostSection: some View {
- Section("Host") {
- labelled("Name") {
- TextField("Optional", text: $host.name)
+ Section(tr("f.host")) {
+ labelled(tr("f.name")) {
+ TextField(tr("optional"), text: $host.name)
}
- labelled("Hostname") {
+ labelled(tr("f.hostname")) {
TextField("example.com or 10.0.0.4", text: $host.hostname)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.keyboardType(.URL)
}
- labelled("Port") {
+ labelled(tr("f.port")) {
TextField("22", value: $host.port, format: .number)
.keyboardType(.numberPad)
}
- labelled("User") {
+ labelled(tr("f.user")) {
TextField("root", text: $host.user)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
@@ -81,8 +82,8 @@ struct HostEditView: View {
private var groupSection: some View {
Section {
- labelled("Group") {
- TextField("None", text: $host.group)
+ labelled(tr("f.group")) {
+ TextField(tr("none"), text: $host.group)
.autocorrectionDisabled()
}
if !store.groups.isEmpty {
@@ -113,15 +114,15 @@ struct HostEditView: View {
.listRowInsets(EdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16))
}
} header: {
- Text("Group")
+ Text(tr("f.group"))
} footer: {
- Text("Groups become sections in the host list.")
+ Text(tr("f.groupfoot"))
}
}
private var authSection: some View {
- Section("Authentication") {
- Picker("Method", selection: $host.auth) {
+ Section(tr("f.auth")) {
+ Picker(tr("f.method"), selection: $host.auth) {
ForEach(Host.AuthKind.allCases) { kind in Text(kind.label).tag(kind) }
}
.pickerStyle(.segmented)
@@ -130,13 +131,13 @@ struct HostEditView: View {
if host.auth == .key {
keyStatusRow
- Button { pasteKey() } label: { Label("Paste from clipboard", systemImage: "doc.on.clipboard") }
- Button { importing = true } label: { Label("Import file…", systemImage: "folder") }
- Button { generateKey() } label: { Label("Generate new key", systemImage: "key.fill") }
+ Button { pasteKey() } label: { Label(tr("key.paste"), systemImage: "doc.on.clipboard") }
+ Button { importing = true } label: { Label(tr("key.import"), systemImage: "folder") }
+ Button { generateKey() } label: { Label(tr("key.generate"), systemImage: "key.fill") }
if let publicKey = host.publicKey, !publicKey.isEmpty {
publicKeyRow(publicKey)
}
- DisclosureGroup("Paste key text", isExpanded: $showKeyText) {
+ DisclosureGroup(tr("key.pastetext"), isExpanded: $showKeyText) {
TextEditor(text: $secret)
.font(.system(size: 11, design: .monospaced))
.frame(minHeight: 120)
@@ -145,9 +146,9 @@ struct HostEditView: View {
.scrollContentBackground(.hidden)
.onChange(of: secret) { _, _ in refreshPublicKey() }
}
- SecureField("Key passphrase (if any)", text: $passphrase)
+ SecureField(tr("key.passphrase"), text: $passphrase)
} else {
- SecureField("Password", text: $secret)
+ SecureField(tr("f.password"), text: $secret)
}
}
}
@@ -176,13 +177,13 @@ struct HostEditView: View {
copiedPublicKey = true
} label: {
Label(
- copiedPublicKey ? "Copied" : "Copy public key",
+ copiedPublicKey ? tr("copied") : tr("key.copypub"),
systemImage: copiedPublicKey ? "checkmark" : "doc.on.doc"
)
.font(.subheadline)
}
.buttonStyle(.bordered)
- Text("Add this line to ~/.ssh/authorized_keys on the host.")
+ Text(tr("key.authorized"))
.font(.caption)
.foregroundStyle(.secondary)
}
@@ -191,20 +192,20 @@ struct HostEditView: View {
private var advancedSection: some View {
Section {
- DisclosureGroup("Advanced", isExpanded: $showAdvanced) {
+ DisclosureGroup(tr("f.advanced"), isExpanded: $showAdvanced) {
VStack(alignment: .leading, spacing: 6) {
- TextField("Remote command", text: $host.remoteCommand)
+ TextField(tr("f.remotecmd"), text: $host.remoteCommand)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.font(.system(size: 13, design: .monospaced))
- Text("Blank runs `thinkterm cli --prefer-mux proxy` on the host.")
+ Text(tr("f.remotecmd.foot"))
.font(.caption)
.foregroundStyle(.secondary)
}
.padding(.vertical, 4)
if let known = host.knownHost {
VStack(alignment: .leading, spacing: 4) {
- Text("Host key")
+ Text(tr("f.hostkey"))
.font(.subheadline)
Text(known)
.font(.system(size: 11, design: .monospaced))
@@ -216,7 +217,7 @@ struct HostEditView: View {
Button(role: .destructive) {
host.knownHost = nil
} label: {
- Label("Forget host key", systemImage: "xmark.shield")
+ Label(tr("forgetkey"), systemImage: "xmark.shield")
}
}
}
@@ -244,11 +245,11 @@ struct HostEditView: View {
private var keyStatus: (text: String, symbol: String, tint: Color) {
if !secret.isEmpty {
return host.publicKey == nil
- ? ("Key loaded", "checkmark.seal.fill", .green)
- : ("ed25519 key loaded", "checkmark.seal.fill", .green)
+ ? (tr("key.loaded"), "checkmark.seal.fill", .green)
+ : (tr("key.loaded.ed25519"), "checkmark.seal.fill", .green)
}
- if hasStoredSecret { return ("Key stored", "lock.fill", .green) }
- return ("No key yet", "exclamationmark.triangle.fill", .orange)
+ if hasStoredSecret { return (tr("key.stored"), "lock.fill", .green) }
+ return (tr("key.none"), "exclamationmark.triangle.fill", .orange)
}
private var keyComment: String { "\(host.user)@thinkterm-ios" }
@@ -273,7 +274,7 @@ struct HostEditView: View {
let scoped = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
guard let text = try? String(contentsOf: url, encoding: .utf8) else {
- importError = "That file is not readable as text."
+ importError = tr("key.notext")
return
}
secret = text
diff --git a/ios/Sources/HostsView.swift b/ios/Sources/HostsView.swift
index 16f1a632..8e95a36c 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
+ @ObservedObject private var lang = AppLanguage.shared
@State private var editing: Host?
@State private var adding = false
@State private var search = ""
@@ -25,7 +26,7 @@ struct HostsView: View {
.listRowSeparator(.hidden)
} else if matches.isEmpty {
Section {
- Text("No hosts match “\(search)”.")
+ Text(tr("hosts.nomatch.q", search))
.font(.subheadline)
.foregroundStyle(.secondary)
.frame(maxWidth: .infinity, alignment: .center)
@@ -39,19 +40,19 @@ struct HostsView: View {
}
} else {
ForEach(sections) { group in
- Section(group.title ?? "Other") {
+ Section(group.title ?? tr("hosts.other")) {
ForEach(group.hosts) { row($0) }
}
}
}
#if DEBUG
- Section("Development") {
+ Section(tr("dev")) {
NavigationLink(value: probe) {
HostRowLayout(
symbol: "hammer",
tint: .gray,
- title: "This Mac",
+ title: tr("thismac"),
subtitle: "probe sshd on 127.0.0.1:2299"
)
}
@@ -61,9 +62,9 @@ struct HostsView: View {
.listStyle(.insetGrouped)
.scrollContentBackground(.hidden)
.background(Color.black.ignoresSafeArea())
- .navigationTitle("Hosts")
+ .navigationTitle(tr("hosts"))
.navigationBarTitleDisplayMode(.large)
- .searchable(text: $search, placement: .navigationBarDrawer, prompt: "Search hosts")
+ .searchable(text: $search, placement: .navigationBarDrawer, prompt: tr("hosts.search"))
.navigationDestination(for: Host.self) { host in
if host.name == "probe" {
TerminalScreen(host: nil, store: store)
@@ -79,7 +80,7 @@ struct HostsView: View {
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
Button { adding = true } label: { Image(systemName: "plus") }
- .accessibilityLabel("Add host")
+ .accessibilityLabel(tr("hosts.add"))
}
}
.sheet(isPresented: $adding) {
@@ -99,15 +100,15 @@ struct HostsView: View {
.environmentObject(store)
}
.confirmationDialog(
- "Delete this host?",
+ tr("host.delete.title"),
isPresented: Binding(get: { pendingDelete != nil }, set: { if !$0 { pendingDelete = nil } }),
titleVisibility: .visible,
presenting: pendingDelete
) { host in
- Button("Delete \(host.display)", role: .destructive) { store.remove(host) }
- Button("Cancel", role: .cancel) {}
+ Button(tr("host.delete.confirm", host.display), role: .destructive) { store.remove(host) }
+ Button(tr("cancel"), role: .cancel) {}
} message: { _ in
- Text("Its saved key or password is removed from the Keychain too.")
+ Text(tr("host.delete.body"))
}
}
@@ -117,19 +118,19 @@ struct HostsView: View {
HostRow(host: host)
}
.swipeActions(edge: .trailing) {
- Button(role: .destructive) { pendingDelete = host } label: { Label("Delete", systemImage: "trash") }
- Button { editing = host } label: { Label("Edit", systemImage: "pencil") }
+ Button(role: .destructive) { pendingDelete = host } label: { Label(tr("delete"), systemImage: "trash") }
+ Button { editing = host } label: { Label(tr("edit"), systemImage: "pencil") }
.tint(.indigo)
}
.contextMenu {
- Button { connecting = ConnectTarget(host: host) } label: { Label("Connect", systemImage: "bolt.horizontal") }
- Button { editing = host } label: { Label("Edit", systemImage: "pencil") }
- Button { duplicate(host) } label: { Label("Duplicate", systemImage: "plus.square.on.square") }
+ Button { connecting = ConnectTarget(host: host) } label: { Label(tr("connect"), systemImage: "bolt.horizontal") }
+ 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 {
- Button { store.forgetHostKey(for: host.id) } label: { Label("Forget host key", systemImage: "xmark.shield") }
+ Button { store.forgetHostKey(for: host.id) } label: { Label(tr("forgetkey"), systemImage: "xmark.shield") }
}
Divider()
- Button(role: .destructive) { pendingDelete = host } label: { Label("Delete", systemImage: "trash") }
+ Button(role: .destructive) { pendingDelete = host } label: { Label(tr("delete"), systemImage: "trash") }
}
}
@@ -138,7 +139,7 @@ struct HostsView: View {
private func duplicate(_ host: Host) {
var copy = host
copy.id = UUID()
- copy.name = (host.name.isEmpty ? host.display : host.name) + " copy"
+ copy.name = (host.name.isEmpty ? host.display : host.name) + tr("host.copysuffix")
copy.lastConnected = nil
if let secret = Keychain.load(account: host.id.uuidString) {
Keychain.save(secret, account: copy.id.uuidString)
@@ -190,6 +191,7 @@ private struct ConnectTarget: Hashable {
struct HostRow: View {
let host: Host
+ @ObservedObject private var lang = AppLanguage.shared
var body: some View {
HostRowLayout(
@@ -202,7 +204,7 @@ struct HostRow: View {
Text(host.lastConnectedText)
.font(.caption)
.foregroundStyle(.tertiary)
- Text(host.auth == .key ? "key" : "password")
+ Text(host.auth == .key ? tr("badge.key") : tr("badge.password"))
.font(.caption2.weight(.semibold))
.foregroundStyle(.secondary)
.padding(.horizontal, 7)
@@ -253,6 +255,7 @@ extension HostRowLayout where Detail == EmptyView {
struct HostsEmptyState: View {
var add: () -> Void
+ @ObservedObject private var lang = AppLanguage.shared
var body: some View {
VStack(spacing: 10) {
@@ -260,15 +263,15 @@ struct HostsEmptyState: View {
.font(.system(size: 46, weight: .light))
.foregroundStyle(.secondary)
.padding(.bottom, 4)
- Text("No hosts yet")
+ Text(tr("hosts.empty"))
.font(.title3.weight(.semibold))
- Text("Add a machine that has ThinkTerm installed. The app connects over ssh and attaches to its sessions.")
+ Text(tr("hosts.empty.body"))
.font(.subheadline)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
.fixedSize(horizontal: false, vertical: true)
Button(action: add) {
- Label("Add host", systemImage: "plus")
+ Label(tr("hosts.add"), systemImage: "plus")
.font(.headline)
.frame(maxWidth: .infinity)
}
@@ -303,7 +306,9 @@ extension Host {
}
var lastConnectedText: String {
- guard let last = lastConnected else { return "Never connected" }
+ guard let last = lastConnected else { return tr("hosts.never") }
+ // "13m ago" follows the app's language, not the phone's.
+ hostRelativeFormatter.locale = Locale(identifier: L10n.currentTag)
return hostRelativeFormatter.localizedString(for: last, relativeTo: Date())
}
}
diff --git a/ios/Sources/KeyBar.swift b/ios/Sources/KeyBar.swift
index 6ace9740..ea8bc324 100644
--- a/ios/Sources/KeyBar.swift
+++ b/ios/Sources/KeyBar.swift
@@ -1,4 +1,5 @@
import SwiftUI
+import UIKit
/// 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
@@ -11,6 +12,7 @@ struct KeyBar: View {
/// 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
/// `--keypanel snippets` also picks the face it opens on.
private static var debugTab: KeyPanelTab {
@@ -39,6 +41,18 @@ struct KeyBar: View {
}
}
.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.
+ 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 }
+ }
}
private func key(_ cap: KeyCap) -> some View {
diff --git a/ios/Sources/KeyPanel.swift b/ios/Sources/KeyPanel.swift
index 6396b231..29d7dcbc 100644
--- a/ios/Sources/KeyPanel.swift
+++ b/ios/Sources/KeyPanel.swift
@@ -129,10 +129,10 @@ enum KeyPanelTab: String, CaseIterable, Identifiable {
var title: String {
switch self {
- case .keys: return "Keys"
- case .snippets: return "Snippets"
- case .history: return "History"
- case .colors: return "Colors"
+ case .keys: return tr("p.keys")
+ case .snippets: return tr("p.snippets")
+ case .history: return tr("p.history")
+ case .colors: return tr("p.colors")
}
}
}
@@ -142,6 +142,7 @@ enum KeyPanelTab: String, CaseIterable, Identifiable {
/// the prototype's `.kpanel`, on the terminal's own background.
struct KeyPanel: View {
@ObservedObject var model: TerminalModel
+ @ObservedObject private var lang = AppLanguage.shared
@Binding var tab: KeyPanelTab
@ObservedObject private var snippets = SnippetStore.shared
@ObservedObject private var history = KeyHistory.shared
@@ -156,8 +157,8 @@ struct KeyPanel: View {
var body: some View {
VStack(spacing: 0) {
HStack(spacing: 10) {
- chip("gearshape", "Customize") { showSettings = true }
- chip("doc.on.clipboard", "Paste") { model.pasteFromClipboard() }
+ chip("gearshape", tr("p.customize")) { showSettings = true }
+ chip("doc.on.clipboard", tr("paste")) { model.pasteFromClipboard() }
}
.padding(.horizontal, 10)
.padding(.top, 8)
@@ -168,7 +169,7 @@ struct KeyPanel: View {
Rectangle().fill(Color.white.opacity(0.08)).frame(height: 0.5)
- Picker("Panel", selection: $tab) {
+ Picker(tr("p.panel"), selection: $tab) {
ForEach(KeyPanelTab.allCases) { Text($0.title).tag($0) }
}
.pickerStyle(.segmented)
@@ -190,7 +191,7 @@ struct KeyPanel: View {
SettingsView(model: model, showLog: nil)
.toolbar {
ToolbarItem(placement: .confirmationAction) {
- Button("Done") { showSettings = false }
+ Button(tr("done")) { showSettings = false }
}
}
}
@@ -212,10 +213,10 @@ struct KeyPanel: View {
private var keysGrid: some View {
ScrollView {
VStack(alignment: .leading, spacing: 10) {
- block("Function", KeyCaps.functions)
- block("Navigation", KeyCaps.navigation)
- block("Symbols", KeyCaps.symbols)
- block("Control", KeyCaps.chords)
+ block(tr("k.function"), KeyCaps.functions)
+ block(tr("k.navigation"), KeyCaps.navigation)
+ block(tr("k.symbols"), KeyCaps.symbols)
+ block(tr("k.control"), KeyCaps.chords)
}
.padding(.horizontal, 10)
.padding(.vertical, 6)
@@ -262,7 +263,7 @@ struct KeyPanel: View {
.truncationMode(.middle)
.frame(maxWidth: .infinity, alignment: .leading)
if snippet.runs {
- Text("Run")
+ Text(tr("p.run"))
.font(.system(size: 12))
.foregroundColor(.accentColor)
}
@@ -287,7 +288,7 @@ struct KeyPanel: View {
Button {
draft = SnippetDraft(snippet: Snippet(text: ""), isNew: true)
} label: {
- Label("New snippet", systemImage: "plus")
+ Label(tr("snip.new"), systemImage: "plus")
.font(.system(size: 14))
.frame(maxWidth: .infinity)
.frame(height: 42)
@@ -314,7 +315,7 @@ struct KeyPanel: View {
private var historyList: some View {
ScrollView {
if history.lines.isEmpty {
- Text("Nothing sent from here yet")
+ Text(tr("hist.empty"))
.font(.system(size: 13))
.foregroundColor(.white.opacity(0.45))
.frame(maxWidth: .infinity)
@@ -351,7 +352,7 @@ struct KeyPanel: View {
private var colorRow: some View {
ScrollView(.horizontal, showsIndicators: false) {
LazyHGrid(rows: [GridItem(.fixed(62)), GridItem(.fixed(62))], spacing: 10) {
- swatch(Schemes.followDesktop, label: "Follow host")
+ swatch(Schemes.followDesktop, label: tr("followhost"))
ForEach(Schemes.names, id: \.self) { name in
swatch(name, label: name)
}
@@ -432,6 +433,7 @@ struct SnippetDraft: Identifiable {
/// One snippet's text and whether it runs itself; Delete throws it away.
struct SnippetEditor: View {
let draft: SnippetDraft
+ @ObservedObject private var lang = AppLanguage.shared
@Environment(\.dismiss) private var dismiss
@State private var text: String
@State private var runs: Bool
@@ -446,30 +448,30 @@ struct SnippetEditor: View {
NavigationStack {
Form {
Section {
- TextField("Command", text: $text, axis: .vertical)
+ TextField(tr("snip.command"), text: $text, axis: .vertical)
.font(.system(size: 14, design: .monospaced))
.lineLimit(1...6)
.autocorrectionDisabled()
.textInputAutocapitalization(.never)
- Toggle("Press Enter after sending", isOn: $runs)
+ Toggle(tr("snip.enter"), isOn: $runs)
}
if !draft.isNew {
Section {
- Button("Delete", role: .destructive) {
+ Button(tr("delete"), role: .destructive) {
SnippetStore.shared.remove(draft.snippet)
dismiss()
}
}
}
}
- .navigationTitle(draft.isNew ? "New snippet" : "Snippet")
+ .navigationTitle(draft.isNew ? tr("snip.new") : tr("snip.title"))
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .cancellationAction) {
- Button("Cancel") { dismiss() }
+ Button(tr("cancel")) { dismiss() }
}
ToolbarItem(placement: .confirmationAction) {
- Button("Save") { save() }
+ Button(tr("save")) { save() }
.disabled(text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
}
}
diff --git a/ios/Sources/Models.swift b/ios/Sources/Models.swift
index efcacad0..55008cb8 100644
--- a/ios/Sources/Models.swift
+++ b/ios/Sources/Models.swift
@@ -8,7 +8,7 @@ struct Host: Codable, Identifiable, Hashable {
case key
case password
var id: String { rawValue }
- var label: String { self == .key ? "Private key" : "Password" }
+ var label: String { self == .key ? tr("f.key") : tr("f.password") }
}
var id: UUID = UUID()
diff --git a/ios/Sources/SettingsSheet.swift b/ios/Sources/SettingsSheet.swift
index d81213dc..169deb1c 100644
--- a/ios/Sources/SettingsSheet.swift
+++ b/ios/Sources/SettingsSheet.swift
@@ -1,25 +1,29 @@
import SwiftUI
-/// The app's preferences: the terminal's colours and text size, how a
-/// drag scrolls, and the log for when something is wrong. The Settings
+/// The app's preferences, in the prototype's eight sections. 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 then the text size is the live pane's and the log is offered.
struct SettingsView: View {
@ObservedObject var settings = AppSettings.shared
+ @ObservedObject private var lang = AppLanguage.shared
var model: TerminalModel?
var showLog: Binding<Bool>?
var body: some View {
List {
- Section("Terminal") {
+ Section(tr("sec.general")) {
+ push(tr("language"), selection: $settings.language, options: Self.languages)
+ }
+
+ Section(tr("sec.appearance")) {
NavigationLink {
ThemePicker()
} label: {
HStack {
- Text("Theme")
+ Text(tr("theme"))
Spacer()
swatch(settings.schemeName)
- Text(settings.schemeName == Schemes.followDesktop ? "Follow host" : settings.schemeName)
+ Text(settings.schemeName == Schemes.followDesktop ? tr("followhost") : settings.schemeName)
.foregroundColor(.secondary)
.lineLimit(1)
}
@@ -29,7 +33,7 @@ struct SettingsView: View {
} else {
Stepper(value: $settings.fontSize, in: 6...40, step: 1) {
HStack {
- Text("Text size")
+ Text(tr("textsize"))
Spacer()
Text(String(format: "%.0f pt", settings.fontSize))
.foregroundColor(.secondary)
@@ -37,26 +41,124 @@ struct SettingsView: View {
}
}
}
- Toggle("Smooth scrolling", isOn: $settings.smoothScroll)
+ push(tr("font.family"), selection: $settings.fontFamily, options: Self.fonts)
+ push(tr("contrast"), selection: $settings.contrast, options: Self.contrasts)
+ }
+
+ Section(tr("sec.terminal")) {
+ segment(tr("scroll.mode"), isOn: $settings.smoothScroll, off: tr("scroll.stepped"), on: tr("scroll.smooth"))
+ Toggle(tr("scrollbar"), isOn: $settings.scrollbar)
+ push(tr("cursor"), selection: $settings.cursorStyle, options: Self.cursors)
+ Toggle(tr("cursor.blink"), isOn: $settings.cursorBlink)
+ Toggle(tr("bell"), isOn: $settings.bell)
+ push(tr("resize.mode"), selection: $settings.resizeMode, options: Self.resizes)
+ }
+
+ Section(tr("sec.interface")) {
+ segment(tr("i.tabbar"), selection: $settings.tabBarLevels,
+ ("one", tr("i.onelevel")), ("two", tr("i.twolevel")))
+ Toggle(tr("i.panebars"), isOn: $settings.paneBars)
+ }
+
+ Section(tr("sec.keyboard")) {
+ NavigationLink {
+ KeyBarKeys()
+ } label: {
+ HStack {
+ Text(tr("k.keybar"))
+ Spacer()
+ Text("\(KeyCaps.bar.count)").foregroundColor(.secondary)
+ }
+ }
+ Toggle(tr("k.haptics"), isOn: $settings.hapticKeys)
+ Toggle(tr("k.autopanel"), isOn: $settings.autoKeyPanel)
+ }
+
+ Section(tr("sec.gestures")) {
+ Toggle(tr("g.pinch"), isOn: $settings.pinchZoom)
+ Toggle(tr("g.twofinger"), isOn: $settings.twoFingerHidesKeyboard)
+ Toggle(tr("g.longpress"), isOn: $settings.longPressSelects)
+ }
+
+ Section(tr("sec.connection")) {
+ Toggle(tr("c.autoreconnect"), isOn: $settings.autoReconnect)
+ Stepper(value: $settings.keepAliveSeconds, in: 0...300, step: 15) {
+ HStack {
+ Text(tr("c.keepalive"))
+ Spacer()
+ Text(settings.keepAliveSeconds == 0 ? tr("off") : "\(settings.keepAliveSeconds) s")
+ .foregroundColor(.secondary)
+ .monospacedDigit()
+ }
+ }
+ Toggle(tr("c.background"), isOn: $settings.keepSessionInBackground)
}
+
if let showLog {
Section {
- Toggle("Show log", isOn: showLog)
+ Toggle(tr("showlog"), isOn: showLog)
+ Toggle(tr("devmode"), isOn: $settings.devMode)
} header: {
- Text("Diagnostics")
+ Text(tr("diagnostics"))
} footer: {
- Text("The connection's log over the terminal, for reporting a problem.")
+ Text(tr("showlog.foot"))
}
}
- Section("About") {
+
+ Section(tr("sec.about")) {
HStack {
- Text("Version")
+ Text(tr("version"))
Spacer()
Text(Self.version).foregroundColor(.secondary)
}
}
}
- .navigationTitle("Settings")
+ .navigationTitle(tr("settings"))
+ }
+
+ // MARK: rows
+
+ /// A row that pushes a one-of-these screen and shows the choice.
+ private func push(_ title: String, selection: Binding<String>, options: [PickerOption]) -> some View {
+ NavigationLink {
+ OptionPicker(title: title, options: options, selection: selection)
+ } label: {
+ HStack {
+ Text(title)
+ Spacer()
+ Text(options.first { $0.value == selection.wrappedValue }?.label ?? selection.wrappedValue)
+ .foregroundColor(.secondary)
+ .lineLimit(1)
+ }
+ }
+ }
+
+ /// The prototype's segmented row: a quiet label with the control under it.
+ private func segment(_ title: String, selection: Binding<String>,
+ _ first: (String, String), _ second: (String, String)) -> some View {
+ VStack(alignment: .leading, spacing: 7) {
+ Text(title).font(.subheadline).foregroundColor(.secondary)
+ Picker(title, selection: selection) {
+ Text(first.1).tag(first.0)
+ Text(second.1).tag(second.0)
+ }
+ .pickerStyle(.segmented)
+ .labelsHidden()
+ }
+ .padding(.vertical, 3)
+ }
+
+ private func segment(_ title: String, isOn: Binding<Bool>, off: String, on: String) -> some View {
+ VStack(alignment: .leading, spacing: 7) {
+ Text(title).font(.subheadline).foregroundColor(.secondary)
+ Picker(title, selection: isOn) {
+ Text(off).tag(false)
+ Text(on).tag(true)
+ }
+ .pickerStyle(.segmented)
+ .labelsHidden()
+ }
+ .padding(.vertical, 3)
}
@ViewBuilder
@@ -66,6 +168,38 @@ struct SettingsView: View {
}
}
+ // MARK: the choices behind the push rows
+
+ private static var languages: [PickerOption] { [
+ PickerOption("system", tr("system")),
+ PickerOption("en-US", "English"),
+ PickerOption("zh-CN", "简体中文"),
+ PickerOption("ja-JP", "日本語"),
+ PickerOption("fr-FR", "Français"),
+ PickerOption("de-DE", "Deutsch"),
+ ] }
+ // The faces in the bundle; 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 static let fonts = ["JetBrains Mono", "Fira Code"].map { PickerOption($0, $0) }
+ private static var contrasts: [PickerOption] { [
+ PickerOption("off", tr("contrast.off")),
+ PickerOption("3", tr("contrast.3")),
+ PickerOption("45", tr("contrast.45")),
+ PickerOption("7", tr("contrast.7")),
+ ] }
+ private static var cursors: [PickerOption] { [
+ PickerOption("auto", tr("cursor.auto")),
+ PickerOption("block", tr("cursor.block")),
+ PickerOption("bar", tr("cursor.bar")),
+ PickerOption("underline", tr("cursor.underline")),
+ ] }
+ private static var resizes: [PickerOption] { [
+ PickerOption("auto", tr("resize.auto")),
+ PickerOption("live", tr("resize.live")),
+ PickerOption("release", tr("resize.release")),
+ ] }
+
static var version: String {
let info = Bundle.main.infoDictionary
let short = info?["CFBundleShortVersionString"] as? String ?? "0"
@@ -74,15 +208,76 @@ struct SettingsView: View {
}
}
+/// One choice on a pushed picker screen.
+struct PickerOption: Identifiable {
+ let value: String
+ let label: String
+ var id: String { value }
+
+ init(_ value: String, _ label: String) {
+ self.value = value
+ self.label = label
+ }
+}
+
+/// The screen a push row opens: the choices, the current one ticked.
+struct OptionPicker: View {
+ let title: String
+ @ObservedObject private var lang = AppLanguage.shared
+ let options: [PickerOption]
+ @Binding var selection: String
+
+ var body: some View {
+ List {
+ ForEach(options) { option in
+ Button {
+ selection = option.value
+ } label: {
+ HStack {
+ Text(option.label).foregroundColor(.primary)
+ Spacer()
+ if selection == option.value {
+ Image(systemName: "checkmark").foregroundColor(.accentColor)
+ }
+ }
+ }
+ }
+ }
+ .navigationTitle(title)
+ .navigationBarTitleDisplayMode(.inline)
+ }
+}
+
+/// What the key bar carries, in its order. Read-only for now: the bar is
+/// not editable yet.
+struct KeyBarKeys: View {
+ @ObservedObject private var lang = AppLanguage.shared
+
+ var body: some View {
+ List {
+ Section {
+ ForEach(KeyCaps.bar) { cap in
+ Text(cap.label).font(.system(.body, design: .monospaced))
+ }
+ } footer: {
+ Text(tr("k.keybar.foot"))
+ }
+ }
+ .navigationTitle(tr("k.keybar"))
+ .navigationBarTitleDisplayMode(.inline)
+ }
+}
+
/// The open terminal's text size, stepped live; the size a new
/// connection starts at follows it.
private struct LiveTextSize: View {
@ObservedObject var model: TerminalModel
@ObservedObject var settings = AppSettings.shared
+ @ObservedObject private var lang = AppLanguage.shared
var body: some View {
HStack {
- Text("Text size")
+ Text(tr("textsize"))
Spacer()
Button { step(-1) } label: { Image(systemName: "textformat.size.smaller") }
.buttonStyle(.bordered)
@@ -104,6 +299,7 @@ private struct LiveTextSize: View {
/// swatch; the host's own scheme first.
struct ThemePicker: View {
@ObservedObject var settings = AppSettings.shared
+ @ObservedObject private var lang = AppLanguage.shared
@State private var query = ""
private var names: [String] {
@@ -115,14 +311,14 @@ struct ThemePicker: View {
var body: some View {
List {
if query.isEmpty {
- row(Schemes.followDesktop, label: "Follow host", color: nil)
+ row(Schemes.followDesktop, label: tr("followhost"), color: nil)
}
ForEach(names, id: \.self) { name in
row(name, label: name, color: Schemes.background(of: name))
}
}
- .searchable(text: $query, prompt: "Search schemes")
- .navigationTitle("Theme")
+ .searchable(text: $query, prompt: tr("theme.search"))
+ .navigationTitle(tr("theme"))
.navigationBarTitleDisplayMode(.inline)
}
diff --git a/ios/Sources/TerminalInputView.swift b/ios/Sources/TerminalInputView.swift
index 8b8c60d4..57ea1653 100644
--- a/ios/Sources/TerminalInputView.swift
+++ b/ios/Sources/TerminalInputView.swift
@@ -1,3 +1,4 @@
+import Combine
import SwiftUI
import UIKit
@@ -40,6 +41,13 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDel
/// the core last gave them. Fetched when a selection interaction asks
/// and dropped when the core reports a change.
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)
+ /// 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?
+ private var selectionWatch: AnyCancellable?
override init(frame: CGRect) {
super.init(frame: frame)
@@ -58,16 +66,35 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDel
let hide = UISwipeGestureRecognizer(target: self, action: #selector(swipedDown(_:)))
hide.direction = .down
hide.numberOfTouchesRequired = 2
- for g in [tap, pinch, hide] as [UIGestureRecognizer] {
+ // Ours never hold the system's back: the touches go on to the text
+ // interaction's recognizers whatever ours decide.
+ tap.cancelsTouchesInView = false
+ tap.delaysTouchesEnded = false
+ // A sideways flick goes to the next or previous tab. The scroll
+ // view only moves vertically, so a horizontal pan is nobody's.
+ let flick = UIPanGestureRecognizer(target: self, action: #selector(flicked(_:)))
+ flick.maximumNumberOfTouches = 1
+ flick.cancelsTouchesInView = false
+ for g in [tap, pinch, hide, flick] as [UIGestureRecognizer] {
g.delegate = self
addGestureRecognizer(g)
}
- // The system's selection: a long press selects a word and shows
- // the handles, a tap elsewhere clears it. Non-editable, so a tap
- // does not place a caret -- the terminal's cursor is its own.
- let selection = UITextInteraction(for: .nonEditable)
+ // The system's text editing over the rows, the way every editable
+ // text view has it: a tap raises the keyboard, a double tap selects
+ // a word and shows the handles, a long press the loupe. The caret
+ // it places is kept but not drawn; the terminal's cursor is its own.
selection.textInput = self
- addInteraction(selection)
+ // The setting decides whether it is attached at all; the publisher
+ // hands over the value it holds now, so this also starts it right.
+ selectionWatch = AppSettings.shared.$longPressSelects.sink { [weak self] on in
+ guard let self else { return }
+ let attached = self.interactions.contains { $0 === self.selection }
+ if on, !attached {
+ self.addInteraction(self.selection)
+ } else if !on, attached {
+ self.removeInteraction(self.selection)
+ }
+ }
}
override func layoutSubviews() {
@@ -144,13 +171,27 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDel
}
}
+ @objc private func flicked(_ g: UIPanGestureRecognizer) {
+ guard g.state == .ended else { return }
+ let t = g.translation(in: self)
+ let v = g.velocity(in: self)
+ guard abs(t.x) > 70, abs(t.y) < 50, abs(v.x) > 400, abs(v.x) > abs(v.y) * 2 else { return }
+ model?.switchTab(by: t.x < 0 ? 1 : -1)
+ }
+
@objc private func swipedDown(_ g: UISwipeGestureRecognizer) {
+ // Read the setting as the gesture fires, so turning it off in
+ // Settings takes hold without rebuilding the view.
+ guard AppSettings.shared.twoFingerHidesKeyboard else { return }
if isFirstResponder {
resignFirstResponder()
}
}
@objc private func pinched(_ g: UIPinchGestureRecognizer) {
+ // Same as the swipe: the recognizer stays, the setting decides
+ // here, so a change applies to the very next pinch.
+ guard AppSettings.shared.pinchZoom else { return }
switch g.state {
case .began: pinchStart = 1
case .changed:
@@ -171,6 +212,14 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDel
true
}
+ func gestureRecognizer(_ a: UIGestureRecognizer, shouldRequireFailureOf b: UIGestureRecognizer) -> Bool {
+ false
+ }
+
+ func gestureRecognizer(_ a: UIGestureRecognizer, shouldBeRequiredToFailBy b: UIGestureRecognizer) -> Bool {
+ false
+ }
+
override var canBecomeFirstResponder: Bool { true }
// MARK: composition bookkeeping
@@ -311,25 +360,31 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDel
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 caret, caret <= screenLength {
+ return Range(caret, caret)
+ }
let n = documentLength
return Range(n, n)
}
set {
guard let r = newValue as? Range else {
+ caret = nil
model?.core.clearSelection()
screen = nil
return
}
- // A non-empty range inside the rows is a selection; anything
- // else (a caret) clears it. The end is exclusive here and
- // inclusive in the core.
+ // 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) {
+ 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
}
} else {
+ caret = r.a < screenLength ? r.a : nil
model?.core.clearSelection()
if var s = screen {
s.selection = nil
@@ -442,10 +497,17 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDel
return rect(row: a.row, col: a.col, cols: max(cols, 1))
}
+ /// Where the caret would be: the cell, but nothing wide enough to
+ /// see -- the terminal draws its own cursor, and a second one over a
+ /// tapped cell would only mislead.
func caretRect(for position: UITextPosition) -> CGRect {
- guard let p = position as? Pos, let c = cell(at: p.i) else { return model?.cursorRect ?? .zero }
+ guard let p = position as? Pos, let c = cell(at: p.i) else {
+ var r = model?.cursorRect ?? .zero
+ r.size.width = 0
+ return r
+ }
var r = rect(row: c.row, col: c.col)
- r.size.width = 2
+ r.size.width = 0
return r
}
diff --git a/ios/Sources/TerminalModel.swift b/ios/Sources/TerminalModel.swift
index 3549710e..570d5afa 100644
--- a/ios/Sources/TerminalModel.swift
+++ b/ios/Sources/TerminalModel.swift
@@ -16,6 +16,9 @@ import CoreGraphics
final class TerminalModel: ObservableObject, @unchecked Sendable {
// The App's views, refreshed when the core says something changed.
@Published var tabs: TabsView?
+ @Published var threads: ThreadsView?
+ /// The last rows of panes the overview asked about, by pane.
+ @Published var previews: [Int: [PreviewRow]] = [:]
@Published var sidebar: SidebarView?
@Published var navs: [NavView] = []
@Published var status: StatusView?
@@ -42,6 +45,14 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {
@Published var background = Color(white: 0.11)
/// The App's font size in points, from its layout view.
@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 scrollShown = false
+ private var scrollTimer: Timer?
+ /// The background task that holds the connection after the app leaves
+ /// the screen, for as long as iOS allows.
+ private var backgroundTask: UIBackgroundTaskIdentifier = .invalid
@Published var animating = false
/// The log view is open: the stats are worth refreshing.
var wantsStats = false
@@ -108,10 +119,25 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {
applyScheme()
settings.$schemeName.dropFirst().sink { [weak self] _ in self?.applyScheme() }.store(in: &subscriptions)
settings.$smoothScroll.dropFirst().sink { [weak self] _ in self?.applyScrollMode() }.store(in: &subscriptions)
+ applyTerminalPrefs()
+ settings.$cursorStyle.dropFirst().sink { [weak self] _ in self?.applyTerminalPrefs() }.store(in: &subscriptions)
+ settings.$cursorBlink.dropFirst().sink { [weak self] _ in self?.applyTerminalPrefs() }.store(in: &subscriptions)
+ settings.$contrast.dropFirst().sink { [weak self] _ in self?.applyTerminalPrefs() }.store(in: &subscriptions)
+ settings.$resizeMode.dropFirst().sink { [weak self] _ in self?.applyTerminalPrefs() }.store(in: &subscriptions)
+ settings.$autoReconnect.dropFirst().sink { [weak self] _ in self?.applyTerminalPrefs() }.store(in: &subscriptions)
+ settings.$paneBars.dropFirst().sink { [weak self] _ in self?.applyTerminalPrefs() }.store(in: &subscriptions)
+ // A face is shaped at connect time: the connection is made again.
+ settings.$fontFamily.dropFirst().removeDuplicates().sink { [weak self] _ in
+ guard let self, self.connection.hasPrefix("pane ") else { return }
+ self.disconnect()
+ self.connect()
+ }.store(in: &subscriptions)
+ settings.$devMode.sink { [weak self] on in self?.wantsStats = on || (self?.wantsStats ?? false) }.store(in: &subscriptions)
if args.contains("--autotest") { scheduleAutotest() }
if args.contains("--autoconnect") { scheduleAutoconnect() }
if args.contains("--imetest") { scheduleImeTest() }
if args.contains("--seltest") { scheduleSelectionTest() }
+ if args.contains("--treetest") { scheduleTreeTest() }
if args.contains("--uitest") { scheduleUiTest() }
}
@@ -125,8 +151,10 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {
// MARK: connection
+ /// The chosen face first, the symbols fallback after it.
var fontPaths: [String] {
- ["JetBrainsMono-Regular", "SymbolsNerdFontMono-Regular"].compactMap {
+ let face = settings.fontFamily == "Fira Code" ? "FiraCode-Regular" : "JetBrainsMono-Regular"
+ return [face, "SymbolsNerdFontMono-Regular"].compactMap {
Bundle.main.path(forResource: $0, ofType: "ttf")
}
}
@@ -174,7 +202,8 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {
core.connect(
host: hostname, port: UInt16(clamping: port), user: user,
authKind: authKind, secret: secret, passphrase: passphrase, knownHost: knownHost,
- remoteCommand: remoteCommand, deviceId: Self.deviceId, fontPaths: paths, sizePt: settings.fontSize,
+ remoteCommand: remoteCommand, deviceId: Self.deviceId, keepaliveSecs: UInt32(max(settings.keepAliveSeconds, 0)),
+ fontPaths: paths, sizePt: settings.fontSize,
painter: CoreTextPainter()
)
}
@@ -260,6 +289,40 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {
core.setSetting(key: "scroll-mode", value: smoothScroll ? "\"smooth\"" : "\"stepped\"")
}
+ /// The preferences the shared App honours, as its JSON values.
+ private func applyTerminalPrefs() {
+ let style = ["auto", "block", "bar", "underline"].contains(settings.cursorStyle) ? settings.cursorStyle : "auto"
+ core.setSetting(key: "cursor-style", value: "\"\(style)\"")
+ core.setSetting(key: "cursor-blink", value: settings.cursorBlink ? "true" : "false")
+ let contrast: Double = ["3": 3, "45": 4.5, "7": 7][settings.contrast] ?? 0
+ core.setSetting(key: "min-contrast", value: String(contrast))
+ core.setSetting(key: "resize-mode", value: settings.resizeMode == "release" ? "\"release\"" : "\"live\"")
+ core.setSetting(key: "auto-reconnect", value: settings.autoReconnect ? "true" : "false")
+ core.setSetting(key: "pane-bars", value: settings.paneBars ? "true" : "false")
+ }
+
+ /// The tab `by` places along the strip from the current one, shown.
+ func switchTab(by: Int) {
+ guard let tabs = tabs?.tabs, !tabs.isEmpty,
+ let at = tabs.firstIndex(where: { $0.current }) else { return }
+ let next = at + by
+ guard tabs.indices.contains(next) else { return }
+ chromeClick("pane", pane: tabs[next].target)
+ }
+
+ /// The last rows of a pane, for a thumbnail; `previews` fills in.
+ func requestPreview(pane: Int, rows: Int = 8) {
+ core.requestPreview(pane: UInt32(pane), rows: UInt32(rows))
+ }
+
+ /// A pane rang its bell: a buzz, if the setting says so.
+ fileprivate func coreBell() {
+ DispatchQueue.main.async {
+ guard self.settings.bell else { return }
+ UINotificationFeedbackGenerator().notificationOccurred(.warning)
+ }
+ }
+
func stepFont(_ by: Double) { core.stepFont(by: by) }
// MARK: the App's chrome
@@ -303,6 +366,8 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {
if tabs != self.tabs { self.tabs = tabs }
let sidebar = ViewJSON.decode(SidebarView.self, core.view(name: "sidebar"))
if sidebar != self.sidebar { self.sidebar = sidebar }
+ let threads = ViewJSON.decode(ThreadsView.self, core.view(name: "threads"))
+ if threads != self.threads { self.threads = threads }
let navs = ViewJSON.decode([NavView].self, core.view(name: "navs")) ?? []
if navs != self.navs { self.navs = navs }
let status = ViewJSON.decode(StatusView.self, core.view(name: "status"))
@@ -316,6 +381,18 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {
let parts = layout[r.upperBound..<end].split(separator: ",")
if parts.count == 2, let h = Double(parts[1]), h > 0 { cellHeight = h }
}
+ 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 {
+ scroll = (a, b)
+ scrollShown = true
+ scrollTimer?.invalidate()
+ scrollTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) { [weak self] _ in
+ self?.scrollShown = false
+ }
+ }
+ }
if let r = layout.range(of: "\"font_pt\":"),
let end = layout[r.upperBound...].firstIndex(where: { $0 == "," || $0 == "}" }),
let pt = Double(layout[r.upperBound..<end]), pt > 0, pt != fontPt {
@@ -372,9 +449,28 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {
func detachForBackground() {
detach()
report("background")
+ if settings.keepSessionInBackground {
+ // iOS grants about half a minute; the socket lives that long.
+ backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "thinkterm-connection") { [weak self] in
+ self?.endBackgroundTask()
+ }
+ } else if connection.hasPrefix("pane ") {
+ disconnect()
+ }
+ }
+
+ private func endBackgroundTask() {
+ if backgroundTask != .invalid {
+ UIApplication.shared.endBackgroundTask(backgroundTask)
+ backgroundTask = .invalid
+ }
}
func reattachAfterBackground() {
+ endBackgroundTask()
+ if !settings.keepSessionInBackground, connection.hasPrefix("disconnected") {
+ connect()
+ }
guard wantsSurface, generation == 0, let layer, let size = drawableSize(of: layer) else { return }
attach(layer, width: size.0, height: size.1, scale: size.2)
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { self.report("foreground") }
@@ -569,6 +665,40 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {
/// The native selection's document against the core: the rows read
/// back, a programmatic selection lands in the core and copies.
+ /// Threads on a bare server: a project, two threads in it, and the
+ /// two-level strip that follows.
+ private func scheduleTreeTest() {
+ let q = DispatchQueue.main
+ var project: String?
+ q.asyncAfter(deadline: .now() + 1.5) { self.connectProbe() }
+ q.asyncAfter(deadline: .now() + 4.0) { self.sideClick("new-project") }
+ q.asyncAfter(deadline: .now() + 4.6) { self.sideKey("Enter", value: "/tmp/ttp-srv") }
+ q.asyncAfter(deadline: .now() + 6.5) {
+ self.refreshViews()
+ project = self.sidebar?.rows.compactMap { row -> String? in
+ if case .project(let id, _, _, _, false) = row { return id }
+ return nil
+ }.first
+ self.check("project made", project != nil, self.sidebar?.new_project_error ?? "\(self.sidebar?.rows.count ?? -1) rows")
+ if let project { self.sideClick("new-thread", id: project) }
+ }
+ q.asyncAfter(deadline: .now() + 9.5) {
+ self.refreshViews()
+ let threads = self.threads?.threads ?? []
+ self.check("thread listed", threads.count >= 1, "\(threads.count) threads")
+ self.check("thread current with a tab", threads.contains { $0.current && !$0.tabs.isEmpty }, threads.map { "\($0.name):\($0.tabs.count):\($0.current)" }.joined(separator: " "))
+ if let project { self.sideClick("new-thread", id: project) }
+ }
+ q.asyncAfter(deadline: .now() + 12.5) {
+ self.refreshViews()
+ let threads = self.threads?.threads ?? []
+ self.check("second thread", threads.count >= 2, "\(threads.count) threads")
+ self.check("one current", threads.filter(\.current).count == 1, threads.map { "\($0.name):\($0.current)" }.joined(separator: " "))
+ self.report("tree done")
+ print("TREETEST DONE")
+ }
+ }
+
private func scheduleSelectionTest() {
let q = DispatchQueue.main
q.asyncAfter(deadline: .now() + 1.5) { self.connectProbe() }
@@ -714,6 +844,11 @@ private final class NotifySink: Notify, @unchecked Sendable {
}
func onHostKey(fingerprint: String) { model?.coreHostKey(fingerprint) }
func onPublished(key: String, value: String) { model?.corePublished(key, value) }
+ func onBell() { model?.coreBell() }
+ func onPreview(pane: UInt32, rows: String) {
+ let decoded = ViewJSON.decode([PreviewRow].self, rows) ?? []
+ DispatchQueue.main.async { self.model?.previews[Int(pane)] = decoded }
+ }
}
/// Paints the graphemes the bundled faces lack with CoreText, which falls
diff --git a/ios/Sources/TerminalScreen.swift b/ios/Sources/TerminalScreen.swift
index 98c50381..f435af68 100644
--- a/ios/Sources/TerminalScreen.swift
+++ b/ios/Sources/TerminalScreen.swift
@@ -4,16 +4,31 @@ import SwiftUI
/// key bar, and the sidebar and menus as sheets.
struct TerminalScreen: View {
@StateObject private 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 showSidebar = false
- @State private var showSessions = false
+ @State private var showTree = false
@State private var showLog = false
@State private var showSettings = false
@State private var menu: MenuSheet?
@State private var editingHost: Host?
/// A bar being dragged moves the divider it hangs from.
@State private var barDrag: CGPoint?
+ /// The bar's width, for the strip in its middle: a principal item is
+ /// centred and clipped when wider than its slot, so it is sized.
+ @State private var barWidth: CGFloat = 402
+ /// The software keyboard is up: the key bar shows with it.
+ @State private var keyboardUp = false
+ /// 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.
+ @State private var overviewOpen = false
+ @State private var overviewShown = false
+ @State private var terminalFrame: CGRect = .zero
+ @State private var cardFrame: CGRect?
+ @State private var zoomScale: CGFloat = 1
+ @State private var zoomOffset: CGSize = .zero
+ @State private var zoomClip: CGFloat?
init(host: Host?, store: HostStore?) {
_model = StateObject(wrappedValue: TerminalModel(host: host, store: store))
@@ -23,33 +38,80 @@ struct TerminalScreen: View {
/// button and the menu; the keys sit below the terminal, and nothing
/// else. Every piece of chrome takes the terminal's own background.
var body: some View {
- VStack(spacing: 0) {
- terminal
- statusLine
- KeyBar(model: model)
+ ZStack(alignment: .topLeading) {
+ if overviewShown {
+ OverviewScreen(model: model, isPresented: $overviewShown, cardFrame: $cardFrame, liveThread: currentThreadId)
+ .opacity(overviewOpen ? 1 : 0)
+ .onChange(of: overviewShown) { _, shown in if !shown { closeOverview() } }
+ }
+ // Above the cards, so the shrunken terminal shows in its card;
+ // untouchable meanwhile, so the cards get the taps.
+ VStack(spacing: 0) {
+ if twoLevel {
+ tabSubstrip.opacity(overviewOpen ? 0 : 1)
+ }
+ terminal
+ .background(GeometryReader { geo in
+ Color.clear
+ .onAppear { terminalFrame = geo.frame(in: .named("screen")) }
+ .onChange(of: geo.frame(in: .named("screen"))) { _, f in terminalFrame = f }
+ })
+ .mask(alignment: .top) {
+ Rectangle().frame(height: zoomClip)
+ }
+ .scaleEffect(zoomScale, anchor: .topLeading)
+ .offset(zoomOffset)
+ .zIndex(2)
+ .allowsHitTesting(!overviewOpen)
+ statusLine.opacity(overviewOpen ? 0 : 1)
+ if keyboardUp && !overviewOpen {
+ KeyBar(model: model)
+ .transition(.move(edge: .bottom).combined(with: .opacity))
+ }
+ }
+ .animation(.easeOut(duration: 0.2), value: keyboardUp)
+ .zIndex(1)
+ .allowsHitTesting(!overviewOpen)
+ }
+ .coordinateSpace(name: "screen")
+ .background(overviewOpen ? Color(white: 0.06) : model.background)
+ .background(GeometryReader { geo in
+ Color.clear.onAppear { barWidth = geo.size.width }
+ .onChange(of: geo.size.width) { _, w in barWidth = w }
+ })
+ .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)) { note in
+ let frame = (note.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect) ?? .zero
+ keyboardUp = frame.height > 0
+ }
+ .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)) { _ in
+ keyboardUp = false
+ }
+ .onChange(of: cardFrame) { _, frame in
+ // The card's thumbnail is laid out: the terminal goes there.
+ if overviewShown, let frame, !overviewOpen { zoom(into: frame) }
}
- .background(model.background)
.navigationBarTitleDisplayMode(.inline)
.toolbar(.hidden, for: .tabBar)
.toolbarBackground(model.background, for: .navigationBar)
.toolbarBackground(.visible, for: .navigationBar)
.toolbar {
- ToolbarItem(placement: .principal) { tabStrip }
- ToolbarItem(placement: .topBarTrailing) { moreMenu }
+ ToolbarItem(placement: .principal) { tabStrip.frame(width: max(barWidth - 190, 120)) }
+ ToolbarItemGroup(placement: .topBarTrailing) {
+ Button { if overviewShown { overviewShown = false } else { openOverview() } } label: {
+ Image(systemName: "square.grid.2x2")
+ }
+ moreMenu
+ }
}
.ignoresSafeArea(.container, edges: .bottom)
- .sheet(isPresented: $showSidebar) {
- SidebarSheet(model: model, isPresented: $showSidebar)
- }
- .sheet(isPresented: $showSessions) {
- SessionsSheet(model: model, isPresented: $showSessions, menu: $menu, showSidebar: $showSidebar)
- .presentationDetents([.medium, .large])
+ .sheet(isPresented: $showTree) {
+ TreeSheet(model: model, isPresented: $showTree, menu: $menu)
}
.sheet(isPresented: $showSettings) {
NavigationStack {
SettingsView(model: model, showLog: $showLog)
.toolbar {
- ToolbarItem(placement: .confirmationAction) { Button("Done") { showSettings = false } }
+ ToolbarItem(placement: .confirmationAction) { Button(tr("done")) { showSettings = false } }
}
}
}
@@ -69,9 +131,19 @@ struct TerminalScreen: View {
}
.onAppear {
// The automated flows connect on their own schedule.
- if !ProcessInfo.processInfo.arguments.contains(where: { $0.hasSuffix("test") || $0 == "--autoconnect" }) {
+ let args = ProcessInfo.processInfo.arguments
+ if !args.contains(where: { $0.hasSuffix("test") || $0 == "--autoconnect" }) {
model.connect()
}
+ #if DEBUG
+ // Screenshots of the sheets, which no script can tap open.
+ if args.contains("--open-tree") {
+ DispatchQueue.main.asyncAfter(deadline: .now() + 14) { showTree = true }
+ }
+ if args.contains("--open-overview") {
+ DispatchQueue.main.asyncAfter(deadline: .now() + 14) { openOverview() }
+ }
+ #endif
}
.onDisappear {
model.shutdown()
@@ -92,7 +164,7 @@ struct TerminalScreen: View {
}
private var hostName: String {
- model.host?.display ?? "This Mac"
+ model.host?.display ?? tr("thismac")
}
private var statusColor: Color {
@@ -102,72 +174,213 @@ struct TerminalScreen: View {
return .red
}
- /// The connection's state and the tabs, in the bar's middle.
+ /// The desktop's two layers, as two rows: threads (the sidebar's
+ /// layer, one per workspace) in the navigation bar, the current
+ /// thread's tabs in a strip under it. A server without threads (no
+ /// session state) shows its tabs in the bar instead.
+ private var twoLevel: Bool { settings.tabBarLevels == "two" && !(model.threads?.threads.isEmpty ?? true) }
+
private var tabStrip: some View {
HStack(spacing: 6) {
Circle().fill(statusColor).frame(width: 7, height: 7)
+ ScrollViewReader { reader in
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 4) {
- ForEach(model.tabs?.tabs ?? []) { tab in
- Button {
- model.chromeClick("pane", pane: tab.target)
- } label: {
- Text(tab.label.isEmpty ? "Tab \(tab.tab)" : tab.label)
- .font(.system(size: 12, weight: tab.current ? .semibold : .regular))
- .lineLimit(1)
+ if twoLevel {
+ ForEach(model.threads?.threads ?? []) { thread in
+ Button {
+ // The one on show opens the tree; another is shown.
+ if thread.current { showTree = true } else { model.sideClick("thread", id: thread.id) }
+ } label: {
+ HStack(spacing: 5) {
+ Circle().fill(threadColor(thread)).frame(width: 6, height: 6)
+ Text(thread.name)
+ .font(.system(size: 12, weight: thread.current ? .semibold : .regular))
+ .lineLimit(1)
+ }
.padding(.horizontal, 10)
- .padding(.vertical, 5)
- .background(tab.current ? Color.white.opacity(0.18) : Color.white.opacity(0.06))
+ .frame(minWidth: 64, minHeight: 26)
+ .background(thread.current ? Color.white.opacity(0.18) : Color.white.opacity(0.06))
.clipShape(Capsule())
+ }
+ .buttonStyle(.plain)
+ .contextMenu {
+ AppMenuItems(model: model, kind: "thread", id: thread.id)
+ }
+ .id("thread:" + thread.id)
}
- .buttonStyle(.plain)
- .contextMenu {
- Button("Close tab", role: .destructive) { model.chromeClick("close-tab", tab: tab.tab) }
- Button("More…") { menu = MenuSheet(kind: "tab", id: String(tab.tab), title: "Tab") }
+ Button { model.sideClick("new-thread") } label: {
+ Image(systemName: "plus").font(.system(size: 13, weight: .semibold)).padding(6)
+ .foregroundColor(Color.white.opacity(0.62))
}
+ .buttonStyle(.plain)
+ } else {
+ tabPills(size: 12, height: 26)
+ newTabButton
}
- Button { model.chromeClick("new-tab") } label: {
- Image(systemName: "plus").font(.system(size: 13, weight: .semibold)).padding(6)
+ }
+ }
+ .onChange(of: model.threads?.threads.first(where: { $0.current })?.id) { _, id in
+ if let id { reader.scrollTo("thread:" + id, anchor: .center) }
+ }
+ .onChange(of: model.tabs?.tabs.first(where: { $0.current })?.tab) { _, tab in
+ if let tab, !twoLevel { reader.scrollTo("tab:\(tab)", anchor: .center) }
+ }
+ }
+ }
+ .foregroundColor(.white)
+ }
+
+ /// The current thread's tabs, under the bar.
+ private var tabSubstrip: some View {
+ HStack(spacing: 4) {
+ ScrollViewReader { reader in
+ ScrollView(.horizontal, showsIndicators: false) {
+ HStack(spacing: 4) {
+ tabPills(size: 11.5, height: 22)
}
- .buttonStyle(.plain)
+ }
+ .onChange(of: model.tabs?.tabs.first(where: { $0.current })?.tab) { _, tab in
+ if let tab { reader.scrollTo("tab:\(tab)", anchor: .center) }
}
}
+ newTabButton
}
.foregroundColor(.white)
+ .padding(.horizontal, 8)
+ .frame(height: 32)
+ .contentShape(Rectangle())
+ // Pinching the strip zooms out to the overview.
+ .gesture(MagnifyGesture().onEnded { value in
+ if value.magnification < 0.8 { openOverview() }
+ })
+ .background(model.background)
+ }
+
+ private func tabPills(size: CGFloat, height: CGFloat) -> some View {
+ ForEach(model.tabs?.tabs ?? []) { tab in
+ Button {
+ model.chromeClick("pane", pane: tab.target)
+ } label: {
+ Text(tab.label.isEmpty ? tr("tab.num", tab.tab) : tab.label)
+ .font(.system(size: size, weight: tab.current ? .semibold : .regular))
+ .lineLimit(1)
+ .padding(.horizontal, 10)
+ .frame(minWidth: 76, maxWidth: 140, minHeight: height)
+ .foregroundColor(tab.current ? .white : Color.white.opacity(0.62))
+ .background(tab.current ? Color.white.opacity(0.18) : Color.white.opacity(0.06))
+ .clipShape(Capsule())
+ }
+ .buttonStyle(.plain)
+ .contextMenu {
+ AppMenuItems(model: model, kind: "tab", id: String(tab.tab))
+ }
+ .id("tab:\(tab.tab)")
+ }
+ }
+
+ private var newTabButton: some View {
+ Button { model.chromeClick("new-tab") } label: {
+ Image(systemName: "plus").font(.system(size: 13, weight: .semibold)).padding(6)
+ .foregroundColor(Color.white.opacity(0.62))
+ }
+ .buttonStyle(.plain)
}
+ static func threadColor(status: String, live: Bool) -> Color {
+ switch status {
+ case "Running": return .green
+ case "NeedsAttention": return .orange
+ case "Done": return .blue
+ default: return live ? .gray : .gray.opacity(0.4)
+ }
+ }
+
+ private func threadColor(_ t: ThreadView) -> Color { Self.threadColor(status: t.status, live: t.live) }
+
private var moreMenu: some View {
Menu {
Section(hostName) {
- Button(connected ? "Disconnect" : "Reconnect") {
+ Button(connected ? tr("disconnect") : tr("reconnect")) {
if connected { model.disconnect() } else { model.connect() }
}
}
- Button("Split right") { model.chromeClick("split-right") }
- Button("Split below") { model.chromeClick("split-below") }
- Button("Zoom pane") { model.chromeClick("zoom") }
- Button("Pane…") { menu = MenuSheet(kind: "pane", id: String(model.tabs?.tabs.first(where: { $0.current })?.target ?? 0), title: "Pane") }
+ Button(tr("split.right")) { model.chromeClick("split-right") }
+ Button(tr("split.below")) { model.chromeClick("split-below") }
+ Button(tr("zoom")) { model.chromeClick("zoom") }
+ Button(tr("pane")) { menu = MenuSheet(kind: "pane", id: String(model.tabs?.tabs.first(where: { $0.current })?.target ?? 0), title: tr("pane.title")) }
Divider()
- Button("Sessions…") { showSessions = true }
- Button("Threads…") { showSidebar = true }
- Button("Paste") { model.pasteFromClipboard() }
+ Button(tr("m.threadstabs")) { showTree = true }
+ Button(tr("m.overview")) { openOverview() }
+ Button(tr("paste")) { model.pasteFromClipboard() }
Divider()
- Button("Settings…") { showSettings = true }
- Button("Close pane", role: .destructive) { model.chromeClick("close") }
+ Button(tr("m.settings")) { showSettings = true }
+ Button(tr("closepane"), role: .destructive) { model.chromeClick("close") }
} label: {
Image(systemName: "ellipsis")
}
}
+ // MARK: the overview's zoom
+
+ private var currentThreadId: String? { model.threads?.threads.first(where: { $0.current })?.id }
+
+ private func openOverview() {
+ guard !overviewShown else { return }
+ model.refreshViews()
+ cardFrame = nil
+ overviewShown = true
+ // Without a card of its own (no threads, or none current) the
+ // terminal only fades.
+ if currentThreadId == nil {
+ withAnimation(.easeOut(duration: 0.25)) { overviewOpen = true }
+ }
+ }
+
+ /// Shrink the terminal into the card's thumbnail: scaled to its
+ /// width, moved to its corner, and masked to its height.
+ private func zoom(into frame: CGRect) {
+ guard terminalFrame.width > 0 else { return }
+ let scale = frame.width / terminalFrame.width
+ withAnimation(.spring(response: 0.4, dampingFraction: 0.85)) {
+ overviewOpen = true
+ zoomScale = scale
+ zoomOffset = CGSize(width: frame.minX - terminalFrame.minX, height: frame.minY - terminalFrame.minY)
+ zoomClip = frame.height / scale
+ }
+ }
+
+ private func closeOverview() {
+ withAnimation(.spring(response: 0.35, dampingFraction: 0.9)) {
+ overviewOpen = false
+ zoomScale = 1
+ zoomOffset = .zero
+ zoomClip = nil
+ }
+ cardFrame = nil
+ }
+
// MARK: the terminal with its overlays
private var terminal: some View {
ZStack(alignment: .topLeading) {
MetalView()
TerminalInput()
- if model.navs.count > 1 {
+ if model.navs.count > 1 && settings.paneBars {
navBars
}
+ if settings.scrollbar && model.scroll.1 > 0 && model.scrollShown {
+ scrollbar
+ }
+ if settings.devMode {
+ Text(model.stats)
+ .font(.system(size: 8, design: .monospaced))
+ .foregroundColor(.white.opacity(0.7))
+ .padding(4)
+ .background(Color.black.opacity(0.5))
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomLeading)
+ .allowsHitTesting(false)
+ }
if let composing = model.composing {
Text(composing)
.font(.system(size: 14, design: .monospaced))
@@ -182,6 +395,15 @@ struct TerminalScreen: View {
if showLog {
logView
}
+ if model.reconnecting && !settings.autoReconnect && ConnectionPhase(status: model.connection) == nil {
+ // Asked not to redial: the card offers it instead.
+ ConnectionCard(phase: .disconnected, hostName: hostName, canEdit: model.host != nil) { action in
+ switch action {
+ case .back: dismiss()
+ default: model.connect()
+ }
+ }
+ }
if let phase = ConnectionPhase(status: model.connection) {
ConnectionCard(phase: phase, hostName: hostName, canEdit: model.host != nil) { action in
switch action {
@@ -204,6 +426,24 @@ struct TerminalScreen: View {
.background(model.background)
}
+ /// A thin bar at the right: where the view is in the scrollback.
+ private var scrollbar: some View {
+ GeometryReader { geo in
+ let (above, max) = model.scroll
+ let total = CGFloat(max) + geo.size.height / Swift.max(model.cellHeight, 1)
+ let visible = geo.size.height / Swift.max(model.cellHeight, 1)
+ let thumb = Swift.max(geo.size.height * visible / Swift.max(total, 1), 24)
+ let track = geo.size.height - thumb
+ let y = track * (1 - CGFloat(above) / CGFloat(Swift.max(max, 1)))
+ RoundedRectangle(cornerRadius: 2)
+ .fill(Color.white.opacity(0.35))
+ .frame(width: 3, height: thumb)
+ .offset(x: geo.size.width - 6, y: y)
+ }
+ .allowsHitTesting(false)
+ .transition(.opacity)
+ }
+
/// The App leaves rows above each pane for its bar; these draw it,
/// where the App says (points, from the terminal's origin).
private var navBars: some View {
@@ -255,8 +495,8 @@ struct TerminalScreen: View {
.background(model.background)
.background(Color.white.opacity(nav.focused ? 0.1 : 0.04))
.contentShape(Rectangle())
- .onLongPressGesture {
- menu = MenuSheet(kind: "pane", id: String(nav.rect.pane), title: "Pane")
+ .contextMenu {
+ AppMenuItems(model: model, kind: "pane", id: String(nav.rect.pane))
}
.gesture(barDragGesture(nav))
.offset(x: nav.rect.left, y: nav.rect.top)
@@ -322,7 +562,7 @@ struct TerminalScreen: View {
@ViewBuilder
private var statusLine: some View {
- let text = model.copied ? "Copied" : (model.toastText ?? "")
+ let text = model.copied ? tr("copied") : (model.toastText ?? "")
let showing = !text.isEmpty || model.connection.hasPrefix("connecting") || model.connection.hasPrefix("disconnected") || model.connection.hasPrefix("failed") || model.connection.contains("reconnect")
if showing {
Text(text.isEmpty ? model.connection : text)
@@ -345,8 +585,53 @@ struct MenuSheet: Identifiable {
var key: String { kind + ":" + id }
}
+/// The App's context menu for something, as the system menu that a long
+/// press opens: its items, checks, separators and submenus, built when
+/// the menu shows.
+struct AppMenuItems: View {
+ @ObservedObject var model: TerminalModel
+ var kind: String
+ var id: String
+
+ var body: some View {
+ let items = model.contextMenu(kind, id: id)
+ ForEach(items, id: \.rowId) { item in
+ Self.row(item, model: model)
+ }
+ }
+
+ static func row(_ item: MenuItem, model: TerminalModel) -> AnyView {
+ switch item.kind {
+ case "separator":
+ return AnyView(Divider())
+ case "header":
+ return AnyView(Text(item.label))
+ default:
+ if !item.submenu.isEmpty {
+ let subs = item.submenu
+ return AnyView(Menu(item.label) {
+ ForEach(subs, id: \.rowId) { sub in row(sub, model: model) }
+ })
+ }
+ return AnyView(
+ Button {
+ model.menuAction(item.id)
+ } label: {
+ if item.checked {
+ Label(item.label, systemImage: "checkmark")
+ } else {
+ Text(item.label)
+ }
+ }
+ .disabled(!item.enabled)
+ )
+ }
+ }
+}
+
struct MenuList: View {
@ObservedObject var model: TerminalModel
+ @ObservedObject private var lang = AppLanguage.shared
var sheet: MenuSheet
var dismiss: () -> Void
@State private var items: [MenuItem] = []
@@ -361,7 +646,7 @@ struct MenuList: View {
.navigationTitle(sheet.title)
.navigationBarTitleDisplayMode(.inline)
.toolbar {
- ToolbarItem(placement: .cancellationAction) { Button("Done", action: dismiss) }
+ ToolbarItem(placement: .cancellationAction) { Button(tr("done"), action: dismiss) }
}
}
.onAppear { items = model.contextMenu(sheet.kind, id: sheet.id) }
@@ -404,133 +689,9 @@ struct MenuList: View {
}
}
-/// The keys a soft keyboard has not got, with sticky Ctrl and Alt.
-struct KeyBar: View {
- @ObservedObject var model: TerminalModel
-
- var body: some View {
- ScrollView(.horizontal, showsIndicators: false) {
- HStack(spacing: 6) {
- key("esc") { model.key("Escape") }
- key("tab") { model.key("Tab") }
- toggle("ctrl", $model.ctrlSticky)
- toggle("alt", $model.altSticky)
- key("↑") { model.key("ArrowUp") }
- key("↓") { model.key("ArrowDown") }
- key("←") { model.key("ArrowLeft") }
- key("→") { model.key("ArrowRight") }
- key("home") { model.key("Home") }
- key("end") { model.key("End") }
- key("pgup") { model.key("PageUp") }
- key("pgdn") { model.key("PageDown") }
- key("-") { model.text("-") }
- key("/") { model.text("/") }
- key("|") { model.text("|") }
- key("~") { model.text("~") }
- key("^C") { model.key("c", ctrl: true) }
- key("^D") { model.key("d", ctrl: true) }
- key("^L") { model.key("l", ctrl: true) }
- key("^Z") { model.key("z", ctrl: true) }
- key("⌫") { model.key("Backspace") }
- }
- .padding(.horizontal, 6)
- }
- .frame(height: 38)
- .background(model.background)
- }
-
- private func key(_ label: String, action: @escaping () -> Void) -> some View {
- Button(action: action) {
- Text(label)
- .font(.system(size: 13, design: .monospaced))
- .padding(.horizontal, 10)
- .padding(.vertical, 6)
- .background(Color.white.opacity(0.08))
- .clipShape(RoundedRectangle(cornerRadius: 6))
- }
- .buttonStyle(.plain)
- .foregroundColor(.white)
- }
-
- private func toggle(_ label: String, _ on: Binding<Bool>) -> some View {
- Button { on.wrappedValue.toggle() } label: {
- Text(label)
- .font(.system(size: 13, design: .monospaced))
- .padding(.horizontal, 10)
- .padding(.vertical, 6)
- .background(on.wrappedValue ? Color.accentColor : Color.white.opacity(0.08))
- .clipShape(RoundedRectangle(cornerRadius: 6))
- }
- .buttonStyle(.plain)
- .foregroundColor(.white)
- }
-}
-
-/// The tabs and their panes, as a list: a tap shows one, a swipe closes
-/// a tab. This is where the strip and the pane menu went.
-struct SessionsSheet: View {
- @ObservedObject var model: TerminalModel
- @Binding var isPresented: Bool
- @Binding var menu: MenuSheet?
- @Binding var showSidebar: Bool
-
- var body: some View {
- NavigationStack {
- List {
- ForEach(model.tabs?.tabs ?? []) { tab in
- Section {
- ForEach(tab.panes, id: \.pane) { pane in
- Button {
- model.chromeClick("pane", pane: pane.pane)
- isPresented = false
- } label: {
- HStack {
- Image(systemName: "terminal")
- .foregroundColor(pane.current && tab.current ? .accentColor : .secondary)
- Text(pane.title.isEmpty ? "shell" : pane.title)
- .fontWeight(pane.current && tab.current ? .semibold : .regular)
- Spacer()
- if pane.current && tab.current {
- Image(systemName: "checkmark").foregroundColor(.accentColor)
- }
- }
- }
- .foregroundColor(.primary)
- }
- } header: {
- HStack {
- Text(tab.label.isEmpty ? "Tab \(tab.tab)" : tab.label)
- Spacer()
- Button("More…") {
- menu = MenuSheet(kind: "tab", id: String(tab.tab), title: "Tab")
- isPresented = false
- }
- .font(.caption)
- }
- }
- .swipeActions(edge: .trailing) {
- Button(role: .destructive) { model.chromeClick("close-tab", tab: tab.tab) } label: {
- Label("Close tab", systemImage: "xmark")
- }
- }
- }
- }
- .navigationTitle("Sessions")
- .navigationBarTitleDisplayMode(.inline)
- .toolbar {
- ToolbarItem(placement: .cancellationAction) { Button("Done") { isPresented = false } }
- ToolbarItemGroup(placement: .topBarTrailing) {
- Button { showSidebar = true; isPresented = false } label: { Image(systemName: "sidebar.left") }
- Button { model.chromeClick("new-tab") } label: { Image(systemName: "plus") }
- }
- }
- }
- .onAppear { model.refreshViews() }
- }
-}
/// Where a connection is, read off the core's status line.
-enum ConnectionPhase {
+enum ConnectionPhase: Equatable {
case connecting(String)
case attaching
case reconnecting
@@ -565,6 +726,8 @@ enum ConnectionPhase {
struct ConnectionCard: View {
enum Action { case retry, forgetKeyAndRetry, edit, back }
+ @ObservedObject private var lang = AppLanguage.shared
+
var phase: ConnectionPhase
var hostName: String
var canEdit: Bool
@@ -575,28 +738,28 @@ struct ConnectionCard: View {
switch phase {
case .connecting(let target):
ProgressView().controlSize(.large)
- Text("Connecting to \(hostName)").font(.headline)
+ Text(tr("card.connecting", hostName)).font(.headline)
if !target.isEmpty {
Text(target).font(.caption.monospaced()).foregroundColor(.secondary)
}
steps(done: 0)
case .attaching:
ProgressView().controlSize(.large)
- Text("Starting ThinkTerm on \(hostName)").font(.headline)
+ Text(tr("card.attaching", hostName)).font(.headline)
steps(done: 1)
case .reconnecting:
ProgressView().controlSize(.large)
- Text("Reconnecting to \(hostName)…").font(.headline)
+ Text(tr("card.reconnecting", hostName)).font(.headline)
case .disconnected:
Image(systemName: "bolt.slash").font(.system(size: 34)).foregroundColor(.secondary)
- Text("Disconnected").font(.headline)
+ Text(tr("conn.disconnected")).font(.headline)
HStack {
- Button("Back") { act(.back) }.buttonStyle(.bordered)
- Button("Reconnect") { act(.retry) }.buttonStyle(.borderedProminent)
+ Button(tr("back")) { act(.back) }.buttonStyle(.bordered)
+ Button(tr("reconnect")) { act(.retry) }.buttonStyle(.borderedProminent)
}
case .failed(let reason):
Image(systemName: "exclamationmark.triangle").font(.system(size: 34)).foregroundColor(.orange)
- Text("Couldn't connect to \(hostName)").font(.headline).multilineTextAlignment(.center)
+ Text(tr("card.failed", hostName)).font(.headline).multilineTextAlignment(.center)
Text(reason)
.font(.caption.monospaced())
.foregroundColor(.secondary)
@@ -606,14 +769,14 @@ struct ConnectionCard: View {
Text(hint).font(.footnote).multilineTextAlignment(.center)
}
HStack {
- Button("Back") { act(.back) }.buttonStyle(.bordered)
+ Button(tr("back")) { act(.back) }.buttonStyle(.bordered)
if canEdit {
- Button("Edit host") { act(.edit) }.buttonStyle(.bordered)
+ Button(tr("edithost")) { act(.edit) }.buttonStyle(.bordered)
}
if reason.contains("key changed") && canEdit {
- Button("Forget key & retry") { act(.forgetKeyAndRetry) }.buttonStyle(.borderedProminent)
+ Button(tr("forgetretry")) { act(.forgetKeyAndRetry) }.buttonStyle(.borderedProminent)
} else {
- Button("Retry") { act(.retry) }.buttonStyle(.borderedProminent)
+ Button(tr("retry")) { act(.retry) }.buttonStyle(.borderedProminent)
}
}
}
@@ -628,8 +791,8 @@ struct ConnectionCard: View {
private func steps(done: Int) -> some View {
VStack(alignment: .leading, spacing: 6) {
- step("Secure connection", state: done > 0 ? 2 : 1)
- step("ThinkTerm on the host", state: done > 1 ? 2 : (done == 1 ? 1 : 0))
+ step(tr("conn.step1"), state: done > 0 ? 2 : 1)
+ step(tr("conn.step2"), state: done > 1 ? 2 : (done == 1 ? 1 : 0))
}
.font(.footnote)
.padding(.top, 4)
@@ -647,19 +810,19 @@ struct ConnectionCard: View {
static func hint(for reason: String) -> String? {
let r = reason.lowercased()
if r.contains("refused the login") || r.contains("auth") {
- return "The host did not accept the user name with this key or password."
+ return tr("hint.auth")
}
if r.contains("key changed") {
- return "The host's key is not the one seen before. If the host was reinstalled, forget the old key."
+ return tr("hint.keychanged")
}
if r.contains("timed out") || r.contains("connection refused") || r.contains("unreachable") || r.contains("no route") {
- return "The host did not answer on this address and port. Check the network, or a VPN such as Tailscale."
+ return tr("hint.unreachable")
}
if r.contains("not found") || r.contains("exit 127") || r.contains("no such file") {
- return "ThinkTerm is not installed on the host, or not on its PATH."
+ return tr("hint.notfound")
}
if r.contains("codec") || r.contains("version") {
- return "The host runs another version of ThinkTerm. Update one of the two."
+ return tr("hint.version")
}
return nil
}
diff --git a/ios/Sources/ThinkTermApp.swift b/ios/Sources/ThinkTermApp.swift
index d9799882..695b5a04 100644
--- a/ios/Sources/ThinkTermApp.swift
+++ b/ios/Sources/ThinkTermApp.swift
@@ -3,7 +3,6 @@ import SwiftUI
@main
struct ThinkTermApp: App {
@StateObject private var store = HostStore()
- @State private var path = NavigationPath()
var body: some Scene {
WindowGroup {
@@ -12,24 +11,7 @@ struct ThinkTermApp: App {
// The automated flows go straight to the probe's host.
NavigationStack { TerminalScreen(host: nil, store: store) }
} else {
- TabView {
- NavigationStack(path: $path) {
- HostsView()
- .onAppear {
- // A saved host for the probe, with its key
- // in the Keychain, opened over the list: the
- // same path a real host takes, back included.
- if path.isEmpty, let seeded = Self.seededHost(into: store) {
- path.append(seeded)
- }
- }
- }
- .tabItem { Label("Hosts", systemImage: "server.rack") }
- NavigationStack {
- SettingsView(model: nil, showLog: nil)
- }
- .tabItem { Label("Settings", systemImage: "gearshape") }
- }
+ RootTabs(store: store)
}
}
.environmentObject(store)
@@ -60,3 +42,32 @@ struct ThinkTermApp: App {
#endif
}
}
+
+/// The two tabs. Its own view so the language switch relabels the tab bar
+/// with the rest of the app.
+private struct RootTabs: View {
+ let store: HostStore
+ @State private var path = NavigationPath()
+ @ObservedObject private var lang = AppLanguage.shared
+
+ var body: some View {
+ TabView {
+ NavigationStack(path: $path) {
+ HostsView()
+ .onAppear {
+ // A saved host for the probe, with its key in the
+ // Keychain, opened over the list: the same path a
+ // real host takes, back included.
+ if path.isEmpty, let seeded = ThinkTermApp.seededHost(into: store) {
+ path.append(seeded)
+ }
+ }
+ }
+ .tabItem { Label(tr("hosts"), systemImage: "server.rack") }
+ NavigationStack {
+ SettingsView(model: nil, showLog: nil)
+ }
+ .tabItem { Label(tr("settings"), systemImage: "gearshape") }
+ }
+ }
+}
diff --git a/ios/Sources/TreeSheet.swift b/ios/Sources/TreeSheet.swift
index 42c1b0c3..cff62cdf 100644
--- a/ios/Sources/TreeSheet.swift
+++ b/ios/Sources/TreeSheet.swift
@@ -7,6 +7,7 @@ import SwiftUI
/// desktop names it: thread, tab, pane.
struct TreeSheet: View {
@ObservedObject var model: TerminalModel
+ @ObservedObject private var lang = AppLanguage.shared
@Binding var isPresented: Bool
@Binding var menu: MenuSheet?
@State private var openThreads: Set<String> = []
@@ -28,11 +29,11 @@ struct TreeSheet: View {
}
}
.listStyle(.plain)
- .navigationTitle("Threads")
+ .navigationTitle(tr("threads"))
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .cancellationAction) {
- Button("Done") { isPresented = false }
+ Button(tr("done")) { isPresented = false }
}
ToolbarItemGroup(placement: .topBarTrailing) {
Menu {
@@ -50,13 +51,13 @@ struct TreeSheet: View {
Button { model.chromeClick("new-tab") } label: { Image(systemName: "plus") }
}
}
- .alert("Rename", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {
- TextField("Name", text: $renameText)
- Button("Save") {
+ .alert(tr("rename"), isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {
+ TextField(tr("f.name"), text: $renameText)
+ Button(tr("save")) {
model.sideKey("Enter", value: renameText)
renaming = nil
}
- Button("Cancel", role: .cancel) {
+ Button(tr("cancel"), role: .cancel) {
model.sideKey("Escape", value: "")
renaming = nil
}
@@ -90,12 +91,12 @@ struct TreeSheet: View {
Text(name).font(.headline)
case .newThread:
Button { model.sideClick("new-thread") } label: {
- Label("New thread", systemImage: "plus").foregroundColor(.accentColor)
+ Label(tr("thread.new"), systemImage: "plus").foregroundColor(.accentColor)
}
case .pinned:
- caption("Pinned")
+ caption(tr("pinned"))
case .workspaces:
- caption("Workspaces")
+ caption(tr("workspaces"))
case .project(let id, let name, let path, let collapsed, let archived):
HStack {
Button { model.sideClick("toggle-project", id: id) } label: {
@@ -117,7 +118,7 @@ struct TreeSheet: View {
}
}
.contextMenu {
- Button("More…") { menu = MenuSheet(kind: archived ? "archived-project" : "project", id: id, title: name) }
+ AppMenuItems(model: model, kind: archived ? "archived-project" : "project", id: id)
}
case .thread(let t):
if let thread = threads.first(where: { $0.id == t.id }) {
@@ -135,12 +136,12 @@ struct TreeSheet: View {
.foregroundColor(.secondary)
}
case .others:
- caption("Other windows")
+ caption(tr("otherwindows"))
case .window(let id, let title, let selected):
Button { model.sideClick("window", id: String(id)) } label: {
HStack {
Image(systemName: "macwindow").foregroundColor(.secondary)
- Text(title.isEmpty ? "Window \(id)" : title)
+ Text(title.isEmpty ? tr("window.n", id) : title)
}
}
.listRowBackground(selected ? Color.accentColor.opacity(0.2) : nil)
@@ -169,7 +170,7 @@ struct TreeSheet: View {
if thread.pinned {
Image(systemName: "pin").font(.caption).foregroundColor(.secondary)
}
- Text(thread.live ? "\(thread.tabs.count) tab\(thread.tabs.count == 1 ? "" : "s")" : "off")
+ Text(thread.live ? tr(thread.tabs.count == 1 ? "tab.one" : "tab.n", thread.tabs.count) : tr("thread.off"))
.font(.caption2).foregroundColor(.secondary)
if !thread.tabs.isEmpty {
Button {
@@ -187,7 +188,7 @@ struct TreeSheet: View {
.padding(.leading, indent)
.listRowBackground(thread.current ? Color.accentColor.opacity(0.18) : nil)
.contextMenu {
- Button("More…") { menu = MenuSheet(kind: "thread", id: thread.id, title: thread.name) }
+ AppMenuItems(model: model, kind: "thread", id: thread.id)
}
if open {
ForEach(thread.tabs) { tab in
@@ -209,7 +210,7 @@ struct TreeSheet: View {
isPresented = false
} label: {
HStack(spacing: 6) {
- Text(tab.title.isEmpty ? "Tab \(tab.tab)" : tab.title)
+ Text(tab.title.isEmpty ? tr("tab.num", tab.tab) : tab.title)
if let first = tab.panes.first, !first.title.isEmpty, first.title != tab.title {
Text(first.title).font(.caption).foregroundColor(.secondary)
}
@@ -221,7 +222,7 @@ struct TreeSheet: View {
Image(systemName: "checkmark").foregroundColor(.accentColor)
}
if tab.panes.count > 1 {
- Text("\(tab.panes.count) panes").font(.caption2).foregroundColor(.secondary)
+ Text(tr("panes.n", tab.panes.count)).font(.caption2).foregroundColor(.secondary)
Button {
if open { openTabs.remove(key) } else { openTabs.insert(key) }
} label: {
@@ -236,8 +237,7 @@ struct TreeSheet: View {
}
.padding(.leading, indent)
.contextMenu {
- Button("Close tab", role: .destructive) { model.chromeClick("close-tab", tab: tab.tab) }
- Button("More…") { menu = MenuSheet(kind: "tab", id: String(tab.tab), title: tab.title) }
+ AppMenuItems(model: model, kind: "tab", id: String(tab.tab))
}
if open {
ForEach(tab.panes) { pane in
@@ -261,13 +261,24 @@ struct TreeSheet: View {
}
}
-/// The desktop's Live Overview, one column of cards: a card per thread,
-/// grouped by project, with its tabs as dots (the rest folded into +N),
-/// an offline badge, and the last rows of its terminal as a preview.
+/// The desktop's Live Overview as an overlay under the terminal: a card
+/// per thread, grouped by project, two to a row. Each card is the
+/// thread's name and state, its tabs as dots (the rest folded into +N),
+/// an offline badge, and a thumbnail of its terminal in its colours: the
+/// last rows of its current tab's pane, fetched from the server and
+/// refreshed while the overview is up. The thread on show leaves its
+/// thumbnail empty and reports the box's frame: the live terminal is
+/// zoomed into it by the screen above.
struct OverviewScreen: View {
@ObservedObject var model: TerminalModel
+ @ObservedObject private var lang = AppLanguage.shared
@Binding var isPresented: Bool
+ /// The thumbnail box of the thread on show, in the screen's space.
+ @Binding var cardFrame: CGRect?
+ var liveThread: String?
private let dots = 4
+ private let rows = 9
+ private let columns = [GridItem(.flexible(), spacing: 10), GridItem(.flexible(), spacing: 10)]
private var threads: [ThreadView] { model.threads?.threads ?? [] }
@@ -282,104 +293,155 @@ struct OverviewScreen: View {
}
var body: some View {
- NavigationStack {
+ VStack(spacing: 0) {
ScrollView {
if threads.isEmpty {
- Text("No threads on this server.")
+ Text(tr("overview.none"))
.foregroundColor(.secondary)
.padding(.top, 60)
} else {
- LazyVStack(alignment: .leading, spacing: 10) {
+ LazyVStack(alignment: .leading, spacing: 8) {
ForEach(groups, id: \.project) { group in
HStack(spacing: 6) {
Text(model.threads?.space ?? "")
Text("·").foregroundColor(.secondary)
Text(group.project)
- Rectangle().fill(Color.secondary.opacity(0.3)).frame(height: 1)
+ Rectangle().fill(Color.white.opacity(0.08)).frame(height: 1)
Text("\(group.threads.count)").foregroundColor(.secondary)
}
.font(.caption)
- .padding(.horizontal, 12)
- .padding(.top, 8)
- ForEach(group.threads) { thread in
- card(thread)
- .padding(.horizontal, 12)
+ .padding(.top, 10)
+ LazyVGrid(columns: columns, spacing: 10) {
+ ForEach(group.threads) { thread in
+ card(thread)
+ }
}
}
}
+ .padding(.horizontal, 12)
.padding(.vertical, 8)
}
}
- .background(Color(white: 0.06))
- .navigationTitle("Overview")
- .navigationBarTitleDisplayMode(.inline)
- .toolbar {
- ToolbarItem(placement: .cancellationAction) { Button("Done") { isPresented = false } }
+ // Pinching back in returns to the terminal.
+ .gesture(MagnifyGesture().onEnded { value in
+ if value.magnification > 1.25 { isPresented = false }
+ })
+ }
+ .foregroundColor(.white)
+ .background(Color(white: 0.06))
+ .onAppear {
+ model.refreshViews()
+ refreshPreviews()
+ }
+ .onReceive(Timer.publish(every: 2, on: .main, in: .common).autoconnect()) { _ in
+ refreshPreviews()
+ }
+ }
+
+ /// Every live thread's current tab, asked for its last rows.
+ private func refreshPreviews() {
+ for thread in threads where thread.live && thread.id != liveThread {
+ if let pane = previewPane(thread) {
+ model.requestPreview(pane: pane, rows: rows)
}
}
- .onAppear { model.refreshViews() }
+ }
+
+ private func previewPane(_ thread: ThreadView) -> Int? {
+ (thread.tabs.first(where: { $0.current }) ?? thread.tabs.first)?.target
}
private func card(_ thread: ThreadView) -> some View {
let shown = Array(thread.tabs.prefix(dots))
let folded = thread.tabs.count - shown.count
let currentTab = thread.tabs.first(where: { $0.current }) ?? thread.tabs.first
+ let live = thread.id == liveThread
return Button {
- model.sideClick("thread", id: thread.id)
+ if !live { model.sideClick("thread", id: thread.id) }
isPresented = false
} label: {
- VStack(alignment: .leading, spacing: 6) {
- HStack(spacing: 8) {
- Circle().fill(TerminalScreen.threadColor(status: thread.status, live: thread.live)).frame(width: 8, height: 8)
- Text(thread.name).font(.subheadline.weight(.semibold)).lineLimit(1)
- Spacer()
+ VStack(alignment: .leading, spacing: 0) {
+ HStack(spacing: 7) {
+ Circle().fill(TerminalScreen.threadColor(status: thread.status, live: thread.live)).frame(width: 7, height: 7)
+ Text(thread.name).font(.system(size: 13.5, weight: .semibold)).lineLimit(1)
+ Spacer(minLength: 0)
}
+ .padding(.horizontal, 10)
+ .padding(.top, 10)
+ .padding(.bottom, 6)
HStack(spacing: 4) {
ForEach(shown) { tab in
Circle()
- .fill(thread.current && tab.current ? Color.white : Color.white.opacity(0.3))
- .frame(width: 7, height: 7)
+ .fill(thread.current && tab.current ? Color.accentColor : Color.white.opacity(0.28))
+ .frame(width: 6, height: 6)
}
if folded > 0 {
- Text("+\(folded)").font(.caption2).foregroundColor(.secondary)
+ Text("+\(folded)").font(.system(size: 9.5)).foregroundColor(.secondary)
}
- Text(currentTab?.title ?? "").font(.caption).foregroundColor(.secondary).lineLimit(1)
- Spacer()
+ Text(currentTab?.title ?? "")
+ .font(.system(size: 10, design: .monospaced))
+ .foregroundColor(.secondary)
+ .lineLimit(1)
+ .padding(.leading, 3)
+ Spacer(minLength: 0)
if !thread.live {
- Text("offline")
- .font(.caption2)
+ Text(tr("offline"))
+ .font(.system(size: 9, weight: .semibold))
+ .foregroundColor(.secondary)
.padding(.horizontal, 6).padding(.vertical, 2)
- .background(Color.white.opacity(0.1))
+ .background(Color.gray.opacity(0.22))
.clipShape(Capsule())
}
}
- Text(preview(thread))
- .font(.system(size: 9, design: .monospaced))
- .foregroundColor(.secondary)
- .lineLimit(7)
- .frame(maxWidth: .infinity, alignment: .leading)
- .padding(8)
- .background(model.background)
- .clipShape(RoundedRectangle(cornerRadius: 8))
+ .padding(.horizontal, 10)
+ .padding(.bottom, 7)
+ Group {
+ if live {
+ // The terminal itself lands here; the frame is reported.
+ Color.clear
+ .background(GeometryReader { geo in
+ Color.clear
+ .onAppear { cardFrame = geo.frame(in: .named("screen")) }
+ .onChange(of: geo.frame(in: .named("screen"))) { _, f in cardFrame = f }
+ })
+ } else {
+ Text(preview(thread))
+ .font(.system(size: 7, design: .monospaced))
+ .lineSpacing(1)
+ .frame(maxWidth: .infinity, alignment: .topLeading)
+ .padding(.horizontal, 8)
+ .padding(.vertical, 7)
+ }
+ }
+ .frame(height: 92, alignment: .topLeading)
+ .background(thread.live ? model.background : Color.black.opacity(0.4))
+ .clipped()
}
- .padding(10)
- .background(Color.white.opacity(thread.current ? 0.12 : 0.06))
- .clipShape(RoundedRectangle(cornerRadius: 12))
- .overlay(RoundedRectangle(cornerRadius: 12).stroke(thread.current ? Color.accentColor : Color.clear, lineWidth: 1))
+ .background(Color(red: 0.10, green: 0.11, blue: 0.13))
+ .clipShape(RoundedRectangle(cornerRadius: 13))
+ .overlay(RoundedRectangle(cornerRadius: 13).stroke(live ? Color.accentColor : Color.white.opacity(0.07), lineWidth: live ? 2 : 1))
}
.buttonStyle(.plain)
- .foregroundColor(.white)
}
- /// The current thread's terminal, its last rows; another thread's is
- /// not on this phone, and shows what it holds.
- private func preview(_ thread: ThreadView) -> String {
- if thread.current, let screen = ViewJSON.decode(ScreenText.self, model.core.screenText()) {
- let rows = screen.text.split(separator: "\n", omittingEmptySubsequences: false)
- .map { $0.replacingOccurrences(of: "\u{2060}", with: "").trimmingCharacters(in: .whitespaces) }
- let kept = rows.reversed().drop(while: { $0.isEmpty }).reversed().suffix(7)
- return kept.joined(separator: "\n")
+ /// 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 func preview(_ thread: ThreadView) -> AttributedString {
+ guard let pane = previewPane(thread), let fetched = model.previews[pane] else { return AttributedString("") }
+ let kept = Array(fetched.reversed().drop(while: { $0.runs.isEmpty }).reversed().suffix(rows))
+ var out = AttributedString()
+ for (i, row) in kept.enumerated() {
+ var used = 0
+ for run in row.runs {
+ let room = 38 - used
+ if room <= 0 { break }
+ var piece = AttributedString(String(run.text.prefix(room)))
+ piece.foregroundColor = Color(hex: run.fg) ?? .white
+ out += piece
+ used += min(run.text.count, room)
+ }
+ if i < kept.count - 1 { out += AttributedString("\n") }
}
- return thread.tabs.map { "· " + ($0.title.isEmpty ? "Tab \($0.tab)" : $0.title) }.joined(separator: "\n")
+ return out
}
}
diff --git a/ios/Sources/Views.swift b/ios/Sources/Views.swift
index f9447fe8..19805f68 100644
--- a/ios/Sources/Views.swift
+++ b/ios/Sources/Views.swift
@@ -57,6 +57,52 @@ struct NavView: Decodable, Hashable, Identifiable {
var id: Int { rect.pane }
}
+/// The desktop's sidebar layer with its tabs: `App::threads_view`.
+struct ThreadsView: Decodable, Hashable {
+ var space: String
+ var threads: [ThreadView]
+}
+
+struct ThreadView: Decodable, Hashable, Identifiable {
+ var id: String
+ var name: String
+ var project: String
+ var project_id: String
+ var status: String
+ var dot: String
+ var live: Bool
+ var pinned: Bool
+ var unread: Bool
+ var current: Bool
+ var window: Int?
+ var tabs: [ThreadTab]
+}
+
+struct ThreadTab: Decodable, Hashable, Identifiable {
+ var tab: Int
+ var title: String
+ var target: Int
+ var current: Bool
+ var panes: [PaneRef]
+ var id: Int { tab }
+}
+
+struct PaneRef: Decodable, Hashable, Identifiable {
+ var pane: Int
+ var title: String
+ var id: Int { pane }
+}
+
+/// A thumbnail row: `App::PreviewRow`.
+struct PreviewRow: Decodable, Hashable {
+ var runs: [PreviewRun]
+}
+
+struct PreviewRun: Decodable, Hashable {
+ var text: String
+ var fg: String
+}
+
struct Toast: Decodable, Hashable {
var text: String
var sticky: Bool
diff --git a/ios/build.sh b/ios/build.sh
index e660e99c..9550e815 100755
--- a/ios/build.sh
+++ b/ios/build.sh
@@ -53,7 +53,7 @@ mv ios/Generated/thinkterm_mobileFFI.modulemap ios/Generated/module.modulemap
echo "== fonts"
mkdir -p ios/Resources
-cp assets/fonts/JetBrainsMono-Regular.ttf assets/fonts/SymbolsNerdFontMono-Regular.ttf ios/Resources/
+cp assets/fonts/JetBrainsMono-Regular.ttf assets/fonts/FiraCode-Regular.ttf assets/fonts/SymbolsNerdFontMono-Regular.ttf ios/Resources/
# The colour schemes the theme picker offers: the web page's list.
cp thinkterm-web/www/schemes.json ios/Resources/
diff --git a/ios/project.yml b/ios/project.yml
index 7f76d20e..4cf461b4 100644
--- a/ios/project.yml
+++ b/ios/project.yml
@@ -32,7 +32,11 @@ targets:
# iOS 26 and later render, and Assets.xcassets carries a plain 1024 PNG
# for older systems. Both are named ThinkTerm, which is the name
# ASSETCATALOG_COMPILER_APPICON_NAME below points at.
- - path: ../assets/icon/ThinkTerm.icon
+ # This is the iOS-only bundle (ios/ThinkTerm.icon), not the Mac one in
+ # assets/icon: it is a gradient background plus the glass chevron, with
+ # no baked squircle, so iOS composites its own liquid-glass shape. The
+ # Mac bundle's raster layer would show as a squircle inside a squircle.
+ - path: ThinkTerm.icon
type: file
buildPhase: resources
- path: Assets.xcassets