A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
ios: hosts, connection, theme, native selection, and a real phone
RoversX310f42d920bc
diff --git a/ios/.gitignore b/ios/.gitignoreindex 1fc589e7..907a7d94 100644--- a/ios/.gitignore+++ b/ios/.gitignore@@ -1,3 +1,5 @@# Regenerated by ios/build.shGenerated/ThinkTerm.xcodeproj/+# The developer's signing team+Local.xcconfigdiff --git a/ios/Assets.xcassets/Contents.json b/ios/Assets.xcassets/Contents.jsonnew file mode 100644index 00000000..73c00596--- /dev/null+++ b/ios/Assets.xcassets/Contents.json@@ -0,0 +1,6 @@+{+ "info" : {+ "author" : "xcode",+ "version" : 1+ }+}diff --git a/ios/Assets.xcassets/ThinkTerm.appiconset/Contents.json b/ios/Assets.xcassets/ThinkTerm.appiconset/Contents.jsonnew file mode 100644index 00000000..8d110426--- /dev/null+++ b/ios/Assets.xcassets/ThinkTerm.appiconset/Contents.json@@ -0,0 +1,14 @@+{+ "images" : [+ {+ "filename" : "ThinkTerm-1024.png",+ "idiom" : "universal",+ "platform" : "ios",+ "size" : "1024x1024"+ }+ ],+ "info" : {+ "author" : "xcode",+ "version" : 1+ }+}diff --git a/ios/Assets.xcassets/ThinkTerm.appiconset/ThinkTerm-1024.png b/ios/Assets.xcassets/ThinkTerm.appiconset/ThinkTerm-1024.pngnew file mode 100644index 00000000..c2ff4658Binary files /dev/null and b/ios/Assets.xcassets/ThinkTerm.appiconset/ThinkTerm-1024.png differdiff --git a/ios/Resources/.gitignore b/ios/Resources/.gitignoreindex d259f058..1849e94c 100644--- a/ios/Resources/.gitignore+++ b/ios/Resources/.gitignore@@ -1 +1,2 @@*.ttf+schemes.jsondiff --git a/ios/Sources/AppSettings.swift b/ios/Sources/AppSettings.swiftnew file mode 100644index 00000000..4f201fae--- /dev/null+++ b/ios/Sources/AppSettings.swift@@ -0,0 +1,31 @@+import SwiftUI+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.+final class AppSettings: ObservableObject {+ static let shared = AppSettings()++ /// A scheme name from schemes.json, or "desktop" to follow the host's.+ @Published var schemeName: String {+ didSet { defaults.set(schemeName, forKey: "scheme.name") }+ }+ /// 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") }+ }++ 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")+ fontSize = size > 0 ? size : 11+ }+}diff --git a/ios/Sources/HostEditView.swift b/ios/Sources/HostEditView.swiftnew file mode 100644index 00000000..67f09937--- /dev/null+++ b/ios/Sources/HostEditView.swift@@ -0,0 +1,292 @@+import SwiftUI+import UniformTypeIdentifiers++/// Add or edit one host. The private key never travels back out of the+/// Keychain into a field: the editor only reports whether one is stored,+/// and hands a new secret to `save` when the user supplies one.+struct HostEditView: View {+ @Environment(\.dismiss) private var dismiss+ @EnvironmentObject var store: HostStore+ @State var host: Host+ @State private var secret = ""+ @State private var passphrase = ""+ @State private var hasStoredSecret = false+ @State private var showKeyText = false+ @State private var showAdvanced = false+ @State private var importing = false+ @State private var importError: String?+ @State private var copiedPublicKey = false+ var save: (Host, String, String?) -> Void++ var body: some View {+ NavigationStack {+ Form {+ hostSection+ groupSection+ authSection+ advancedSection+ }+ .scrollContentBackground(.hidden)+ .background(Color.black.ignoresSafeArea())+ .navigationTitle(host.hostname.isEmpty ? "New host" : host.display)+ .navigationBarTitleDisplayMode(.inline)+ .toolbar {+ ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+ ToolbarItem(placement: .confirmationAction) {+ Button("Save") {+ save(host, secret, passphrase.isEmpty ? nil : passphrase)+ dismiss()+ }+ .fontWeight(.semibold)+ .disabled(!canSave)+ }+ }+ .onAppear { hasStoredSecret = Keychain.load(account: host.id.uuidString) != nil }+ .fileImporter(isPresented: $importing, allowedContentTypes: [.data, .text]) { result in+ importKey(result)+ }+ .alert(+ "Import failed",+ isPresented: Binding(get: { importError != nil }, set: { if !$0 { importError = nil } })+ ) {+ Button("OK", role: .cancel) { importError = nil }+ } message: {+ Text(importError ?? "")+ }+ }+ }++ private var hostSection: some View {+ Section("Host") {+ labelled("Name") {+ TextField("Optional", text: $host.name)+ }+ labelled("Hostname") {+ TextField("example.com or 10.0.0.4", text: $host.hostname)+ .textInputAutocapitalization(.never)+ .autocorrectionDisabled()+ .keyboardType(.URL)+ }+ labelled("Port") {+ TextField("22", value: $host.port, format: .number)+ .keyboardType(.numberPad)+ }+ labelled("User") {+ TextField("root", text: $host.user)+ .textInputAutocapitalization(.never)+ .autocorrectionDisabled()+ }+ }+ }++ private var groupSection: some View {+ Section {+ labelled("Group") {+ TextField("None", text: $host.group)+ .autocorrectionDisabled()+ }+ if !store.groups.isEmpty {+ ScrollView(.horizontal, showsIndicators: false) {+ HStack(spacing: 8) {+ ForEach(store.groups, id: \.self) { group in+ Button {+ host.group = host.group == group ? "" : group+ } label: {+ Text(group)+ .font(.footnote.weight(.medium))+ .padding(.horizontal, 12)+ .padding(.vertical, 6)+ .background(+ Capsule().fill(+ host.group == group+ ? Color.accentColor.opacity(0.85)+ : Color.secondary.opacity(0.2)+ )+ )+ .foregroundStyle(host.group == group ? Color.white : Color.primary)+ }+ .buttonStyle(.plain)+ }+ }+ .padding(.vertical, 2)+ }+ .listRowInsets(EdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16))+ }+ } header: {+ Text("Group")+ } footer: {+ Text("Groups become sections in the host list.")+ }+ }++ private var authSection: some View {+ Section("Authentication") {+ Picker("Method", selection: $host.auth) {+ ForEach(Host.AuthKind.allCases) { kind in Text(kind.label).tag(kind) }+ }+ .pickerStyle(.segmented)+ .labelsHidden()+ .padding(.vertical, 2)++ 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") }+ if let publicKey = host.publicKey, !publicKey.isEmpty {+ publicKeyRow(publicKey)+ }+ DisclosureGroup("Paste key text", isExpanded: $showKeyText) {+ TextEditor(text: $secret)+ .font(.system(size: 11, design: .monospaced))+ .frame(minHeight: 120)+ .autocorrectionDisabled()+ .textInputAutocapitalization(.never)+ .scrollContentBackground(.hidden)+ .onChange(of: secret) { _, _ in refreshPublicKey() }+ }+ SecureField("Key passphrase (if any)", text: $passphrase)+ } else {+ SecureField("Password", text: $secret)+ }+ }+ }++ private var keyStatusRow: some View {+ HStack(spacing: 10) {+ Image(systemName: keyStatus.symbol)+ .foregroundStyle(keyStatus.tint)+ Text(keyStatus.text)+ .font(.subheadline)+ Spacer(minLength: 0)+ }+ .padding(.vertical, 2)+ }++ private func publicKeyRow(_ publicKey: String) -> some View {+ VStack(alignment: .leading, spacing: 8) {+ Text(publicKey)+ .font(.system(size: 11, design: .monospaced))+ .foregroundStyle(.secondary)+ .lineLimit(4)+ .fixedSize(horizontal: false, vertical: true)+ .textSelection(.enabled)+ Button {+ UIPasteboard.general.string = publicKey+ copiedPublicKey = true+ } label: {+ Label(+ copiedPublicKey ? "Copied" : "Copy public key",+ systemImage: copiedPublicKey ? "checkmark" : "doc.on.doc"+ )+ .font(.subheadline)+ }+ .buttonStyle(.bordered)+ Text("Add this line to ~/.ssh/authorized_keys on the host.")+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ .padding(.vertical, 6)+ }++ private var advancedSection: some View {+ Section {+ DisclosureGroup("Advanced", isExpanded: $showAdvanced) {+ VStack(alignment: .leading, spacing: 6) {+ TextField("Remote command", text: $host.remoteCommand)+ .textInputAutocapitalization(.never)+ .autocorrectionDisabled()+ .font(.system(size: 13, design: .monospaced))+ Text("Blank runs `thinkterm cli --prefer-mux proxy` on the host.")+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ .padding(.vertical, 4)+ if let known = host.knownHost {+ VStack(alignment: .leading, spacing: 4) {+ Text("Host key")+ .font(.subheadline)+ Text(known)+ .font(.system(size: 11, design: .monospaced))+ .foregroundStyle(.secondary)+ .lineLimit(3)+ .fixedSize(horizontal: false, vertical: true)+ }+ .padding(.vertical, 4)+ Button(role: .destructive) {+ host.knownHost = nil+ } label: {+ Label("Forget host key", systemImage: "xmark.shield")+ }+ }+ }+ }+ }++ private func labelled<Field: View>(_ label: String, @ViewBuilder field: () -> Field) -> some View {+ HStack(spacing: 10) {+ Text(label)+ .foregroundStyle(.secondary)+ .frame(width: 86, alignment: .leading)+ field()+ }+ }++ private var isExisting: Bool { store.hosts.contains { $0.id == host.id } }++ private var canSave: Bool {+ guard !host.hostname.trimmingCharacters(in: .whitespaces).isEmpty,+ !host.user.trimmingCharacters(in: .whitespaces).isEmpty else { return false }+ // A new host has nothing in the Keychain yet, so it needs a secret now.+ return isExisting || hasStoredSecret || !secret.isEmpty+ }++ 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)+ }+ if hasStoredSecret { return ("Key stored", "lock.fill", .green) }+ return ("No key yet", "exclamationmark.triangle.fill", .orange)+ }++ private var keyComment: String { "\(host.user)@thinkterm-ios" }++ private func pasteKey() {+ guard let text = UIPasteboard.general.string,+ !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }+ secret = text+ refreshPublicKey()+ }++ private func generateKey() {+ let key = SSHKey.generate(comment: keyComment)+ secret = key.privatePEM+ host.publicKey = key.publicLine+ copiedPublicKey = false+ }++ private func importKey(_ result: Result<URL, Error>) {+ switch result {+ case .success(let url):+ 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."+ return+ }+ secret = text+ refreshPublicKey()+ case .failure(let error):+ importError = error.localizedDescription+ }+ }++ /// Only an unencrypted ed25519 key yields a public line; for anything+ /// else the user pastes the public half on the host themselves.+ private func refreshPublicKey() {+ host.publicKey = SSHKey.publicLine(ofPrivate: secret, comment: keyComment)+ copiedPublicKey = false+ }+}diff --git a/ios/Sources/HostsView.swift b/ios/Sources/HostsView.swiftindex 78c8fb34..16f1a632 100644--- a/ios/Sources/HostsView.swift+++ b/ios/Sources/HostsView.swift@@ -1,47 +1,69 @@import SwiftUI-/// The hosts, and the way in. The probe's local sshd is a row of its own-/// so the automated flows and a quick check need no setup.+/// The hosts, and the way in. The probe's local sshd is a debug-only row of+/// its own so the automated flows and a quick check need no setup.struct HostsView: View {@EnvironmentObject var store: HostStore@State private var editing: Host?@State private var adding = false+ @State private var search = ""+ @State private var pendingDelete: Host?+ @State private var connecting: ConnectTarget?+ #if DEBUG+ // Built once: a fresh Host would get a new id on every body pass, and+ // NavigationLink needs the value to stay equal across redraws.+ @State private var probe = Host(name: "probe", hostname: "127.0.0.1", port: 2299, user: probeUserName())+ #endifvar body: some View {List {- Section {- ForEach(store.hosts) { host in- NavigationLink(value: host) {- VStack(alignment: .leading, spacing: 2) {- Text(host.display).font(.body)- Text("\(host.user)@\(host.hostname):\(host.port) · \(host.auth.label)")- .font(.caption).foregroundColor(.secondary)- }- }- .swipeActions(edge: .trailing) {- Button(role: .destructive) { store.remove(host) } label: { Label("Delete", systemImage: "trash") }- Button { editing = host } label: { Label("Edit", systemImage: "pencil") }- }- .contextMenu {- Button("Edit") { editing = host }- if host.knownHost != nil {- Button("Forget host key") { store.forgetHostKey(for: host.id) }- }- Button("Delete", role: .destructive) { store.remove(host) }- }+ if store.hosts.isEmpty {+ Section {+ HostsEmptyState { adding = true }}- } header: {- Text("Hosts")- } footer: {- if store.hosts.isEmpty {- Text("Add a host that has ThinkTerm installed. The app connects over ssh and attaches to the host's mux server.")+ .listRowBackground(Color.clear)+ .listRowSeparator(.hidden)+ } else if matches.isEmpty {+ Section {+ Text("No hosts match “\(search)”.")+ .font(.subheadline)+ .foregroundStyle(.secondary)+ .frame(maxWidth: .infinity, alignment: .center)+ .padding(.vertical, 24)+ }+ .listRowBackground(Color.clear)+ .listRowSeparator(.hidden)+ } else if sections.count == 1, sections[0].title == nil {+ Section {+ ForEach(sections[0].hosts) { row($0) }+ }+ } else {+ ForEach(sections) { group in+ Section(group.title ?? "Other") {+ ForEach(group.hosts) { row($0) }+ }}}++ #if DEBUGSection("Development") {- NavigationLink("This Mac (probe sshd on :2299)", value: Host(name: "probe", hostname: "127.0.0.1", port: 2299, user: probeUserName()))+ NavigationLink(value: probe) {+ HostRowLayout(+ symbol: "hammer",+ tint: .gray,+ title: "This Mac",+ subtitle: "probe sshd on 127.0.0.1:2299"+ )+ }}+ #endif}- .navigationTitle("ThinkTerm")+ .listStyle(.insetGrouped)+ .scrollContentBackground(.hidden)+ .background(Color.black.ignoresSafeArea())+ .navigationTitle("Hosts")+ .navigationBarTitleDisplayMode(.large)+ .searchable(text: $search, placement: .navigationBarDrawer, prompt: "Search hosts").navigationDestination(for: Host.self) { host inif host.name == "probe" {TerminalScreen(host: nil, store: store)@@ -49,9 +71,15 @@ struct HostsView: View {TerminalScreen(host: host, store: store)}}+ // A separate destination type so the context menu's Connect can push+ // without fighting the value-based destination above.+ .navigationDestination(item: $connecting) { target in+ TerminalScreen(host: target.host, store: store)+ }.toolbar {ToolbarItem(placement: .topBarTrailing) {Button { adding = true } label: { Image(systemName: "plus") }+ .accessibilityLabel("Add host")}}.sheet(isPresented: $adding) {@@ -60,6 +88,7 @@ struct HostsView: View {if let passphrase { Keychain.save(passphrase, account: host.id.uuidString + ".passphrase") }store.upsert(host)}+ .environmentObject(store)}.sheet(item: $editing) { host inHostEditView(host: host) { host, secret, passphrase in@@ -67,67 +96,214 @@ struct HostsView: View {if let passphrase { Keychain.save(passphrase, account: host.id.uuidString + ".passphrase") }store.upsert(host)}+ .environmentObject(store)+ }+ .confirmationDialog(+ "Delete this host?",+ 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) {}+ } message: { _ in+ Text("Its saved key or password is removed from the Keychain too.")+ }+ }++ @ViewBuilder+ private func row(_ host: Host) -> some View {+ NavigationLink(value: host) {+ HostRow(host: host)+ }+ .swipeActions(edge: .trailing) {+ Button(role: .destructive) { pendingDelete = host } label: { Label("Delete", systemImage: "trash") }+ Button { editing = host } label: { Label("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") }+ if host.knownHost != nil {+ Button { store.forgetHostKey(for: host.id) } label: { Label("Forget host key", systemImage: "xmark.shield") }+ }+ Divider()+ Button(role: .destructive) { pendingDelete = host } label: { Label("Delete", systemImage: "trash") }}}++ /// A copy under a new id, with the Keychain secret copied across so the+ /// duplicate connects without being re-keyed.+ private func duplicate(_ host: Host) {+ var copy = host+ copy.id = UUID()+ copy.name = (host.name.isEmpty ? host.display : host.name) + " copy"+ copy.lastConnected = nil+ if let secret = Keychain.load(account: host.id.uuidString) {+ Keychain.save(secret, account: copy.id.uuidString)+ }+ if let passphrase = Keychain.load(account: host.id.uuidString + ".passphrase") {+ Keychain.save(passphrase, account: copy.id.uuidString + ".passphrase")+ }+ store.upsert(copy)+ }++ private var matches: [Host] {+ let query = search.trimmingCharacters(in: .whitespaces).lowercased()+ guard !query.isEmpty else { return store.hosts }+ return store.hosts.filter { host in+ [host.name, host.hostname, host.user, host.group].contains { $0.lowercased().contains(query) }+ }+ }++ /// One section per group once any host has one, ungrouped hosts last;+ /// a single title-less section when nobody uses groups.+ private var sections: [HostSection] {+ let hosts = matches+ guard store.hosts.contains(where: { !$0.group.isEmpty }) else {+ return [HostSection(id: "all", title: nil, hosts: hosts)]+ }+ var byGroup: [String: [Host]] = [:]+ for host in hosts { byGroup[host.group, default: []].append(host) }+ var out = byGroup.keys.filter { !$0.isEmpty }.sorted().map {+ HostSection(id: "g:" + $0, title: $0, hosts: byGroup[$0] ?? [])+ }+ if let ungrouped = byGroup[""], !ungrouped.isEmpty {+ out.append(HostSection(id: "other", title: nil, hosts: ungrouped))+ }+ return out+ }+}++private struct HostSection: Identifiable {+ let id: String+ let title: String?+ let hosts: [Host]+}++/// The push target for the context menu's Connect. Its own type so it does+/// not collide with the list's `navigationDestination(for: Host.self)`.+private struct ConnectTarget: Hashable {+ let host: Host}-struct HostEditView: View {- @Environment(\.dismiss) private var dismiss- @State var host: Host- @State private var secret = ""- @State private var passphrase = ""- var save: (Host, String, String?) -> Void+struct HostRow: View {+ let host: Hostvar body: some View {- NavigationStack {- Form {- Section("Host") {- TextField("Name (optional)", text: $host.name)- TextField("Hostname or IP", text: $host.hostname)- .textInputAutocapitalization(.never).autocorrectionDisabled().keyboardType(.URL)- TextField("Port", value: $host.port, format: .number).keyboardType(.numberPad)- TextField("User", text: $host.user)- .textInputAutocapitalization(.never).autocorrectionDisabled()- }- Section("Authentication") {- Picker("Method", selection: $host.auth) {- ForEach(Host.AuthKind.allCases) { kind in Text(kind.label).tag(kind) }- }- .pickerStyle(.segmented)- if host.auth == .key {- TextEditor(text: $secret)- .font(.system(size: 11, design: .monospaced))- .frame(minHeight: 120)- .autocorrectionDisabled()- .textInputAutocapitalization(.never)- Text("Paste the private key (OpenSSH or PEM). Its public half must be in the host's authorized_keys.")- .font(.caption).foregroundColor(.secondary)- SecureField("Key passphrase (if any)", text: $passphrase)- } else {- SecureField("Password", text: $secret)- }- }- Section("Advanced") {- TextField("Remote command (blank = thinkterm cli --prefer-mux proxy)", text: $host.remoteCommand)- .textInputAutocapitalization(.never).autocorrectionDisabled()- .font(.caption)- if let known = host.knownHost {- Text("Host key: \(known)").font(.caption2).foregroundColor(.secondary)- }- }+ HostRowLayout(+ symbol: "server.rack",+ tint: host.tint,+ title: host.title,+ subtitle: host.address+ ) {+ HStack(spacing: 6) {+ Text(host.lastConnectedText)+ .font(.caption)+ .foregroundStyle(.tertiary)+ Text(host.auth == .key ? "key" : "password")+ .font(.caption2.weight(.semibold))+ .foregroundStyle(.secondary)+ .padding(.horizontal, 7)+ .padding(.vertical, 2)+ .background(Capsule().fill(Color.secondary.opacity(0.18)))}- .navigationTitle(host.hostname.isEmpty ? "New host" : host.display)- .navigationBarTitleDisplayMode(.inline)- .toolbar {- ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }- ToolbarItem(placement: .confirmationAction) {- Button("Save") {- save(host, secret, passphrase.isEmpty ? nil : passphrase)- dismiss()- }- .disabled(host.hostname.isEmpty || host.user.isEmpty)- }+ .padding(.top, 1)+ }+ }+}++/// The shared shape of a row: a tinted disc, a name, an address, and an+/// optional third line.+struct HostRowLayout<Detail: View>: View {+ let symbol: String+ let tint: Color+ let title: String+ let subtitle: String+ @ViewBuilder var detail: () -> Detail++ var body: some View {+ HStack(spacing: 12) {+ ZStack {+ Circle().fill(tint.gradient).frame(width: 40, height: 40)+ Image(systemName: symbol)+ .font(.system(size: 16, weight: .semibold))+ .foregroundStyle(.white)+ }+ VStack(alignment: .leading, spacing: 2) {+ Text(title).font(.headline).lineLimit(1)+ Text(subtitle)+ .font(.subheadline)+ .foregroundStyle(.secondary)+ .lineLimit(1)+ detail()+ }+ Spacer(minLength: 0)+ }+ .padding(.vertical, 6)+ }+}++extension HostRowLayout where Detail == EmptyView {+ init(symbol: String, tint: Color, title: String, subtitle: String) {+ self.init(symbol: symbol, tint: tint, title: title, subtitle: subtitle) { EmptyView() }+ }+}++struct HostsEmptyState: View {+ var add: () -> Void++ var body: some View {+ VStack(spacing: 10) {+ Image(systemName: "server.rack")+ .font(.system(size: 46, weight: .light))+ .foregroundStyle(.secondary)+ .padding(.bottom, 4)+ Text("No hosts yet")+ .font(.title3.weight(.semibold))+ Text("Add a machine that has ThinkTerm installed. The app connects over ssh and attaches to its sessions.")+ .font(.subheadline)+ .foregroundStyle(.secondary)+ .multilineTextAlignment(.center)+ .fixedSize(horizontal: false, vertical: true)+ Button(action: add) {+ Label("Add host", systemImage: "plus")+ .font(.headline)+ .frame(maxWidth: .infinity)}+ .buttonStyle(.borderedProminent)+ .controlSize(.large)+ .padding(.top, 14)}+ .padding(.horizontal, 12)+ .padding(.vertical, 32)+ .frame(maxWidth: .infinity)+ }+}++private let hostRelativeFormatter: RelativeDateTimeFormatter = {+ let formatter = RelativeDateTimeFormatter()+ formatter.unitsStyle = .abbreviated+ return formatter+}()++extension Host {+ /// A stable colour per host. String.hashValue is seeded per process, so+ /// the bytes are hashed here instead to survive a relaunch.+ /// The headline of a row: `display` would repeat the address below it+ /// when the host has no name.+ var title: String { name.isEmpty ? hostname : name }++ var tint: Color {+ let palette: [Color] = [.blue, .indigo, .purple, .pink, .orange, .teal, .green, .cyan]+ var hash: UInt64 = 5381+ for byte in (name + hostname + user).utf8 { hash = hash &* 33 &+ UInt64(byte) }+ return palette[Int(hash % UInt64(palette.count))]+ }++ var lastConnectedText: String {+ guard let last = lastConnected else { return "Never connected" }+ return hostRelativeFormatter.localizedString(for: last, relativeTo: Date())}}diff --git a/ios/Sources/Models.swift b/ios/Sources/Models.swiftindex d03d5d33..efcacad0 100644--- a/ios/Sources/Models.swift+++ b/ios/Sources/Models.swift@@ -22,10 +22,50 @@ struct Host: Codable, Identifiable, Hashable {/// Set when the remote runs the probe's wrapper rather than an/// installed `thinkterm`; empty means the default proxy command.var remoteCommand: String = ""+ /// A label the list groups by; empty is no group.+ var group: String = ""+ /// The public half of a key the app generated or could read, so it+ /// can be shown and copied to the host's authorized_keys.+ var publicKey: String?+ var lastConnected: Date?var display: String {name.isEmpty ? "\(user)@\(hostname):\(port)" : name}++ var address: String { "\(user)@\(hostname)" + (port == 22 ? "" : ":\(port)") }++ init() {}++ // Fields added later are absent from hosts saved before them.+ private enum Keys: String, CodingKey {+ case id, name, hostname, port, user, auth, knownHost, remoteCommand, group, publicKey, lastConnected+ }++ init(from decoder: Decoder) throws {+ let c = try decoder.container(keyedBy: Keys.self)+ id = try c.decode(UUID.self, forKey: .id)+ name = try c.decodeIfPresent(String.self, forKey: .name) ?? ""+ hostname = try c.decodeIfPresent(String.self, forKey: .hostname) ?? ""+ port = try c.decodeIfPresent(Int.self, forKey: .port) ?? 22+ user = try c.decodeIfPresent(String.self, forKey: .user) ?? ""+ auth = try c.decodeIfPresent(AuthKind.self, forKey: .auth) ?? .key+ knownHost = try c.decodeIfPresent(String.self, forKey: .knownHost)+ remoteCommand = try c.decodeIfPresent(String.self, forKey: .remoteCommand) ?? ""+ group = try c.decodeIfPresent(String.self, forKey: .group) ?? ""+ publicKey = try c.decodeIfPresent(String.self, forKey: .publicKey)+ lastConnected = try c.decodeIfPresent(Date.self, forKey: .lastConnected)+ }+}++extension Host {+ init(name: String, hostname: String, port: Int, user: String) {+ self.init()+ self.name = name+ self.hostname = hostname+ self.port = port+ self.user = user+ }}/// The hosts, in the app's defaults. Small, and edited rarely.@@ -64,6 +104,18 @@ final class HostStore: ObservableObject {}}+ /// A connection reached the terminal: the list shows when.+ func touchConnected(_ id: UUID) {+ guard let i = hosts.firstIndex(where: { $0.id == id }) else { return }+ hosts[i].lastConnected = Date()+ save()+ }++ /// The groups in use, for the editor's suggestions.+ var groups: [String] {+ Array(Set(hosts.map(\.group).filter { !$0.isEmpty })).sorted()+ }+func forgetHostKey(for id: UUID) {guard let i = hosts.firstIndex(where: { $0.id == id }) else { return }hosts[i].knownHost = nil@@ -93,11 +145,15 @@ enum Keychain {kSecValueData as String: data,kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly,]- let status = SecItemUpdate(query as CFDictionary, attrs as CFDictionary)+ var status = SecItemUpdate(query as CFDictionary, attrs as CFDictionary)if status == errSecItemNotFound {var add = queryadd.merge(attrs) { $1 }- SecItemAdd(add as CFDictionary, nil)+ status = SecItemAdd(add as CFDictionary, nil)+ }+ if status != errSecSuccess {+ // -34018 is a missing entitlement: an unsigned simulator build.+ NSLog("keychain: saving %@ failed with %d", account, status)}}diff --git a/ios/Sources/SSHKey.swift b/ios/Sources/SSHKey.swiftnew file mode 100644index 00000000..65ee94d6--- /dev/null+++ b/ios/Sources/SSHKey.swift@@ -0,0 +1,104 @@+import Foundation+import CryptoKit++/// An ed25519 key pair the app makes for a host, written the way OpenSSH+/// writes its own (`PROTOCOL.key`): the private half in the unencrypted+/// openssh-key-v1 container, which russh reads, and the public half as+/// one `authorized_keys` line.+struct SSHKey {+ let privatePEM: String+ let publicLine: String++ static func generate(comment: String) -> SSHKey {+ let key = Curve25519.Signing.PrivateKey()+ let seed = Data(key.rawRepresentation)+ let pub = Data(key.publicKey.rawRepresentation)++ var publicBlob = Data()+ publicBlob.sshString("ssh-ed25519")+ publicBlob.sshString(pub)++ // The private section: two matching check ints, the key, and+ // padding up to the (unencrypted) block size of 8.+ let check = UInt32.random(in: 0...UInt32.max)+ var section = Data()+ section.sshUInt32(check)+ section.sshUInt32(check)+ section.sshString("ssh-ed25519")+ section.sshString(pub)+ section.sshString(seed + pub)+ section.sshString(comment)+ var pad: UInt8 = 1+ while section.count % 8 != 0 {+ section.append(pad)+ pad += 1+ }++ var blob = Data("openssh-key-v1".utf8)+ blob.append(0)+ blob.sshString("none")+ blob.sshString("none")+ blob.sshString("")+ blob.sshUInt32(1)+ blob.sshString(publicBlob)+ blob.sshString(section)++ let body = blob.base64EncodedString(options: [.lineLength76Characters, .endLineWithLineFeed])+ .replacingOccurrences(of: "\r", with: "")+ let pem = "-----BEGIN OPENSSH PRIVATE KEY-----\n" + body + "\n-----END OPENSSH PRIVATE KEY-----\n"+ let line = "ssh-ed25519 " + publicBlob.base64EncodedString() + (comment.isEmpty ? "" : " " + comment)+ return SSHKey(privatePEM: pem, publicLine: line)+ }++ /// The public line of an unencrypted OpenSSH ed25519 private key,+ /// for a key that was pasted or imported; nil for anything else.+ static func publicLine(ofPrivate pem: String, comment: String) -> String? {+ let lines = pem.split(whereSeparator: \.isNewline).map(String.init)+ guard lines.first?.contains("BEGIN OPENSSH PRIVATE KEY") == true else { return nil }+ let body = lines.dropFirst().filter { !$0.hasPrefix("-----") }.joined()+ guard let blob = Data(base64Encoded: body) else { return nil }+ var reader = SSHReader(blob)+ guard reader.take(15) == Data("openssh-key-v1".utf8) + [0],+ let cipher = reader.string(), cipher == Data("none".utf8),+ reader.string() != nil, reader.string() != nil,+ reader.uint32() == 1,+ let publicBlob = reader.string() else { return nil }+ var pub = SSHReader(publicBlob)+ guard pub.string() == Data("ssh-ed25519".utf8) else { return nil }+ return "ssh-ed25519 " + publicBlob.base64EncodedString() + (comment.isEmpty ? "" : " " + comment)+ }+}++private extension Data {+ mutating func sshUInt32(_ v: UInt32) {+ var be = v.bigEndian+ append(Data(bytes: &be, count: 4))+ }+ mutating func sshString(_ d: Data) {+ sshUInt32(UInt32(d.count))+ append(d)+ }+ mutating func sshString(_ s: String) {+ sshString(Data(s.utf8))+ }+}++private struct SSHReader {+ let data: Data+ var at = 0+ init(_ data: Data) { self.data = data }++ mutating func take(_ n: Int) -> Data? {+ guard at + n <= data.count else { return nil }+ defer { at += n }+ return data.subdata(in: at..<(at + n))+ }+ mutating func uint32() -> UInt32? {+ guard let d = take(4) else { return nil }+ return d.reduce(0) { ($0 << 8) | UInt32($1) }+ }+ mutating func string() -> Data? {+ guard let n = uint32() else { return nil }+ return take(Int(n))+ }+}diff --git a/ios/Sources/Schemes.swift b/ios/Sources/Schemes.swiftnew file mode 100644index 00000000..2aa3524f--- /dev/null+++ b/ios/Sources/Schemes.swift@@ -0,0 +1,58 @@+import SwiftUI++/// The colour schemes in the bundle's schemes.json (the web page's list,+/// straight from the desktop's), by name. Read once, on first use.+enum Schemes {+ static let followDesktop = "desktop"++ /// Every scheme's name, in the file's order (alphabetical).+ static var names: [String] { table.names }++ /// One scheme as the core takes it: its JSON object, unchanged.+ static func json(named name: String) -> String? {+ table.byName[name]+ }++ /// The background of a scheme, for the picker's swatches.+ static func background(of name: String) -> Color? {+ guard let json = table.byName[name],+ let r = json.range(of: "\"background\":\""),+ let end = json[r.upperBound...].firstIndex(of: "\"") else { return nil }+ return Color(hex: String(json[r.upperBound..<end]))+ }++ private struct Table {+ var names: [String] = []+ var byName: [String: String] = [:]+ }++ private static let table: Table = {+ var t = Table()+ guard let url = Bundle.main.url(forResource: "schemes", withExtension: "json"),+ let data = try? Data(contentsOf: url),+ let list = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]] else { return t }+ for entry in list {+ guard let name = entry["name"] as? String,+ let json = try? JSONSerialization.data(withJSONObject: entry),+ let text = String(data: json, encoding: .utf8) else { continue }+ t.names.append(name)+ t.byName[name] = text+ }+ return t+ }()+}++extension Color {+ /// "#rrggbb" or "#rgb"; nil for anything else.+ init?(hex: String) {+ var s = hex.trimmingCharacters(in: .whitespaces)+ if s.hasPrefix("#") { s.removeFirst() }+ if s.count == 3 { s = s.map { "\($0)\($0)" }.joined() }+ guard s.count == 6, let v = UInt32(s, radix: 16) else { return nil }+ self.init(+ red: Double((v >> 16) & 0xff) / 255,+ green: Double((v >> 8) & 0xff) / 255,+ blue: Double(v & 0xff) / 255+ )+ }+}diff --git a/ios/Sources/SettingsSheet.swift b/ios/Sources/SettingsSheet.swiftnew file mode 100644index 00000000..d81213dc--- /dev/null+++ b/ios/Sources/SettingsSheet.swift@@ -0,0 +1,149 @@+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+/// tab shows it with no terminal; a terminal's menu shows it with one,+/// and then the text size is the live pane's.+struct SettingsView: View {+ @ObservedObject var settings = AppSettings.shared+ var model: TerminalModel?+ var showLog: Binding<Bool>?++ var body: some View {+ List {+ Section("Terminal") {+ NavigationLink {+ ThemePicker()+ } label: {+ HStack {+ Text("Theme")+ Spacer()+ swatch(settings.schemeName)+ Text(settings.schemeName == Schemes.followDesktop ? "Follow host" : settings.schemeName)+ .foregroundColor(.secondary)+ .lineLimit(1)+ }+ }+ if let model {+ LiveTextSize(model: model)+ } else {+ Stepper(value: $settings.fontSize, in: 6...40, step: 1) {+ HStack {+ Text("Text size")+ Spacer()+ Text(String(format: "%.0f pt", settings.fontSize))+ .foregroundColor(.secondary)+ .monospacedDigit()+ }+ }+ }+ Toggle("Smooth scrolling", isOn: $settings.smoothScroll)+ }+ if let showLog {+ Section {+ Toggle("Show log", isOn: showLog)+ } header: {+ Text("Diagnostics")+ } footer: {+ Text("The connection's log over the terminal, for reporting a problem.")+ }+ }+ Section("About") {+ HStack {+ Text("Version")+ Spacer()+ Text(Self.version).foregroundColor(.secondary)+ }+ }+ }+ .navigationTitle("Settings")+ }++ @ViewBuilder+ private func swatch(_ name: String) -> some View {+ if let color = Schemes.background(of: name) {+ Circle().fill(color).overlay(Circle().stroke(Color.white.opacity(0.3), lineWidth: 1)).frame(width: 16, height: 16)+ }+ }++ static var version: String {+ let info = Bundle.main.infoDictionary+ let short = info?["CFBundleShortVersionString"] as? String ?? "0"+ let build = info?["CFBundleVersion"] as? String ?? "0"+ return "\(short) (\(build))"+ }+}++/// 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++ var body: some View {+ HStack {+ Text("Text size")+ Spacer()+ Button { step(-1) } label: { Image(systemName: "textformat.size.smaller") }+ .buttonStyle(.bordered)+ Text(String(format: "%.1f pt", model.fontPt))+ .font(.callout.monospacedDigit())+ .frame(minWidth: 56)+ Button { step(1) } label: { Image(systemName: "textformat.size.larger") }+ .buttonStyle(.bordered)+ }+ }++ private func step(_ by: Double) {+ model.stepFont(by)+ settings.fontSize = max(6, min(40, (model.fontPt * (1 + 0.1 * by)).rounded()))+ }+}++/// The colour schemes by name, searchable, each with its background as a+/// swatch; the host's own scheme first.+struct ThemePicker: View {+ @ObservedObject var settings = AppSettings.shared+ @State private var query = ""++ private var names: [String] {+ let all = Schemes.names+ if query.isEmpty { return all }+ return all.filter { $0.localizedCaseInsensitiveContains(query) }+ }++ var body: some View {+ List {+ if query.isEmpty {+ row(Schemes.followDesktop, label: "Follow host", 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")+ .navigationBarTitleDisplayMode(.inline)+ }++ private func row(_ name: String, label: String, color: Color?) -> some View {+ Button {+ settings.schemeName = name+ } label: {+ HStack {+ if let color {+ RoundedRectangle(cornerRadius: 4).fill(color)+ .overlay(RoundedRectangle(cornerRadius: 4).stroke(Color.white.opacity(0.25), lineWidth: 1))+ .frame(width: 22, height: 22)+ } else {+ Image(systemName: "desktopcomputer").frame(width: 22)+ }+ Text(label).foregroundColor(.primary)+ Spacer()+ if settings.schemeName == name {+ Image(systemName: "checkmark").foregroundColor(.accentColor)+ }+ }+ }+ }+}diff --git a/ios/Sources/TerminalInputView.swift b/ios/Sources/TerminalInputView.swiftindex 98dfd73b..8b8c60d4 100644--- a/ios/Sources/TerminalInputView.swift+++ b/ios/Sources/TerminalInputView.swift@@ -6,9 +6,13 @@ import UIKit/// keyboard, its IMEs (Pinyin, Kana...) and a hardware keyboard all talk/// to it, and whose gestures are the terminal's -- a tap focuses the pane/// under it and raises the keyboard, a one-finger drag scrolls, a-/// two-finger swipe down puts the keyboard away, a long press opens the-/// pane's menu, a pinch changes the font. A phone can tell a tap from a-/// drag, so there is no keyboard button.+/// two-finger swipe down puts the keyboard away, and a pinch changes the+/// font. Selecting text is the system's own: a UITextInteraction over+/// this view brings the native handles, magnifier and Copy menu, and+/// reads the terminal through UITextInput -- the focused pane's visible+/// rows are the document (`App::screen_text`), with the IME's marked+/// text appended after them. A phone can tell a tap from a drag, so+/// there is no keyboard button.////// It holds no text of its own beyond the IME's marked (composing)/// string: committed text goes straight to the core, keys go as key@@ -19,7 +23,6 @@ import UIKit/// again); backspace inside a composition edits the marked text only.final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDelegate, UIScrollViewDelegate {weak var model: TerminalModel?- var onMenu: ((CGPoint) -> Void)?private(set) var marked: String?private var markedSelection = NSRange(location: 0, length: 0)@@ -33,6 +36,10 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDelprivate var recentring = false/// Stepped mode: finger travel not yet a whole row.private var rowRemainder: CGFloat = 0+ /// The document the text system reads: the pane's visible rows, as+ /// the core last gave them. Fetched when a selection interaction asks+ /// and dropped when the core reports a change.+ private var screen: ScreenText?override init(frame: CGRect) {super.init(frame: frame)@@ -47,16 +54,20 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDelpanGestureRecognizer.maximumNumberOfTouches = 1delegate = selflet tap = UITapGestureRecognizer(target: self, action: #selector(tapped(_:)))- let press = UILongPressGestureRecognizer(target: self, action: #selector(pressed(_:)))let pinch = UIPinchGestureRecognizer(target: self, action: #selector(pinched(_:)))let hide = UISwipeGestureRecognizer(target: self, action: #selector(swipedDown(_:)))- press.minimumPressDuration = 0.45hide.direction = .downhide.numberOfTouchesRequired = 2- for g in [tap, press, pinch, hide] as [UIGestureRecognizer] {+ for g in [tap, pinch, hide] as [UIGestureRecognizer] {g.delegate = selfaddGestureRecognizer(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)+ selection.textInput = self+ addInteraction(selection)}override func layoutSubviews() {@@ -116,8 +127,15 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDel// MARK: gestures- @objc private func tapped(_ g: UITapGestureRecognizer) {+ /// A gesture's point in the view's own box. The scroll view's+ /// coordinates start at the content offset, half-way down the runway.+ private func point(of g: UIGestureRecognizer) -> CGPoint {let p = g.location(in: self)+ return CGPoint(x: p.x - contentOffset.x, y: p.y - contentOffset.y)+ }++ @objc private func tapped(_ g: UITapGestureRecognizer) {+ let p = point(of: g)// A press and release at the point: the App focuses the pane.model?.pointer("down", at: p)model?.pointer("up", at: p)@@ -132,14 +150,6 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDel}}- @objc private func pressed(_ g: UILongPressGestureRecognizer) {- guard g.state == .began else { return }- let p = g.location(in: self)- model?.pointer("down", at: p)- model?.pointer("up", at: p)- onMenu?(p)- }-@objc private func pinched(_ g: UIPinchGestureRecognizer) {switch g.state {case .began: pinchStart = 1@@ -204,11 +214,64 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDelmodel?.key("Backspace")}- // MARK: UITextInput -- marked text+ // MARK: the document++ /// The core changed something on screen: the rows are read again+ /// when next asked for.+ func screenChanged() {+ screen = nil+ }++ private func currentScreen() -> ScreenText? {+ if let screen { return screen }+ guard let model, let s = ViewJSON.decode(ScreenText.self, model.core.screenText()) else { return nil }+ screen = s+ return s+ }++ /// The rows' length in the document; marked text follows it.+ private var screenLength: Int {+ currentScreen().map { $0.rows * ($0.cols + 1) } ?? 0+ }++ private var markedLength: Int { marked?.utf16.count ?? 0 }+ private var documentLength: Int { screenLength + markedLength }++ private func cell(at index: Int) -> (row: Int, col: Int)? {+ guard let s = currentScreen(), index >= 0, index < screenLength else { return nil }+ let stride = s.cols + 1+ return (index / stride, min(index % stride, s.cols - 1))+ }++ private func index(row: Int, col: Int) -> Int {+ guard let s = currentScreen() else { return 0 }+ return row * (s.cols + 1) + col+ }++ /// The cell under a point in the view, clamped into the pane.+ private func cell(under point: CGPoint) -> (row: Int, col: Int)? {+ guard let s = currentScreen(), s.cell[0] > 0, s.cell[1] > 0 else { return nil }+ let col = Int(((point.x - s.origin[0]) / s.cell[0]).rounded(.down))+ let row = Int(((point.y - s.origin[1]) / s.cell[1]).rounded(.down))+ return (min(max(row, 0), s.rows - 1), min(max(col, 0), s.cols - 1))+ }++ private func rect(row: Int, col: Int, cols: Int = 1) -> CGRect {+ guard let s = currentScreen() else { return .zero }+ return CGRect(+ x: s.origin[0] + Double(col) * s.cell[0],+ y: s.origin[1] + Double(row) * s.cell[1],+ width: Double(cols) * s.cell[0],+ height: s.cell[1]+ )+ }++ // MARK: UITextInput -- marked text (after the rows)var markedTextRange: UITextRange? {guard let marked, !marked.isEmpty else { return nil }- return Range(0, marked.utf16.count)+ let n = screenLength+ return Range(n, n + marked.utf16.count)}var markedTextStyle: [NSAttributedString.Key: Any]? {@@ -239,26 +302,66 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDelendComposing()}- // MARK: UITextInput -- the (empty) document+ // MARK: UITextInput -- the selection+ /// The pane's selection while there is one, else the caret at the+ /// end of the marked text (the keyboard's insertion point).var selectedTextRange: UITextRange? {get {- let n = marked?.utf16.count ?? 0+ 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)+ }+ let n = documentLengthreturn Range(n, n)}- set {}+ set {+ guard let r = newValue as? Range else {+ 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.+ if r.b > r.a, let a = cell(at: r.a), let b = cell(at: r.b - 1) {+ 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 {+ model?.core.clearSelection()+ if var s = screen {+ s.selection = nil+ screen = s+ }+ }+ }}var beginningOfDocument: UITextPosition { Pos(0) }- var endOfDocument: UITextPosition { Pos(marked?.utf16.count ?? 0) }+ var endOfDocument: UITextPosition { Pos(documentLength) }func text(in range: UITextRange) -> String? {- guard let r = range as? Range, let marked else { return nil }- let s = marked.utf16- guard r.a <= s.count, r.b <= s.count, r.a <= r.b else { return nil }- let start = s.index(s.startIndex, offsetBy: r.a)- let end = s.index(s.startIndex, offsetBy: r.b)- return String(s[start..<end])+ guard let r = range as? Range, r.a <= r.b else { return nil }+ let n = screenLength+ var out = ""+ if r.a < n, let s = currentScreen() {+ let u = s.text.utf16+ let end = min(r.b, n)+ if let a = u.index(u.startIndex, offsetBy: r.a, limitedBy: u.endIndex),+ let b = u.index(u.startIndex, offsetBy: end, limitedBy: u.endIndex) {+ out += String(u[a..<b]) ?? ""+ }+ }+ if r.b > n, let marked {+ let m = marked.utf16+ let a = max(r.a - n, 0), b = min(r.b - n, m.count)+ if a < b {+ out += String(m[m.index(m.startIndex, offsetBy: a)..<m.index(m.startIndex, offsetBy: b)]) ?? ""+ }+ }+ return out}func replace(_ range: UITextRange, withText text: String) {@@ -273,14 +376,20 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDelfunc position(from position: UITextPosition, offset: Int) -> UITextPosition? {guard let p = position as? Pos else { return nil }let n = p.i + offset- let max = marked?.utf16.count ?? 0- return (0...max).contains(n) ? Pos(n) : nil+ return (0...documentLength).contains(n) ? Pos(n) : nil}func position(from position: UITextPosition, in direction: UITextLayoutDirection, offset: Int) -> UITextPosition? {+ guard let p = position as? Pos else { return nil }switch direction {- case .right, .down: return self.position(from: position, offset: offset)- case .left, .up: return self.position(from: position, offset: -offset)+ case .right: return self.position(from: p, offset: offset)+ case .left: return self.position(from: p, offset: -offset)+ case .down, .up:+ // A row at a time within the rows.+ guard let s = currentScreen(), let c = cell(at: p.i) else { return nil }+ let row = direction == .down ? c.row + offset : c.row - offset+ guard (0..<s.rows).contains(row) else { return nil }+ return Pos(index(row: row, col: c.col))@unknown default: return nil}}@@ -312,7 +421,10 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDelfunc characterRange(byExtending position: UITextPosition, in direction: UITextLayoutDirection) -> UITextRange? {guard let p = position as? Pos else { return nil }- return Range(p.i, p.i)+ switch direction {+ case .right, .down: return Range(p.i, min(p.i + 1, documentLength))+ default: return Range(max(p.i - 1, 0), p.i)+ }}func baseWritingDirection(for position: UITextPosition, in direction: UITextStorageDirection) -> NSWritingDirection {@@ -321,24 +433,98 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDelfunc setBaseWritingDirection(_ writingDirection: NSWritingDirection, for range: UITextRange) {}- func firstRect(for range: UITextRange) -> CGRect { model?.cursorRect ?? CGRect(x: 0, y: 0, width: 1, height: 20) }- func caretRect(for position: UITextPosition) -> CGRect { model?.cursorRect ?? CGRect(x: 0, y: 0, width: 1, height: 20) }- func selectionRects(for range: UITextRange) -> [UITextSelectionRect] { [] }- func closestPosition(to point: CGPoint) -> UITextPosition? { endOfDocument }- func closestPosition(to point: CGPoint, within range: UITextRange) -> UITextPosition? { endOfDocument }- func characterRange(at point: CGPoint) -> UITextRange? { nil }+ // MARK: UITextInput -- geometry++ func firstRect(for range: UITextRange) -> CGRect {+ guard let r = range as? Range, let a = cell(at: r.a) else { return model?.cursorRect ?? .zero }+ let last = cell(at: max(r.b - 1, r.a)) ?? a+ let cols = last.row == a.row ? last.col - a.col + 1 : (currentScreen()?.cols ?? 1) - a.col+ return rect(row: a.row, col: a.col, cols: max(cols, 1))+ }++ func caretRect(for position: UITextPosition) -> CGRect {+ guard let p = position as? Pos, let c = cell(at: p.i) else { return model?.cursorRect ?? .zero }+ var r = rect(row: c.row, col: c.col)+ r.size.width = 2+ return r+ }++ /// One rect per row the range touches, so the handles sit on the+ /// first and last cells and the highlight follows the rows.+ func selectionRects(for range: UITextRange) -> [UITextSelectionRect] {+ guard let r = range as? Range, r.b > r.a, let s = currentScreen(),+ let a = cell(at: r.a), let b = cell(at: r.b - 1) else { return [] }+ var rects: [UITextSelectionRect] = []+ for row in a.row...b.row {+ let from = row == a.row ? a.col : 0+ let to = row == b.row ? b.col : s.cols - 1+ rects.append(SelectionRect(+ rect: rect(row: row, col: from, cols: to - from + 1),+ start: row == a.row, end: row == b.row+ ))+ }+ return rects+ }++ func closestPosition(to point: CGPoint) -> UITextPosition? {+ guard let c = cell(under: point) else { return endOfDocument }+ return Pos(index(row: c.row, col: c.col))+ }++ func closestPosition(to point: CGPoint, within range: UITextRange) -> UITextPosition? {+ guard let r = range as? Range, let p = closestPosition(to: point) as? Pos else { return nil }+ return Pos(min(max(p.i, r.a), r.b))+ }++ func characterRange(at point: CGPoint) -> UITextRange? {+ guard let p = closestPosition(to: point) as? Pos, p.i < screenLength else { return nil }+ return Range(p.i, p.i + 1)+ }++ // MARK: the edit menu++ override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {+ switch action {+ case #selector(copy(_:)): return currentScreen()?.selection != nil+ case #selector(paste(_:)): return UIPasteboard.general.hasStrings+ case #selector(selectAll(_:)): return currentScreen() != nil+ default: return false+ }+ }++ override func copy(_ sender: Any?) {+ if let text = model?.core.selectedText(), !text.isEmpty {+ UIPasteboard.general.string = text+ model?.showCopied()+ }+ model?.core.clearSelection()+ screen = nil+ }++ override func paste(_ sender: Any?) {+ model?.pasteFromClipboard()+ }++ override func selectAll(_ sender: Any?) {+ guard let s = currentScreen() else { return }+ selectedTextRange = Range(0, index(row: s.rows - 1, col: s.cols - 1) + 1)+ }// MARK: traits: a terminal wants raw keys, no autocorrect- var keyboardType: UIKeyboardType { .asciiCapable }- var autocorrectionType: UITextAutocorrectionType { .no }- var autocapitalizationType: UITextAutocapitalizationType { .none }- var spellCheckingType: UITextSpellCheckingType { .no }- var smartQuotesType: UITextSmartQuotesType { .no }- var smartDashesType: UITextSmartDashesType { .no }- var smartInsertDeleteType: UITextSmartInsertDeleteType { .no }- var returnKeyType: UIReturnKeyType { .default }- var enablesReturnKeyAutomatically: Bool { false }+ // Stored, not computed: the traits protocol declares them settable,+ // and UIKit reads them through the setter's counterpart. The inline+ // prediction is the one that draws the suggestion bar on iOS 17+.+ var keyboardType: UIKeyboardType = .asciiCapable+ var autocorrectionType: UITextAutocorrectionType = .no+ var autocapitalizationType: UITextAutocapitalizationType = .none+ var spellCheckingType: UITextSpellCheckingType = .no+ var smartQuotesType: UITextSmartQuotesType = .no+ var smartDashesType: UITextSmartDashesType = .no+ var smartInsertDeleteType: UITextSmartInsertDeleteType = .no+ var inlinePredictionType: UITextInlinePredictionType = .no+ var returnKeyType: UIReturnKeyType = .default+ var enablesReturnKeyAutomatically: Bool = false// MARK: hardware keyboard@@ -391,21 +577,39 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDeloverride var start: UITextPosition { Pos(a) }override var end: UITextPosition { Pos(b) }}++ final class SelectionRect: UITextSelectionRect {+ let r: CGRect+ let first: Bool+ let last: Bool+ init(rect: CGRect, start: Bool, end: Bool) { r = rect; first = start; last = end }+ override var rect: CGRect { r }+ override var writingDirection: NSWritingDirection { .leftToRight }+ override var containsStart: Bool { first }+ override var containsEnd: Bool { last }+ override var isVertical: Bool { false }+ }+}++/// `App::screen_text`, as the core hands it over.+struct ScreenText: Decodable {+ var cols: Int+ var rows: Int+ var text: String+ var origin: [Double]+ var cell: [Double]+ var selection: [[Int]]?}struct TerminalInput: UIViewRepresentable {@EnvironmentObject var model: TerminalModel- var onMenu: (CGPoint) -> Voidfunc makeUIView(context: Context) -> TerminalInputView {let view = TerminalInputView()view.model = model- view.onMenu = onMenumodel.inputView = viewreturn view}- func updateUIView(_ uiView: TerminalInputView, context: Context) {- uiView.onMenu = onMenu- }+ func updateUIView(_ uiView: TerminalInputView, context: Context) {}}diff --git a/ios/Sources/TerminalModel.swift b/ios/Sources/TerminalModel.swiftindex b7d1a8f8..3549710e 100644--- a/ios/Sources/TerminalModel.swift+++ b/ios/Sources/TerminalModel.swift@@ -2,6 +2,7 @@ import Foundationimport UIKitimport QuartzCoreimport Combine+import SwiftUIimport CoreTextimport CoreGraphics@@ -27,19 +28,33 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {@Published var logText = ""@Published var stats = ""@Published var inset: CGFloat = 0+ /// A selection was just copied; the status line says so for a moment.+ @Published var copied = false+ /// The App's remark for the status line: a passing one goes after a+ /// few seconds, a sticky one (the connection is down) stays until the+ /// App takes it back.+ @Published private(set) var toastText: String?+ /// The App says its connection is down and it is redialing.+ @Published private(set) var reconnecting = false+ private var toastTimer: Timer?+ /// The terminal's background, as the App paints it: the chrome around+ /// the terminal takes the same colour.+ @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@Published var animating = false- /// Smooth (by the pixel, with inertia) or stepped (whole rows).- @Published var smoothScroll: Bool = UserDefaults.standard.object(forKey: "scroll.smooth") as? Bool ?? true {- didSet {- UserDefaults.standard.set(smoothScroll, forKey: "scroll.smooth")- applyScrollMode()- }- }+ /// The log view is open: the stats are worth refreshing.+ var wantsStats = false+ /// The preferences, followed as they change.+ let settings = AppSettings.shared+ var smoothScroll: Bool { settings.smoothScroll }+ private var subscriptions: [AnyCancellable] = []/// The App's cell height in points, from its layout view.private(set) var cellHeight: Double = 20let core: Core- let host: Host?+ /// The host this screen shows; edited in place from the failure card.+ @Published var host: Host?weak var store: HostStore?weak var inputView: TerminalInputView?var cursorRect = CGRect(x: 8, y: 8, width: 2, height: 20)@@ -81,14 +96,22 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {let link = CADisplayLink(target: self, selector: #selector(tick))link.add(to: .main, forMode: .common)displayLink = link+ // Every published change redraws the screen (and closes an open+ // menu): the stats tick only while the log shows them.statsTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { [weak self] _ in- guard let self else { return }- self.stats = self.core.stats()+ guard let self, self.wantsStats else { return }+ let stats = self.core.stats()+ if stats != self.stats { self.stats = stats }}+ if let name = arg("--scheme") { settings.schemeName = name }applyScrollMode()+ 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)if args.contains("--autotest") { scheduleAutotest() }if args.contains("--autoconnect") { scheduleAutoconnect() }if args.contains("--imetest") { scheduleImeTest() }+ if args.contains("--seltest") { scheduleSelectionTest() }if args.contains("--uitest") { scheduleUiTest() }}@@ -108,6 +131,15 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {}}+ /// This install's name to the servers, made once: the tab this phone+ /// holds stays its own across launches.+ static let deviceId: String = {+ if let id = UserDefaults.standard.string(forKey: "client.id") { return id }+ let id = UUID().uuidString+ UserDefaults.standard.set(id, forKey: "client.id")+ return id+ }()+/// Connect to the model's host with the secret from the Keychain.func connect() {guard let host else {@@ -117,6 +149,7 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {let account = host.id.uuidStringlet secret = Keychain.load(account: account) ?? ""let passphrase = Keychain.load(account: account + ".passphrase")+ log("shell: \(host.auth == .password ? "password" : "key text") \(secret.count) chars from the Keychain" + (passphrase == nil ? "" : ", with a passphrase"))connect(hostname: host.hostname, port: host.port, user: host.user,authKind: host.auth == .password ? "password" : "key", secret: secret,@@ -141,7 +174,7 @@ 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, fontPaths: paths, sizePt: 11.0,+ remoteCommand: remoteCommand, deviceId: Self.deviceId, fontPaths: paths, sizePt: settings.fontSize,painter: CoreTextPainter())}@@ -188,6 +221,41 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {core.wheelPx(x: point.x, y: point.y, px: px)}+ private func showToast(_ toast: Toast?) {+ toastTimer?.invalidate()+ let sticky = toast?.sticky ?? false+ if reconnecting != sticky { reconnecting = sticky }+ guard let toast, !toast.text.isEmpty else {+ if toastText != nil { toastText = nil }+ return+ }+ toastText = toast.text+ if !sticky {+ toastTimer = Timer.scheduledTimer(withTimeInterval: 4, repeats: false) { [weak self] _ in+ guard let self, self.toastText == toast.text else { return }+ self.toastText = nil+ }+ }+ }++ private func applyScheme() {+ let schemeName = settings.schemeName+ if schemeName == Schemes.followDesktop || Schemes.json(named: schemeName) == nil {+ core.setSetting(key: "terminal-scheme", value: "\"desktop\"")+ core.setPalette(scheme: nil)+ } else {+ core.setSetting(key: "terminal-scheme", value: "\"" + schemeName.replacingOccurrences(of: "\"", with: "\\\"") + "\"")+ core.setPalette(scheme: Schemes.json(named: schemeName))+ }+ }++ fileprivate func corePublished(_ key: String, _ value: String) {+ guard key == "bg", let color = Color(hex: value) else { return }+ DispatchQueue.main.async {+ if self.background != color { self.background = color }+ }+ }+private func applyScrollMode() {core.setSetting(key: "scroll-mode", value: smoothScroll ? "\"smooth\"" : "\"stepped\"")}@@ -228,16 +296,31 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {/// Pull every view the screen shows. Called on the main thread after/// the core said something changed; a burst of changes is one pull.func refreshViews() {- tabs = ViewJSON.decode(TabsView.self, core.view(name: "tabs"))- sidebar = ViewJSON.decode(SidebarView.self, core.view(name: "sidebar"))- navs = ViewJSON.decode([NavView].self, core.view(name: "navs")) ?? []- status = ViewJSON.decode(StatusView.self, core.view(name: "status"))+ inputView?.screenChanged()+ // Assigned only on a change: a published write redraws the whole+ // screen, and the core reports changes as often as output comes.+ let tabs = ViewJSON.decode(TabsView.self, core.view(name: "tabs"))+ 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 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"))+ if status != self.status {+ self.status = status+ showToast(status?.toast)+ }let layout = core.view(name: "layout")if let r = layout.range(of: "\"cell\":["),let end = layout[r.upperBound...].firstIndex(of: "]") {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: "\"font_pt\":"),+ let end = layout[r.upperBound...].firstIndex(where: { $0 == "," || $0 == "}" }),+ let pt = Double(layout[r.upperBound..<end]), pt > 0, pt != fontPt {+ fontPt = pt+ }}// MARK: surface lifecycle, all on the main thread@@ -249,6 +332,7 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {attach(layer, width: width, height: height, scale: scale)} else if lastSize != (width, height, scale) {lastSize = (width, height, scale)+ log("shell: surface \(width)x\(height) @\(scale)")core.resize(generation: generation, width: UInt32(width), height: UInt32(height), scale: scale)}}@@ -336,6 +420,10 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {func toggleInset() { inset = inset > 0 ? 0 : 60 }func focusKeyboard() { inputView?.becomeFirstResponder() }+ func showCopied() {+ copied = true+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) { self.copied = false }+ }func dismissKeyboard() { inputView?.resignFirstResponder() }func compositionChanged(_ text: String?) {DispatchQueue.main.async { self.composing = text }@@ -350,6 +438,9 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {DispatchQueue.main.async {self.connection = statusself.log("status: " + status)+ if status.hasPrefix("pane "), let host = self.host {+ self.store?.touchConnected(host.id)+ }if status.hasPrefix("connecting") || status.contains("reconnect") || status.hasPrefix("disconnected") {self.inputView?.dropComposition()}@@ -358,7 +449,9 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {}fileprivate func coreTitle(_ title: String) {- DispatchQueue.main.async { self.title = title }+ DispatchQueue.main.async {+ if self.title != title { self.title = title }+ }}fileprivate func coreHostKey(_ fingerprint: String) {@@ -376,6 +469,9 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {}private func log(_ line: String) {+ #if DEBUG+ NSLog("%@", line)+ #endiflogLines.append(line)if logLines.count > 60 { logLines.removeFirst(logLines.count - 60) }logText = logLines.joined(separator: "\n")@@ -471,6 +567,46 @@ 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.+ private func scheduleSelectionTest() {+ let q = DispatchQueue.main+ q.asyncAfter(deadline: .now() + 1.5) { self.connectProbe() }+ q.asyncAfter(deadline: .now() + 4.0) { self.core.text(text: "echo SELECT-ME-PLEASE\n") }+ q.asyncAfter(deadline: .now() + 6.0) {+ guard let input = self.inputView else { return self.check("input view", false, "none") }+ let json = self.core.screenText()+ guard let screen = ViewJSON.decode(ScreenText.self, json) else {+ return self.check("screen text", false, String(json.prefix(80)))+ }+ let stride = screen.cols + 1+ self.check("screen text shape", screen.text.utf16.count == screen.rows * stride, "\(screen.rows)x\(screen.cols), \(screen.text.utf16.count) units")+ // The echoed line: the last row holding it.+ let rows = screen.text.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)+ guard let row = rows.lastIndex(where: { $0.contains("SELECT-ME-PLEASE") }),+ let col = rows[row].range(of: "SELECT-ME-PLEASE")?.lowerBound.utf16Offset(in: rows[row]) else {+ return self.check("echoed line on screen", false, "not found")+ }+ let a = row * stride + col+ let range = TerminalInputView.Range(a, a + "SELECT-ME-PLEASE".count)+ input.selectedTextRange = range+ let read = input.text(in: range) ?? ""+ self.check("document text", read == "SELECT-ME-PLEASE", read)+ q.asyncAfter(deadline: .now() + 0.5) {+ let copied = self.core.selectedText() ?? ""+ self.check("core selection", copied == "SELECT-ME-PLEASE", copied)+ let back = input.selectedTextRange as? TerminalInputView.Range+ self.check("selection read back", back?.a == a && back?.b == a + "SELECT-ME-PLEASE".count, "\(back?.a ?? -1)..\(back?.b ?? -1)")+ let rects = input.selectionRects(for: range)+ self.check("selection rects", rects.count == 1 && rects[0].rect.width > 0, "\(rects.count) rects, first \(rects.first?.rect ?? .zero)")+ let under = input.closestPosition(to: CGPoint(x: rects.first?.rect.midX ?? 0, y: rects.first?.rect.midY ?? 0)) as? TerminalInputView.Pos+ self.check("point to cell", under.map { $0.i >= a && $0.i < a + 16 } ?? false, "\(under?.i ?? -1)")+ self.report("selection done")+ print("SELTEST DONE")+ }+ }+ }+private func scheduleImeTest() {let q = DispatchQueue.mainvar sent: Int { Int(inputsSent()) }@@ -563,7 +699,10 @@ private final class NotifySink: Notify, @unchecked Sendable {func onTitle(title: String) { model?.coreTitle(title) }func onChange() { model?.coreChanged() }func onClipboard(text: String) {- DispatchQueue.main.async { UIPasteboard.general.string = text }+ DispatchQueue.main.async {+ UIPasteboard.general.string = text+ self.model?.showCopied()+ }}func onFocusInput() {DispatchQueue.main.async { self.model?.focusKeyboard() }@@ -574,6 +713,7 @@ private final class NotifySink: Notify, @unchecked Sendable {}}func onHostKey(fingerprint: String) { model?.coreHostKey(fingerprint) }+ func onPublished(key: String, value: String) { model?.corePublished(key, value) }}/// Paints the graphemes the bundled faces lack with CoreText, which fallsdiff --git a/ios/Sources/TerminalScreen.swift b/ios/Sources/TerminalScreen.swiftindex 728f3834..98c50381 100644--- a/ios/Sources/TerminalScreen.swift+++ b/ios/Sources/TerminalScreen.swift@@ -5,60 +5,68 @@ import SwiftUIstruct TerminalScreen: View {@StateObject private var model: TerminalModel@Environment(\.scenePhase) private var scenePhase+ @Environment(\.dismiss) private var dismiss@State private var showSidebar = false- @State private var showTabs = false+ @State private var showSessions = 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?init(host: Host?, store: HostStore?) {_model = StateObject(wrappedValue: TerminalModel(host: host, store: store))}+ /// The tabs live in the navigation bar, between the system's own back+ /// button and the menu; the keys sit below the terminal, and nothing+ /// else. Every piece of chrome takes the terminal's own background.var body: some View {VStack(spacing: 0) {- tabStripterminalstatusLineKeyBar(model: model)}- .background(Color.black)- .ignoresSafeArea(.container, edges: .bottom)- .navigationTitle(model.title.isEmpty ? (model.host?.display ?? "Terminal") : model.title)+ .background(model.background).navigationBarTitleDisplayMode(.inline)+ .toolbar(.hidden, for: .tabBar)+ .toolbarBackground(model.background, for: .navigationBar)+ .toolbarBackground(.visible, for: .navigationBar).toolbar {- ToolbarItem(placement: .topBarLeading) {- Button { showSidebar = true } label: { Image(systemName: "sidebar.left") }- }- ToolbarItemGroup(placement: .topBarTrailing) {- Button { model.stepFont(-1) } label: { Image(systemName: "textformat.size.smaller") }- Button { model.stepFont(1) } label: { Image(systemName: "textformat.size.larger") }- Menu {- Button("New tab") { model.chromeClick("new-tab") }- Button("Split right") { model.chromeClick("split-right") }- Button("Split below") { model.chromeClick("split-below") }- Button("Zoom pane") { model.chromeClick("zoom") }- Button("Close pane", role: .destructive) { model.chromeClick("close") }- Divider()- Toggle("Smooth scrolling", isOn: $model.smoothScroll)- Button("Paste") { model.pasteFromClipboard() }- Button(model.connection.hasPrefix("disconnected") || model.connection.hasPrefix("failed") ? "Reconnect" : "Disconnect") {- if model.connection.hasPrefix("disconnected") || model.connection.hasPrefix("failed") {- model.connect()- } else {- model.disconnect()- }- }- Toggle("Show log", isOn: $showLog)- } label: { Image(systemName: "ellipsis.circle") }- }+ ToolbarItem(placement: .principal) { tabStrip }+ ToolbarItem(placement: .topBarTrailing) { 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: $showSettings) {+ NavigationStack {+ SettingsView(model: model, showLog: $showLog)+ .toolbar {+ ToolbarItem(placement: .confirmationAction) { Button("Done") { showSettings = false } }+ }+ }+ }+ .onChange(of: showLog) { _, on in model.wantsStats = on }.sheet(item: $menu) { sheet inMenuList(model: model, sheet: sheet) { menu = nil }.presentationDetents([.medium, .large])}+ .sheet(item: $editingHost) { host in+ HostEditView(host: host) { edited, secret, passphrase in+ if !secret.isEmpty { Keychain.save(secret, account: edited.id.uuidString) }+ if let passphrase { Keychain.save(passphrase, account: edited.id.uuidString + ".passphrase") }+ model.store?.upsert(edited)+ model.host = edited+ model.connect()+ }+ }.onAppear {// The automated flows connect on their own schedule.if !ProcessInfo.processInfo.arguments.contains(where: { $0.hasSuffix("test") || $0 == "--autoconnect" }) {@@ -77,16 +85,89 @@ struct TerminalScreen: View {}}+ // MARK: the bar under the terminal++ private var connected: Bool {+ !(model.connection.hasPrefix("disconnected") || model.connection.hasPrefix("failed") || model.connection.isEmpty)+ }++ private var hostName: String {+ model.host?.display ?? "This Mac"+ }++ private var statusColor: Color {+ if model.reconnecting { return .orange }+ if connected { return .green }+ if model.connection.hasPrefix("connecting") || model.connection.contains("reconnect") { return .orange }+ return .red+ }++ /// The connection's state and the tabs, in the bar's middle.+ private var tabStrip: some View {+ HStack(spacing: 6) {+ Circle().fill(statusColor).frame(width: 7, height: 7)+ 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)+ .padding(.horizontal, 10)+ .padding(.vertical, 5)+ .background(tab.current ? Color.white.opacity(0.18) : Color.white.opacity(0.06))+ .clipShape(Capsule())+ }+ .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.chromeClick("new-tab") } label: {+ Image(systemName: "plus").font(.system(size: 13, weight: .semibold)).padding(6)+ }+ .buttonStyle(.plain)+ }+ }+ }+ .foregroundColor(.white)+ }++ private var moreMenu: some View {+ Menu {+ Section(hostName) {+ Button(connected ? "Disconnect" : "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") }+ Divider()+ Button("Sessions…") { showSessions = true }+ Button("Threads…") { showSidebar = true }+ Button("Paste") { model.pasteFromClipboard() }+ Divider()+ Button("Settings…") { showSettings = true }+ Button("Close pane", role: .destructive) { model.chromeClick("close") }+ } label: {+ Image(systemName: "ellipsis")+ }+ }+// MARK: the terminal with its overlaysprivate var terminal: some View {ZStack(alignment: .topLeading) {MetalView()- TerminalInput { point in- let pane = paneUnder(point)- menu = MenuSheet(kind: "pane", id: String(pane ?? 0), title: "Pane")+ TerminalInput()+ if model.navs.count > 1 {+ navBars}- navBarsif let composing = model.composing {Text(composing).font(.system(size: 14, design: .monospaced))@@ -101,11 +182,26 @@ struct TerminalScreen: View {if showLog {logView}+ if let phase = ConnectionPhase(status: model.connection) {+ ConnectionCard(phase: phase, hostName: hostName, canEdit: model.host != nil) { action in+ switch action {+ case .retry: model.connect()+ case .forgetKeyAndRetry:+ if let host = model.host {+ model.store?.forgetHostKey(for: host.id)+ model.host?.knownHost = nil+ }+ model.connect()+ case .edit: editingHost = model.host+ case .back: dismiss()+ }+ }+ }}.environmentObject(model).frame(maxWidth: .infinity, maxHeight: .infinity).padding(model.inset)- .background(Color.black)+ .background(model.background)}/// The App leaves rows above each pane for its bar; these draw it,@@ -156,20 +252,42 @@ struct TerminalScreen: View {.foregroundColor(nav.focused ? .white : .gray).padding(.horizontal, 6).frame(width: min(nav.rect.width, maxWidth), height: nav.rect.height, alignment: .leading)- .background(Color(white: nav.focused ? 0.16 : 0.1))+ .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")}+ .gesture(barDragGesture(nav)).offset(x: nav.rect.left, y: nav.rect.top)}- private func paneUnder(_ point: CGPoint) -> Int? {- // The bar rects tile the panes' tops; the pane whose bar's column- // holds the point is the one under it, near enough for a menu.- model.navs.first { nav in- point.x >= nav.rect.left && point.x < nav.rect.left + nav.rect.width && point.y >= nav.rect.top- }?.rect.pane ?? model.navs.first?.rect.pane+ /// Dragging a bar drags the divider it sits under (or beside, for a+ /// pane split to the right): the press lands on the divider's row or+ /// column, just outside the bar, and the App does the rest.+ private func barDragGesture(_ nav: NavView) -> some Gesture {+ DragGesture(minimumDistance: 10, coordinateSpace: .local)+ .onChanged { value in+ let r = nav.rect+ let origin: CGPoint+ if r.top > 0 {+ origin = CGPoint(x: r.left + value.startLocation.x, y: r.top - 2)+ } else if r.left > 0 {+ origin = CGPoint(x: r.left - 2, y: r.top + value.startLocation.y)+ } else {+ return+ }+ if barDrag == nil {+ barDrag = origin+ model.pointer("down", at: origin)+ }+ model.pointer("move", at: CGPoint(x: origin.x + value.translation.width, y: origin.y + value.translation.height))+ }+ .onEnded { value in+ guard let origin = barDrag else { return }+ barDrag = nil+ model.pointer("up", at: CGPoint(x: origin.x + value.translation.width, y: origin.y + value.translation.height))+ }}private func takeOverCard(_ card: Card) -> some View {@@ -200,47 +318,11 @@ struct TerminalScreen: View {.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomLeading)}- // MARK: the tab strip-- private var tabStrip: some View {- 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)- .padding(.horizontal, 10)- .padding(.vertical, 5)- .background(tab.current ? Color.white.opacity(0.18) : Color.white.opacity(0.06))- .clipShape(Capsule())- }- .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.chromeClick("new-tab") } label: {- Image(systemName: "plus").padding(6)- }- .buttonStyle(.plain)- }- .padding(.horizontal, 8)- .padding(.vertical, 4)- }- .foregroundColor(.white)- .background(Color(white: 0.12))- .frame(height: 36)- }-// MARK: the status line@ViewBuilderprivate var statusLine: some View {- let text = model.status?.toast?.text ?? ""+ let text = model.copied ? "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)@@ -354,7 +436,7 @@ struct KeyBar: View {.padding(.horizontal, 6)}.frame(height: 38)- .background(Color(white: 0.12))+ .background(model.background)}private func key(_ label: String, action: @escaping () -> Void) -> some View {@@ -383,3 +465,202 @@ struct KeyBar: View {.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 {+ case connecting(String)+ case attaching+ case reconnecting+ case failed(String)+ case disconnected++ init?(status: String) {+ if status.hasPrefix("pane ") { return nil }+ if status.hasPrefix("connecting") {+ self = .connecting(String(status.dropFirst("connecting to ".count)))+ } else if status.hasPrefix("connected") {+ self = .attaching+ } else if status.contains("reconnect") {+ self = .reconnecting+ } else if status.hasPrefix("failed: ") {+ self = .failed(String(status.dropFirst("failed: ".count)))+ } else if status.hasPrefix("attach failed: ") {+ self = .failed(String(status.dropFirst("attach failed: ".count)))+ } else if status.hasPrefix("disconnected: ") {+ self = .failed(String(status.dropFirst("disconnected: ".count)))+ } else if status.hasPrefix("disconnected") {+ self = .disconnected+ } else {+ // "idle", or nothing yet: the connection is about to start.+ self = .connecting("")+ }+ }+}++/// The card over the terminal while there is no terminal to show: the+/// steps of a connection, or what stopped it and what to do about it.+struct ConnectionCard: View {+ enum Action { case retry, forgetKeyAndRetry, edit, back }++ var phase: ConnectionPhase+ var hostName: String+ var canEdit: Bool+ var act: (Action) -> Void++ var body: some View {+ VStack(spacing: 14) {+ switch phase {+ case .connecting(let target):+ ProgressView().controlSize(.large)+ Text("Connecting to \(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)+ steps(done: 1)+ case .reconnecting:+ ProgressView().controlSize(.large)+ Text("Reconnecting to \(hostName)…").font(.headline)+ case .disconnected:+ Image(systemName: "bolt.slash").font(.system(size: 34)).foregroundColor(.secondary)+ Text("Disconnected").font(.headline)+ HStack {+ Button("Back") { act(.back) }.buttonStyle(.bordered)+ Button("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(reason)+ .font(.caption.monospaced())+ .foregroundColor(.secondary)+ .multilineTextAlignment(.center)+ .lineLimit(6)+ if let hint = Self.hint(for: reason) {+ Text(hint).font(.footnote).multilineTextAlignment(.center)+ }+ HStack {+ Button("Back") { act(.back) }.buttonStyle(.bordered)+ if canEdit {+ Button("Edit host") { act(.edit) }.buttonStyle(.bordered)+ }+ if reason.contains("key changed") && canEdit {+ Button("Forget key & retry") { act(.forgetKeyAndRetry) }.buttonStyle(.borderedProminent)+ } else {+ Button("Retry") { act(.retry) }.buttonStyle(.borderedProminent)+ }+ }+ }+ }+ .padding(20)+ .frame(maxWidth: 340)+ .background(.regularMaterial)+ .clipShape(RoundedRectangle(cornerRadius: 16))+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .background(Color.black.opacity(0.4))+ }++ 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))+ }+ .font(.footnote)+ .padding(.top, 4)+ }++ private func step(_ label: String, state: Int) -> some View {+ HStack(spacing: 8) {+ Image(systemName: state == 2 ? "checkmark.circle.fill" : (state == 1 ? "circle.dotted" : "circle"))+ .foregroundColor(state == 2 ? .green : .secondary)+ Text(label).foregroundColor(state == 0 ? .secondary : .primary)+ }+ }++ /// What the reason usually means, in plain words.+ 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."+ }+ 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."+ }+ 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."+ }+ 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."+ }+ if r.contains("codec") || r.contains("version") {+ return "The host runs another version of ThinkTerm. Update one of the two."+ }+ return nil+ }+}diff --git a/ios/Sources/ThinkTermApp.swift b/ios/Sources/ThinkTermApp.swiftindex b4a77f7d..d9799882 100644--- a/ios/Sources/ThinkTermApp.swift+++ b/ios/Sources/ThinkTermApp.swift@@ -3,19 +3,60 @@ import SwiftUI@mainstruct ThinkTermApp: App {@StateObject private var store = HostStore()+ @State private var path = NavigationPath()var body: some Scene {WindowGroup {- NavigationStack {+ Group {if ProcessInfo.processInfo.arguments.contains(where: { $0.hasPrefix("--auto") || $0.hasSuffix("test") }) {// The automated flows go straight to the probe's host.- TerminalScreen(host: nil, store: store)+ NavigationStack { TerminalScreen(host: nil, store: store) }} else {- HostsView()+ 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") }+ }}}.environmentObject(store).preferredColorScheme(.dark)}}++ /// `--seed-probe-host`: save the probe as an ordinary host whose key+ /// text sits in the Keychain, and open it. Debug builds only.+ static func seededHost(into store: HostStore) -> Host? {+ #if DEBUG+ guard ProcessInfo.processInfo.arguments.contains("--seed-probe-host"),+ let pem = try? String(contentsOfFile: "/tmp/ttp-ssh/userkey", encoding: .utf8) else { return nil }+ var host = store.hosts.first(where: { $0.name == "Probe (key)" }) ?? Host()+ host.name = "Probe (key)"+ host.hostname = "127.0.0.1"+ host.port = 2299+ host.user = probeUserName()+ host.auth = .key+ host.group = "Local"+ host.remoteCommand = "/tmp/ttp-ssh/thinkterm-remote cli --prefer-mux proxy"+ host.publicKey = SSHKey.publicLine(ofPrivate: pem, comment: host.user)+ Keychain.save(pem, account: host.id.uuidString)+ store.upsert(host)+ return host+ #else+ return nil+ #endif+ }}diff --git a/ios/Sources/Views.swift b/ios/Sources/Views.swiftindex 5e49570f..f9447fe8 100644--- a/ios/Sources/Views.swift+++ b/ios/Sources/Views.swift@@ -9,7 +9,7 @@ struct PaneView: Decodable, Hashable {var current: Bool}-struct TabView: Decodable, Hashable, Identifiable {+struct TabEntry: Decodable, Hashable, Identifiable {var tab: Intvar window: Intvar title: String@@ -28,7 +28,7 @@ struct Controls: Decodable, Hashable {}struct TabsView: Decodable, Hashable {- var tabs: [TabView]+ var tabs: [TabEntry]var controls: Controls}diff --git a/ios/build.sh b/ios/build.shindex f085cb36..e660e99c 100755--- a/ios/build.sh+++ b/ios/build.sh@@ -4,18 +4,44 @@# ios/build.sh build the Rust library, bindings, project and app# ios/build.sh run ...and boot a simulator, install, launch# ios/build.sh shot FILE ...and save a screenshot to FILE after launch+# ios/build.sh xcode build the Rust library for a real iPhone as well,+# generate the project, and open it in Xcode: pick+# your phone and your team there and press Run.#-# Device builds (aarch64-apple-ios) need a signing team; not wired here yet.+# A signing team for the phone goes in ios/Local.xcconfig (not tracked):+# DEVELOPMENT_TEAM = ABCDE12345+# or is chosen in Xcode's Signing & Capabilities; the project is generated+# again by every build, so the file is the setting that lasts.set -eucd "$(dirname "$0")/.."ROOT=$PWDSIM_TARGET=aarch64-apple-ios-sim+DEVICE_TARGET=aarch64-apple-iosSIM_NAME=${SIM_NAME:-iPhone 17}DERIVED=${DERIVED:-$ROOT/target/xcode}BUNDLE=com.roversx.thinkterm.ios-echo "== rust ($SIM_TARGET, release)"-cargo build -p thinkterm-mobile --release --target $SIM_TARGET+# Only the static library: the crate's cdylib is for Android, and its+# link fails on the iPhone target. The deployment target keeps rustc and+# ring's C objects on the same iOS version.+export IPHONEOS_DEPLOYMENT_TARGET=17.0+# cargo rustc with a crate type does not always leave the library at+# target/<triple>/release/ (the path the project links); the copy in+# deps/ is put there when it is missing.+rust_lib() {+ echo "== rust ($1, release)"+ cargo rustc -p thinkterm-mobile --lib --release --target "$1" --crate-type staticlib+ out=target/$1/release/libthinkterm_mobile.a+ if [ ! -f "$out" ]; then+ newest=$(ls -t target/$1/release/deps/libthinkterm_mobile-*.a | head -1)+ cp "$newest" "$out"+ fi+ test -f "$out" || { echo "no static library at $out" >&2; exit 1; }+}+rust_lib $SIM_TARGET+if [ "${1:-}" = xcode ]; then+ rust_lib $DEVICE_TARGET+fiecho "== bindings"rm -rf ios/Generated && mkdir -p ios/Generated@@ -28,9 +54,16 @@ mv ios/Generated/thinkterm_mobileFFI.modulemap ios/Generated/module.modulemapecho "== fonts"mkdir -p ios/Resourcescp assets/fonts/JetBrainsMono-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/echo "== project"+touch ios/Local.xcconfig(cd ios && xcodegen generate --quiet)+if [ "${1:-}" = xcode ]; then+ open ios/ThinkTerm.xcodeproj+ exit 0+fiecho "== xcodebuild"xcodebuild -project ios/ThinkTerm.xcodeproj -scheme ThinkTerm \diff --git a/ios/project.yml b/ios/project.ymlindex 6c112427..7f76d20e 100644--- a/ios/project.yml+++ b/ios/project.yml@@ -8,6 +8,10 @@ options:deploymentTarget:iOS: "17.0"createIntermediateGroups: true+configFiles:+ # The developer's own signing team, untracked; see ios/build.sh.+ Debug: Local.xcconfig+ Release: Local.xcconfigtargets:ThinkTerm:type: application@@ -24,6 +28,15 @@ targets:buildPhase: resourcesexcludes:- ".gitignore"+ # The app icon, twice over: ThinkTerm.icon is the Icon Composer bundle+ # 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+ type: file+ buildPhase: resources+ - path: Assets.xcassets+ buildPhase: resourcesdependencies:- sdk: Metal.framework- sdk: QuartzCore.framework@@ -33,6 +46,7 @@ targets:INFOPLIST_KEY_UILaunchScreen_Generation: YESINFOPLIST_KEY_CFBundleDisplayName: ThinkTermPRODUCT_BUNDLE_IDENTIFIER: com.roversx.thinkterm.ios+ ASSETCATALOG_COMPILER_APPICON_NAME: ThinkTermINFOPLIST_KEY_UISupportedInterfaceOrientations: UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRightSWIFT_VERSION: "5.9"SWIFT_INCLUDE_PATHS: $(SRCROOT)/Generated@@ -42,7 +56,9 @@ targets:"OTHER_LDFLAGS[sdk=iphoneos*]": $(SRCROOT)/../target/aarch64-apple-ios/release/libthinkterm_mobile.aENABLE_USER_SCRIPT_SANDBOXING: NOCODE_SIGN_STYLE: Automatic- DEVELOPMENT_TEAM: ""configs:Debug:- "CODE_SIGNING_ALLOWED[sdk=iphonesimulator*]": NO+ # Signed to run locally, not left unsigned: an unsigned simulator+ # build has no keychain entitlement, and every Keychain call+ # fails with -34018, so no host's key or password would be kept.+ "CODE_SIGN_IDENTITY[sdk=iphonesimulator*]": "-"