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: the app's interface over the shared App
RoversX3993855ba50a
diff --git a/Cargo.lock b/Cargo.lockindex af931a95..2aacf7e4 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -7795,6 +7795,8 @@ dependencies = ["futures","log","russh",+ "serde",+ "serde_json","termwiz 0.24.0","thinkterm-font-core","thinkterm-font-web",diff --git a/ios/.gitignore b/ios/.gitignoreindex d3abbfdf..1fc589e7 100644--- a/ios/.gitignore+++ b/ios/.gitignore@@ -1,3 +1,3 @@# Regenerated by ios/build.shGenerated/-ThinkTermProbe.xcodeproj/+ThinkTerm.xcodeproj/diff --git a/ios/Sources/HostsView.swift b/ios/Sources/HostsView.swiftnew file mode 100644index 00000000..f53702b7--- /dev/null+++ b/ios/Sources/HostsView.swift@@ -0,0 +1,133 @@+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.+struct HostsView: View {+ @EnvironmentObject var store: HostStore+ @State private var editing: Host?+ @State private var adding = false++ var 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) }+ }+ }+ } 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.")+ }+ }+ Section("Development") {+ NavigationLink("This Mac (probe sshd on :2299)", value: Host(name: "probe", hostname: "127.0.0.1", port: 2299, user: NSUserName()))+ }+ }+ .navigationTitle("ThinkTerm")+ .navigationDestination(for: Host.self) { host in+ if host.name == "probe" {+ TerminalScreen(host: nil, store: store)+ } else {+ TerminalScreen(host: host, store: store)+ }+ }+ .toolbar {+ ToolbarItem(placement: .topBarTrailing) {+ Button { adding = true } label: { Image(systemName: "plus") }+ }+ }+ .sheet(isPresented: $adding) {+ HostEditView(host: Host()) { host, secret, passphrase in+ Keychain.save(secret, account: host.id.uuidString)+ if let passphrase { Keychain.save(passphrase, account: host.id.uuidString + ".passphrase") }+ store.upsert(host)+ }+ }+ .sheet(item: $editing) { host in+ HostEditView(host: host) { host, secret, passphrase in+ if !secret.isEmpty { Keychain.save(secret, account: host.id.uuidString) }+ if let passphrase { Keychain.save(passphrase, account: host.id.uuidString + ".passphrase") }+ store.upsert(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++ var 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)+ }+ }+ }+ .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)+ }+ }+ }+ }+}diff --git a/ios/Sources/MetalView.swift b/ios/Sources/MetalView.swiftindex b2456192..aac06bd0 100644--- a/ios/Sources/MetalView.swift+++ b/ios/Sources/MetalView.swift@@ -7,7 +7,7 @@ import QuartzCore/// and takes the surface back before the layer is torn down.final class MetalLayerView: UIView {override class var layerClass: AnyClass { CAMetalLayer.self }- weak var model: ProbeModel?+ weak var model: TerminalModel?var metalLayer: CAMetalLayer { layer as! CAMetalLayer }@@ -40,7 +40,7 @@ final class MetalLayerView: UIView {}struct MetalView: UIViewRepresentable {- @EnvironmentObject var model: ProbeModel+ @EnvironmentObject var model: TerminalModelfunc makeUIView(context: Context) -> MetalLayerView {let view = MetalLayerView()diff --git a/ios/Sources/Models.swift b/ios/Sources/Models.swiftnew file mode 100644index 00000000..d03d5d33--- /dev/null+++ b/ios/Sources/Models.swift@@ -0,0 +1,126 @@+import Foundation+import Security++/// A host the app connects to. The secret (key text or password) is not+/// here: it lives in the Keychain under the host's id.+struct Host: Codable, Identifiable, Hashable {+ enum AuthKind: String, Codable, CaseIterable, Identifiable {+ case key+ case password+ var id: String { rawValue }+ var label: String { self == .key ? "Private key" : "Password" }+ }++ var id: UUID = UUID()+ var name: String = ""+ var hostname: String = ""+ var port: Int = 22+ var user: String = ""+ var auth: AuthKind = .key+ /// The host key fingerprint seen on the first connection.+ var knownHost: String?+ /// Set when the remote runs the probe's wrapper rather than an+ /// installed `thinkterm`; empty means the default proxy command.+ var remoteCommand: String = ""++ var display: String {+ name.isEmpty ? "\(user)@\(hostname):\(port)" : name+ }+}++/// The hosts, in the app's defaults. Small, and edited rarely.+final class HostStore: ObservableObject {+ @Published private(set) var hosts: [Host] = []+ private let key = "hosts.v1"++ init() {+ if let data = UserDefaults.standard.data(forKey: key),+ let hosts = try? JSONDecoder().decode([Host].self, from: data) {+ self.hosts = hosts+ }+ }++ func upsert(_ host: Host) {+ if let i = hosts.firstIndex(where: { $0.id == host.id }) {+ hosts[i] = host+ } else {+ hosts.append(host)+ }+ save()+ }++ func remove(_ host: Host) {+ hosts.removeAll { $0.id == host.id }+ Keychain.delete(account: host.id.uuidString)+ Keychain.delete(account: host.id.uuidString + ".passphrase")+ save()+ }++ func rememberHostKey(_ fingerprint: String, for id: UUID) {+ guard let i = hosts.firstIndex(where: { $0.id == id }) else { return }+ if hosts[i].knownHost != fingerprint {+ hosts[i].knownHost = fingerprint+ save()+ }+ }++ func forgetHostKey(for id: UUID) {+ guard let i = hosts.firstIndex(where: { $0.id == id }) else { return }+ hosts[i].knownHost = nil+ save()+ }++ private func save() {+ if let data = try? JSONEncoder().encode(hosts) {+ UserDefaults.standard.set(data, forKey: key)+ }+ }+}++/// The secrets, in the Keychain: one generic-password item per host id,+/// readable only while the device is unlocked.+enum Keychain {+ private static let service = "com.roversx.thinkterm.ssh"++ static func save(_ secret: String, account: String) {+ let data = Data(secret.utf8)+ let query: [String: Any] = [+ kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: service,+ kSecAttrAccount as String: account,+ ]+ let attrs: [String: Any] = [+ kSecValueData as String: data,+ kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly,+ ]+ let status = SecItemUpdate(query as CFDictionary, attrs as CFDictionary)+ if status == errSecItemNotFound {+ var add = query+ add.merge(attrs) { $1 }+ SecItemAdd(add as CFDictionary, nil)+ }+ }++ static func load(account: String) -> String? {+ let query: [String: Any] = [+ kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: service,+ kSecAttrAccount as String: account,+ kSecReturnData as String: true,+ kSecMatchLimit as String: kSecMatchLimitOne,+ ]+ var out: AnyObject?+ guard SecItemCopyMatching(query as CFDictionary, &out) == errSecSuccess,+ let data = out as? Data else { return nil }+ return String(data: data, encoding: .utf8)+ }++ static func delete(account: String) {+ let query: [String: Any] = [+ kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: service,+ kSecAttrAccount as String: account,+ ]+ SecItemDelete(query as CFDictionary)+ }+}diff --git a/ios/Sources/ProbeApp.swift b/ios/Sources/ProbeApp.swiftdeleted file mode 100644index 69efe226..00000000--- a/ios/Sources/ProbeApp.swift+++ /dev/null@@ -1,131 +0,0 @@-import SwiftUI--@main-struct ProbeApp: App {- @StateObject private var model = ProbeModel()- @Environment(\.scenePhase) private var scenePhase-- var body: some Scene {- WindowGroup {- ContentView()- .environmentObject(model)- }- // The lifecycle the plan cares about: the surface is handed back- // before the app is suspended and re-attached when it returns.- // (iOS keeps the layer alive across a background stay, but Android- // does not, and the core must be exercised the same way on both.)- .onChange(of: scenePhase) { _, phase in- switch phase {- case .background: model.detachForBackground()- case .active: model.reattachAfterBackground()- default: break- }- }- }-}--struct ContentView: View {- @EnvironmentObject var model: ProbeModel-- var body: some View {- VStack(spacing: 0) {- connection- ZStack(alignment: .topLeading) {- MetalView()- TerminalInput()- if let composing = model.composing {- Text(composing)- .font(.system(size: 14, design: .monospaced))- .padding(4)- .background(Color.yellow.opacity(0.9))- .foregroundColor(.black)- .padding(8)- }- }- .frame(maxWidth: .infinity, maxHeight: .infinity)- .padding(model.inset)- .background(Color.black)- keyBar- controls- ScrollView {- Text(model.logText)- .font(.system(size: 10, design: .monospaced))- .frame(maxWidth: .infinity, alignment: .leading)- .padding(6)- }- .frame(height: 120)- .background(Color(white: 0.1))- }- .background(Color.black)- .ignoresSafeArea(.container, edges: .bottom)- }-- private var connection: some View {- VStack(alignment: .leading, spacing: 4) {- HStack(spacing: 6) {- TextField("host", text: $model.host).frame(width: 110)- TextField("port", text: $model.port).frame(width: 50)- TextField("user", text: $model.user).frame(width: 80)- Button("Connect") { model.connect() }- Button("Drop") { model.disconnect() }- }- .textFieldStyle(.roundedBorder)- .font(.caption)- .autocorrectionDisabled()- .textInputAutocapitalization(.never)- Text(model.status)- .font(.system(size: 10, design: .monospaced))- .lineLimit(1)- }- .padding(6)- .background(Color(white: 0.15))- .foregroundColor(.white)- }-- private var keyBar: some View {- ScrollView(.horizontal, showsIndicators: false) {- HStack(spacing: 6) {- Button("Esc") { model.key("Escape") }- Button("Tab") { model.key("Tab") }- Button("^C") { model.key("c", ctrl: true) }- Button("^D") { model.key("d", ctrl: true) }- Button("^L") { model.key("l", ctrl: true) }- Button("↑") { model.key("ArrowUp") }- Button("↓") { model.key("ArrowDown") }- Button("←") { model.key("ArrowLeft") }- Button("→") { model.key("ArrowRight") }- Button("⌫") { model.key("Backspace") }- Button("Scroll↑") { model.scroll(5) }- Button("Scroll↓") { model.scroll(-5) }- Button("⌨︎") { model.focusKeyboard() }- Button("⌨︎✕") { model.dismissKeyboard() }- }- .buttonStyle(.bordered)- .font(.caption)- .padding(.horizontal, 6)- }- .frame(height: 36)- .background(Color(white: 0.12))- }-- private var controls: some View {- VStack(alignment: .leading, spacing: 4) {- HStack {- Button(model.attached ? "Detach" : "Attach") { model.toggleAttached() }- Button(model.animating ? "Stop" : "Animate") { model.toggleAnimating() }- Button("Frame") { model.requestOneFrame() }- Button(model.inset > 0 ? "Grow" : "Shrink") { model.toggleInset() }- Button("Cycle x20") { model.cycleAttachDetach(times: 20) }- }- .buttonStyle(.bordered)- .font(.caption)- Text(model.stats)- .font(.system(size: 9, design: .monospaced))- .lineLimit(3)- .frame(maxWidth: .infinity, alignment: .leading)- }- .padding(6)- .background(Color(white: 0.15))- .foregroundColor(.white)- }-}diff --git a/ios/Sources/SidebarSheet.swift b/ios/Sources/SidebarSheet.swiftnew file mode 100644index 00000000..ba2e387b--- /dev/null+++ b/ios/Sources/SidebarSheet.swift@@ -0,0 +1,177 @@+import SwiftUI++/// The desktop's sidebar as a sheet: the Space on show, its projects and+/// their threads, the other windows. Rows come from the App; a tap is+/// the App's own click.+struct SidebarSheet: View {+ @ObservedObject var model: TerminalModel+ @Binding var isPresented: Bool+ @State private var renaming: (kind: String, id: String)?+ @State private var renameText = ""+ @State private var newProjectPath = ""+ @State private var spaceMenu: [MenuItem] = []++ var body: some View {+ NavigationStack {+ List {+ ForEach(model.sidebar?.rows ?? []) { row in+ rowView(row)+ }+ if let error = model.sidebar?.new_project_error {+ Text(error).font(.caption).foregroundColor(.red)+ }+ }+ .listStyle(.plain)+ .navigationTitle("Threads")+ .navigationBarTitleDisplayMode(.inline)+ .toolbar {+ ToolbarItem(placement: .cancellationAction) {+ Button("Done") { isPresented = false }+ }+ ToolbarItemGroup(placement: .topBarTrailing) {+ Menu {+ ForEach(spaceMenu, id: \.rowId) { item in+ if item.kind == "item" {+ Button {+ model.menuAction(item.id)+ reloadSpaces()+ } label: {+ Label(item.label, systemImage: item.checked ? "checkmark" : "")+ }+ }+ }+ } label: { Image(systemName: "square.stack.3d.up") }+ Button { model.sideClick("new-project") } label: { Image(systemName: "folder.badge.plus") }+ }+ }+ .alert("Rename", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {+ TextField("Name", text: $renameText)+ Button("Save") {+ model.sideKey("Enter", value: renameText)+ renaming = nil+ }+ Button("Cancel", role: .cancel) {+ model.sideKey("Escape", value: "")+ renaming = nil+ }+ }+ }+ .onAppear {+ model.refreshViews()+ reloadSpaces()+ }+ .onChange(of: model.sidebar?.editing) { _, editing in+ // The App opened a field (a rename, a new project): show it.+ guard let editing else { return }+ switch editing.kind {+ case "thread", "project", "space":+ if renaming == nil {+ renameText = ""+ renaming = (editing.kind, editing.id ?? "")+ }+ case "new-project":+ if renaming == nil {+ renameText = ""+ renaming = ("new-project", "")+ }+ default:+ break+ }+ }+ }++ private func reloadSpaces() {+ spaceMenu = model.contextMenu("space", id: "")+ }++ @ViewBuilder+ private func rowView(_ row: SideRow) -> some View {+ switch row {+ case .space(_, let name):+ Text(name).font(.headline).listRowBackground(Color.clear)+ case .newThread:+ Button {+ model.sideClick("new-thread")+ isPresented = false+ } label: {+ Label("New thread", systemImage: "plus")+ }+ case .pinned:+ Text("Pinned").font(.caption).foregroundColor(.secondary)+ case .workspaces:+ Text("Workspaces").font(.caption).foregroundColor(.secondary)+ case .project(let id, let name, let path, let collapsed, _):+ Button {+ model.sideClick("toggle-project", id: id)+ } label: {+ HStack {+ Image(systemName: collapsed ? "chevron.right" : "chevron.down").font(.caption)+ VStack(alignment: .leading) {+ Text(name).font(.subheadline.weight(.semibold))+ Text(path).font(.caption2).foregroundColor(.secondary).lineLimit(1)+ }+ Spacer()+ Button { model.sideClick("new-thread", id: id) } label: { Image(systemName: "plus") }+ .buttonStyle(.borderless)+ }+ }+ .contextMenu {+ Button("Rename") { model.sideClick("rename-project", id: id) }+ Button("Archive") { model.sideClick("archive", id: id) }+ }+ case .thread(let t):+ Button {+ model.sideClick("thread", id: t.id)+ isPresented = false+ } label: {+ HStack(spacing: 8) {+ Circle().fill(dotColor(t)).frame(width: 8, height: 8)+ Text(t.name).fontWeight(t.unread ? .semibold : .regular)+ Spacer()+ if t.pinned { Image(systemName: "pin.fill").font(.caption2).foregroundColor(.secondary) }+ if !t.live { Text("off").font(.caption2).foregroundColor(.secondary) }+ }+ .padding(.leading, 12)+ }+ .listRowBackground(t.selected ? Color.accentColor.opacity(0.2) : nil)+ .swipeActions(edge: .trailing) {+ Button(role: .destructive) { model.sideClick("delete", id: t.id) } label: { Label("Delete", systemImage: "trash") }+ Button { model.sideClick("pin", id: t.id, flag: !t.pinned) } label: { Label(t.pinned ? "Unpin" : "Pin", systemImage: "pin") }+ }+ .contextMenu {+ Button("Rename") { model.sideClick("rename-thread", id: t.id) }+ Button(t.pinned ? "Unpin" : "Pin") { model.sideClick("pin", id: t.id, flag: !t.pinned) }+ Button("Delete", role: .destructive) { model.sideClick("delete", id: t.id) }+ }+ case .archived(let count, let open, let label):+ Button { model.sideClick("toggle-archived") } label: {+ HStack {+ Image(systemName: open ? "chevron.down" : "chevron.right").font(.caption)+ Text("\(label) (\(count))").font(.caption)+ }+ }+ case .others:+ Text("Other windows").font(.caption).foregroundColor(.secondary)+ case .window(let id, let title, let selected):+ Button {+ model.sideClick("window", id: String(id))+ isPresented = false+ } label: {+ HStack {+ Image(systemName: "macwindow")+ Text(title.isEmpty ? "Window \(id)" : title)+ }+ }+ .listRowBackground(selected ? Color.accentColor.opacity(0.2) : nil)+ }+ }++ private func dotColor(_ t: ThreadRow) -> Color {+ switch t.status {+ case "Running": return .green+ case "NeedsAttention": return .orange+ case "Done": return .blue+ default: return t.live ? .gray : .gray.opacity(0.4)+ }+ }+}diff --git a/ios/Sources/TerminalInputView.swift b/ios/Sources/TerminalInputView.swiftindex 044b49b0..d7a46902 100644--- a/ios/Sources/TerminalInputView.swift+++ b/ios/Sources/TerminalInputView.swift@@ -1,42 +1,108 @@import SwiftUIimport UIKit-/// The keyboard's target: an invisible view over the terminal that adopts-/// `UITextInput` so the soft keyboard, its IMEs (Pinyin, Kana...) and a-/// hardware keyboard all talk to it. 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 events, and while a composition is open the-/// core is told to leave the keyboard to the IME.+/// The keyboard's target and the terminal's touch surface: an invisible+/// view over the Metal layer that adopts `UITextInput` so the soft+/// 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, a drag scrolls, a long press opens the pane's menu, a pinch+/// changes the font.///-/// The rules this enforces (plan §2.6):-/// - nothing is sent while composing; the marked text is the IME's;-/// - cancelling a composition sends nothing;-/// - picking a candidate commits once (insertText clears the marked text-/// before unmarkText can commit it again);-/// - backspace inside a composition edits the marked text only.-final class TerminalInputView: UIView, UITextInput {- weak var model: ProbeModel?-- /// The IME's composing text, `nil` when none is open.+/// 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+/// events, and while a composition is open the core is told to leave the+/// keyboard to the IME. The rules (plan §2.6): nothing is sent while+/// composing; cancelling sends nothing; a candidate commits once+/// (insertText clears the marked text before unmarkText can commit it+/// again); backspace inside a composition edits the marked text only.+final class TerminalInputView: UIView, UITextInput, UIGestureRecognizerDelegate {+ weak var model: TerminalModel?+ var onMenu: ((CGPoint) -> Void)?+private(set) var marked: String?- /// Selection inside the marked text, for the IME's own bookkeeping.private var markedSelection = NSRange(location: 0, length: 0)+ private var panRemainder: CGFloat = 0+ private var pinchStart: CGFloat = 1override init(frame: CGRect) {super.init(frame: frame)isUserInteractionEnabled = truebackgroundColor = .clear- addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapped)))+ let tap = UITapGestureRecognizer(target: self, action: #selector(tapped(_:)))+ let pan = UIPanGestureRecognizer(target: self, action: #selector(panned(_:)))+ let press = UILongPressGestureRecognizer(target: self, action: #selector(pressed(_:)))+ let pinch = UIPinchGestureRecognizer(target: self, action: #selector(pinched(_:)))+ pan.maximumNumberOfTouches = 1+ press.minimumPressDuration = 0.45+ for g in [tap, pan, press, pinch] as [UIGestureRecognizer] {+ g.delegate = self+ addGestureRecognizer(g)+ }}required init?(coder: NSCoder) { fatalError() }- @objc private func tapped() {+ // MARK: gestures++ @objc private func tapped(_ g: UITapGestureRecognizer) {+ let p = g.location(in: self)+ // A press and release at the point: the App focuses the pane.+ model?.pointer("down", at: p)+ model?.pointer("up", at: p)if !isFirstResponder {becomeFirstResponder()}}+ @objc private func panned(_ g: UIPanGestureRecognizer) {+ let p = g.location(in: self)+ switch g.state {+ case .began:+ panRemainder = 0+ case .changed:+ // Points to rows: the App's own cell height is unknown here;+ // a row is taken as 20 pt, which is what 11 pt Menlo is.+ let dy = g.translation(in: self).y + panRemainder+ let rows = (dy / 20).rounded(.towardZero)+ panRemainder = dy - rows * 20+ g.setTranslation(.zero, in: self)+ if rows != 0 {+ model?.wheel(at: p, lines: Double(rows))+ }+ default:+ break+ }+ }++ @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+ case .changed:+ // One font step per 15% of scale, either way.+ while g.scale > pinchStart * 1.15 {+ pinchStart *= 1.15+ model?.stepFont(1)+ }+ while g.scale < pinchStart / 1.15 {+ pinchStart /= 1.15+ model?.stepFont(-1)+ }+ default: break+ }+ }++ func gestureRecognizer(_ a: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith b: UIGestureRecognizer) -> Bool {+ true+ }+override var canBecomeFirstResponder: Bool { true }// MARK: composition bookkeeping@@ -56,8 +122,8 @@ final class TerminalInputView: UIView, UITextInput {model?.compositionChanged(nil)}- /// Called by the shell when the pane goes away or the connection- /// changes: an open composition must not land in whatever comes next.+ /// The pane went away or the connection changed: an open composition+ /// must not land in whatever comes next.func dropComposition() {endComposing()}@@ -67,19 +133,15 @@ final class TerminalInputView: UIView, UITextInput {var hasText: Bool { marked?.isEmpty == false }func insertText(_ text: String) {- // A candidate was chosen (or plain text typed with no IME): the- // marked text is replaced by this, and this alone is sent.endComposing()if text == "\n" {model?.key("Enter")} else {- model?.core.text(text: text)+ model?.text(text)}}func deleteBackward() {- // Inside a composition the IME edits its own buffer through- // setMarkedText; this only fires for a real backspace.if marked != nil { return }model?.key("Backspace")}@@ -99,7 +161,6 @@ final class TerminalInputView: UIView, UITextInput {func setMarkedText(_ markedText: String?, selectedRange: NSRange) {let text = markedText ?? ""if text.isEmpty {- // The IME cleared its buffer without committing: a cancel.endComposing()return}@@ -110,13 +171,11 @@ final class TerminalInputView: UIView, UITextInput {}func unmarkText() {- // The composition ended with text still marked (the IME committed- // the raw buffer, or the keyboard went away): commit it once.if let marked, !marked.isEmpty {self.marked = nilmodel?.core.setComposing(on: false)model?.compositionChanged(nil)- model?.core.text(text: marked)+ model?.text(marked)return}endComposing()@@ -124,10 +183,6 @@ final class TerminalInputView: UIView, UITextInput {// MARK: UITextInput -- the (empty) document- // The view's "text" is only ever the marked string; everything else- // has been handed to the terminal. Positions are UTF-16 offsets into- // the marked text, and the document is otherwise empty.-var selectedTextRange: UITextRange? {get {let n = marked?.utf16.count ?? 0@@ -149,8 +204,6 @@ final class TerminalInputView: UIView, UITextInput {}func replace(_ range: UITextRange, withText text: String) {- // Replacing inside the marked text is the IME's business and comes- // through setMarkedText; anything else is a commit.insertText(text)}@@ -210,9 +263,6 @@ final class TerminalInputView: UIView, UITextInput {func setBaseWritingDirection(_ writingDirection: NSWritingDirection, for range: UITextRange) {}- // The candidate bar and the magnifier ask where the text is; the- // terminal's cursor rectangle is what they should get. The model keeps- // it from the last frame (in points, in this view's coordinates).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] { [] }@@ -236,12 +286,12 @@ final class TerminalInputView: UIView, UITextInput {override var keyCommands: [UIKeyCommand]? {var cmds: [UIKeyCommand] = []- let arrows: [(String, String)] = [- (UIKeyCommand.inputUpArrow, "ArrowUp"), (UIKeyCommand.inputDownArrow, "ArrowDown"),- (UIKeyCommand.inputLeftArrow, "ArrowLeft"), (UIKeyCommand.inputRightArrow, "ArrowRight"),- (UIKeyCommand.inputEscape, "Escape"), ("\t", "Tab"),+ let specials: [String] = [+ UIKeyCommand.inputUpArrow, UIKeyCommand.inputDownArrow,+ UIKeyCommand.inputLeftArrow, UIKeyCommand.inputRightArrow,+ UIKeyCommand.inputEscape, "\t",]- for (input, _) in arrows {+ for input in specials {let c = UIKeyCommand(input: input, modifierFlags: [], action: #selector(hardwareKey(_:)))c.wantsPriorityOverSystemBehavior = truecmds.append(c)@@ -286,14 +336,18 @@ final class TerminalInputView: UIView, UITextInput {}struct TerminalInput: UIViewRepresentable {- @EnvironmentObject var model: ProbeModel+ @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) {}+ func updateUIView(_ uiView: TerminalInputView, context: Context) {+ uiView.onMenu = onMenu+ }}diff --git a/ios/Sources/ProbeModel.swift b/ios/Sources/TerminalModel.swiftsimilarity index 62%rename from ios/Sources/ProbeModel.swiftrename to ios/Sources/TerminalModel.swiftindex bc8fe173..cc3f34eb 100644--- a/ios/Sources/ProbeModel.swift+++ b/ios/Sources/TerminalModel.swift@@ -9,43 +9,53 @@ import CoreGraphics/// core thread; nothing here blocks them, and nothing here calls back into/// the core from inside them. The display link is the only place `render`/// is called; the core only ever *asks* for a frame.-final class ProbeModel: ObservableObject, @unchecked Sendable {+///+/// One model per connection: the screen that shows a host makes one and+/// shuts it down when it goes.+final class TerminalModel: ObservableObject, @unchecked Sendable {+ // The App's views, refreshed when the core says something changed.+ @Published var tabs: TabsView?+ @Published var sidebar: SidebarView?+ @Published var navs: [NavView] = []+ @Published var status: StatusView?+ @Published var title = ""+ @Published var connection = ""@Published var attached = false- @Published var animating = false- @Published var inset: CGFloat = 0- @Published var stats = ""- @Published var status = ""- @Published var logText = ""- @Published var host = "127.0.0.1"- @Published var port = "2299"- @Published var user = NSUserName()- @Published var input = ""- /// The IME's composing text, shown above the terminal while open.@Published var composing: String?+ @Published var ctrlSticky = false+ @Published var altSticky = false+ @Published var logText = ""+ @Published var stats = ""+ @Published var inset: CGFloat = 0+ @Published var animating = false++ let core: Core+ let host: Host?+ weak var store: HostStore?weak var inputView: TerminalInputView?- /// Where the candidate bar should hang, in the input view's points.- /// Fixed until the core reports the cursor's rectangle (S1).var cursorRect = CGRect(x: 8, y: 8, width: 2, height: 20)- let core: Coreprivate let frameNeeded = AtomicFlag()+ private let changePending = AtomicFlag()private var displayLink: CADisplayLink?private var statsTimer: Timer?private var logLines: [String] = []+ private var hostKeyToRemember: String?- /// The layer currently attached, and the generation the core gave it.weak var layer: CAMetalLayer?private(set) var generation: UInt64 = 0private var wantsSurface = falseprivate var lastSize: (Int, Int, Double) = (0, 0, 0)- // The probe's ssh setup: a throwaway key and a wrapper that points the- // remote proxy at an isolated HOME. Overridable from the launch- // arguments so a real host can be tried without a rebuild.- var keyPath = "/tmp/ttp-ssh/userkey"- var remoteCommand = "/tmp/ttp-ssh/thinkterm-remote cli --prefer-mux proxy"+ // The probe's ssh setup, for the automated flows: a throwaway key and+ // a wrapper that points the remote proxy at an isolated HOME.+ private var probeKeyPath = "/tmp/ttp-ssh/userkey"+ private var probeRemoteCommand = "/tmp/ttp-ssh/thinkterm-remote cli --prefer-mux proxy"+ private var probeUser = NSUserName()- init() {+ init(host: Host?, store: HostStore?) {+ self.host = host+ self.store = storelet sink = NotifySink()core = Core(notify: sink)sink.model = self@@ -55,11 +65,9 @@ final class ProbeModel: ObservableObject, @unchecked Sendable {guard let i = args.firstIndex(of: name), i + 1 < args.count else { return nil }return args[i + 1]}- if let h = arg("--host") { host = h }- if let p = arg("--port") { port = p }- if let u = arg("--user") { user = u }- if let k = arg("--key") { keyPath = k }- if let c = arg("--remote-command") { remoteCommand = c }+ if let u = arg("--user") { probeUser = u }+ if let k = arg("--key") { probeKeyPath = k }+ if let c = arg("--remote-command") { probeRemoteCommand = c }let link = CADisplayLink(target: self, selector: #selector(tick))link.add(to: .main, forMode: .common)@@ -68,27 +76,18 @@ final class ProbeModel: ObservableObject, @unchecked Sendable {guard let self else { return }self.stats = self.core.stats()}- if args.contains("--autotest") {- scheduleAutotest()- }- if args.contains("--autoconnect") {- scheduleAutoconnect()- }- if args.contains("--imetest") {- scheduleImeTest()- }- }-- func compositionChanged(_ text: String?) {- DispatchQueue.main.async { self.composing = text }- }-- func focusKeyboard() {- inputView?.becomeFirstResponder()+ if args.contains("--autotest") { scheduleAutotest() }+ if args.contains("--autoconnect") { scheduleAutoconnect() }+ if args.contains("--imetest") { scheduleImeTest() }+ if args.contains("--uitest") { scheduleUiTest() }}- func dismissKeyboard() {- inputView?.resignFirstResponder()+ func shutdown() {+ displayLink?.invalidate()+ statsTimer?.invalidate()+ detach()+ core.disconnect()+ core.shutdown()}// MARK: connection@@ -99,176 +98,126 @@ final class ProbeModel: ObservableObject, @unchecked Sendable {}}+ /// Connect to the model's host with the secret from the Keychain.func connect() {+ guard let host else {+ connectProbe()+ return+ }+ let account = host.id.uuidString+ let secret = Keychain.load(account: account) ?? ""+ let passphrase = Keychain.load(account: account + ".passphrase")+ connect(+ hostname: host.hostname, port: host.port, user: host.user,+ authKind: host.auth == .password ? "password" : "key", secret: secret,+ passphrase: passphrase, knownHost: host.knownHost, remoteCommand: host.remoteCommand+ )+ }++ /// The probe's connection: the private sshd on this Mac.+ func connectProbe() {+ connect(+ hostname: "127.0.0.1", port: 2299, user: probeUser, authKind: "key-path",+ secret: probeKeyPath, passphrase: nil, knownHost: nil, remoteCommand: probeRemoteCommand+ )+ }++ private func connect(hostname: String, port: Int, user: String, authKind: String, secret: String, passphrase: String?, knownHost: String?, remoteCommand: String) {let paths = fontPathsguard paths.count == 2 else {log("shell: fonts missing from the bundle (\(paths))")return}core.connect(- host: host,- port: UInt16(port) ?? 22,- user: user,- keyPath: keyPath,- remoteCommand: remoteCommand,- fontPaths: paths,- sizePt: 11.0,+ host: hostname, port: UInt16(clamping: port), user: user,+ authKind: authKind, secret: secret, passphrase: passphrase, knownHost: knownHost,+ remoteCommand: remoteCommand, fontPaths: paths, sizePt: 11.0,painter: CoreTextPainter())}func disconnect() { core.disconnect() }- func send() {- guard !input.isEmpty else { return }- core.text(text: input)- input = ""+ // MARK: input++ func key(_ name: String, ctrl: Bool = false, alt: Bool = false, shift: Bool = false) {+ core.key(name: name, ctrl: ctrl || takeSticky(\.ctrlSticky), alt: alt || takeSticky(\.altSticky), shift: shift)}- func sendLine() {- core.text(text: input)- core.key(name: "Enter", ctrl: false, alt: false, shift: false)- input = ""+ /// Text from the keyboard. A sticky Ctrl or Alt turns a single+ /// character into a chord.+ func text(_ text: String) {+ if (ctrlSticky || altSticky), text.count == 1 {+ key(text)+ return+ }+ core.text(text: text)}- func key(_ name: String, ctrl: Bool = false, alt: Bool = false, shift: Bool = false) {- core.key(name: name, ctrl: ctrl, alt: alt, shift: shift)+ func pasteFromClipboard() {+ if let text = UIPasteboard.general.string, !text.isEmpty {+ core.paste(text: text)+ }}- func scroll(_ lines: Int32) { core.scroll(lines: lines) }+ private func takeSticky(_ path: ReferenceWritableKeyPath<TerminalModel, Bool>) -> Bool {+ let on = self[keyPath: path]+ if on { self[keyPath: path] = false }+ return on+ }- // MARK: autotest (driven by launch arguments; results go to the console)+ func pointer(_ kind: String, at point: CGPoint) {+ core.pointer(kind: kind, x: point.x, y: point.y)+ }- private func report(_ step: String) {- let line = "AUTOTEST \(step): \(core.stats())"- print(line)- NSLog("%@", line)- log(line)+ func wheel(at point: CGPoint, lines: Double) {+ core.wheel(x: point.x, y: point.y, lines: lines)}- private func scheduleAutotest() {- let q = DispatchQueue.main- q.asyncAfter(deadline: .now() + 2.0) { self.report("start") }- q.asyncAfter(deadline: .now() + 2.1) { self.toggleAnimating() }- q.asyncAfter(deadline: .now() + 4.1) { self.toggleAnimating(); self.report("after 2s animating") }- q.asyncAfter(deadline: .now() + 4.5) { self.cycleAttachDetach(times: 20); self.report("after 20 cycles") }- q.asyncAfter(deadline: .now() + 5.0) { self.requestOneFrame() }- q.asyncAfter(deadline: .now() + 5.5) { self.toggleInset() }- q.asyncAfter(deadline: .now() + 6.5) { self.report("after shrink"); self.toggleInset() }- q.asyncAfter(deadline: .now() + 7.5) { self.report("after grow"); self.detach() }- q.asyncAfter(deadline: .now() + 8.0) { self.requestOneFrame(); self.report("detached, frame requested") }- q.asyncAfter(deadline: .now() + 8.5) { self.toggleAttached() }- q.asyncAfter(deadline: .now() + 9.5) { self.report("reattached"); print("AUTOTEST DONE") }+ func stepFont(_ by: Double) { core.stepFont(by: by) }++ // MARK: the App's chrome++ func chromeClick(_ action: String, pane: Int? = nil, tab: Int? = nil) {+ core.chromeClick(action: action, pane: pane.map { UInt32($0) }, tab: tab.map { UInt32($0) })}- /// Connect, wait for the pane, type a line with CJK and an emoji so the- /// painter path is exercised, then report. The screenshot is taken from- /// outside.- private func scheduleAutoconnect() {- let q = DispatchQueue.main- q.asyncAfter(deadline: .now() + 1.5) { self.connect(); self.report("connect sent") }- q.asyncAfter(deadline: .now() + 5.0) { self.report("after connect") }- q.asyncAfter(deadline: .now() + 5.2) {- self.input = "echo '你好, 世界 🙂 hello from iOS'"- self.sendLine()- }- q.asyncAfter(deadline: .now() + 7.5) { self.report("after typing") }- // Output that arrives while nothing is being drawn must wake a frame.- q.asyncAfter(deadline: .now() + 7.6) {- self.input = "sleep 2; echo WOKE-BY-OUTPUT"- self.sendLine()- }- q.asyncAfter(deadline: .now() + 8.6) { self.report("before wake") }- q.asyncAfter(deadline: .now() + 11.0) { self.report("after wake") }- // The surface goes and comes back while the session stays.- q.asyncAfter(deadline: .now() + 11.2) { self.cycleAttachDetach(times: 5); self.report("after 5 cycles connected") }- q.asyncAfter(deadline: .now() + 12.5) { self.report("final") }- // The harness kills the remote proxy at about 13 s; the core must- // dial again and come back with the same pane.- q.asyncAfter(deadline: .now() + 15.0) { self.report("during reconnect") }- q.asyncAfter(deadline: .now() + 19.0) {- self.input = "echo AFTER-RECONNECT"- self.sendLine()- }- q.asyncAfter(deadline: .now() + 21.0) { self.report("after reconnect"); print("AUTOCONNECT DONE") }+ func sideClick(_ kind: String, id: String? = nil, flag: Bool? = nil) {+ core.sideClick(kind: kind, id: id, flag: flag)}- /// Drives the UITextInput view the way an IME does, without one: the- /// simulator cannot be typed into from outside, so the view's contract- /// is exercised directly and the core's input counter is checked at- /// each step. A real Pinyin keyboard is the user's to try.- private func scheduleImeTest() {- let q = DispatchQueue.main- var sent: Int { Int(inputsSent()) }- var sizeBefore = ""- q.asyncAfter(deadline: .now() + 1.5) { self.connect() }- q.asyncAfter(deadline: .now() + 5.0) {- sizeBefore = self.sizeString()- self.focusKeyboard()- }- q.asyncAfter(deadline: .now() + 6.5) {- let after = self.sizeString()- self.check("keyboard resize", after != sizeBefore, "\(sizeBefore) -> \(after)")- }- q.asyncAfter(deadline: .now() + 7.0) {- guard let v = self.inputView else { self.check("input view", false, "missing"); return }- let base = sent- v.setMarkedText("n", selectedRange: NSRange(location: 1, length: 0))- v.setMarkedText("ni", selectedRange: NSRange(location: 2, length: 0))- v.setMarkedText("nih", selectedRange: NSRange(location: 3, length: 0))- q.asyncAfter(deadline: .now() + 0.3) {- self.check("composing sends nothing", sent == base, "sent \(sent - base), composing=\(self.composingFlag())")- // Candidate chosen: iOS calls insertText then unmarkText.- v.insertText("你")- v.unmarkText()- q.asyncAfter(deadline: .now() + 0.3) {- self.check("candidate commits once", sent == base + 1, "sent \(sent - base)")- let b2 = sent- v.setMarkedText("hao", selectedRange: NSRange(location: 3, length: 0))- v.setMarkedText("", selectedRange: NSRange(location: 0, length: 0))- q.asyncAfter(deadline: .now() + 0.3) {- self.check("cancel sends nothing", sent == b2, "sent \(sent - b2)")- v.setMarkedText("hao", selectedRange: NSRange(location: 3, length: 0))- v.deleteBackward()- v.setMarkedText("ha", selectedRange: NSRange(location: 2, length: 0))- q.asyncAfter(deadline: .now() + 0.3) {- self.check("backspace edits composition only", sent == b2 && v.marked == "ha", "sent \(sent - b2), marked=\(v.marked ?? "nil")")- v.unmarkText()- q.asyncAfter(deadline: .now() + 0.3) {- self.check("leftover composition commits once", sent == b2 + 1, "sent \(sent - b2)")- self.key("Enter")- q.asyncAfter(deadline: .now() + 1.5) {- self.report("ime done")- print("IMETEST DONE")- }- }- }- }- }- }- }+ func sideKey(_ key: String, value: String) {+ core.sideKey(key: key, value: value)}- private func check(_ name: String, _ ok: Bool, _ detail: String) {- let line = "IMECHECK \(ok ? "PASS" : "FAIL") \(name): \(detail)"- print(line)- log(line)+ func contextMenu(_ kind: String, id: String) -> [MenuItem] {+ ViewJSON.decode([MenuItem].self, core.contextMenu(kind: kind, id: id)) ?? []}- private func statsField(_ key: String) -> String {- let s = core.stats()- guard let r = s.range(of: "\"\(key)\":") else { return "" }- let rest = s[r.upperBound...]- return String(rest.prefix { $0 != "," && $0 != "}" }).replacingOccurrences(of: "\"", with: "")+ /// Run a menu row. Copy and paste are the shell's to do.+ func menuAction(_ id: String) {+ guard let outcome = ViewJSON.decode(MenuOutcome.self, core.menuAction(id: id)) else { return }+ if let text = outcome.copy {+ UIPasteboard.general.string = text+ }+ if outcome.paste {+ pasteFromClipboard()+ }}- private func inputsSent() -> Int64 { Int64(statsField("inputs_sent")) ?? -1 }- private func composingFlag() -> String { statsField("composing") }- private func sizeString() -> String { statsField("size") }+ func takeOver() { core.takeOver() }++ /// 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"))+ }// MARK: surface lifecycle, all on the main thread- /// Called by the view whenever its layer exists and has a size.func surfaceReady(_ layer: CAMetalLayer, width: Int, height: Int, scale: Double) {self.layer = layerwantsSurface = true@@ -280,7 +229,6 @@ final class ProbeModel: ObservableObject, @unchecked Sendable {}}- /// Called by the view before its layer goes away.func surfaceGone() {wantsSurface = falsedetach()@@ -297,7 +245,6 @@ final class ProbeModel: ObservableObject, @unchecked Sendable {private func detach() {guard generation != 0 else { return }- // The one synchronous call: returns once the core has let go.let started = CACurrentMediaTime()core.detachSurface(generation: generation)let ms = (CACurrentMediaTime() - started) * 1000@@ -350,6 +297,9 @@ final class ProbeModel: ObservableObject, @unchecked Sendable {if frameNeeded.take() {core.render()}+ if changePending.take() {+ refreshViews()+ }}func requestOneFrame() { frameNeeded.set() }@@ -359,25 +309,40 @@ final class ProbeModel: ObservableObject, @unchecked Sendable {core.setAnimating(on: animating)}- func toggleInset() {- inset = inset > 0 ? 0 : 60+ func toggleInset() { inset = inset > 0 ? 0 : 60 }++ func focusKeyboard() { inputView?.becomeFirstResponder() }+ func dismissKeyboard() { inputView?.resignFirstResponder() }+ func compositionChanged(_ text: String?) {+ DispatchQueue.main.async { self.composing = text }}// MARK: notify (core thread)- fileprivate func coreWantsFrame() {- frameNeeded.set()- }+ fileprivate func coreWantsFrame() { frameNeeded.set() }+ fileprivate func coreChanged() { changePending.set() }fileprivate func coreStatus(_ status: String) {DispatchQueue.main.async {- self.status = status+ self.connection = statusself.log("status: " + status)- // Whatever the IME was composing belongs to the pane that was- // there; a new attachment must not receive it.if status.hasPrefix("connecting") || status.contains("reconnect") || status.hasPrefix("disconnected") {self.inputView?.dropComposition()}+ self.changePending.set()+ }+ }++ fileprivate func coreTitle(_ title: String) {+ DispatchQueue.main.async { self.title = title }+ }++ fileprivate func coreHostKey(_ fingerprint: String) {+ DispatchQueue.main.async {+ self.log("host key " + fingerprint)+ if let host = self.host {+ self.store?.rememberHostKey(fingerprint, for: host.id)+ }}}@@ -388,20 +353,178 @@ final class ProbeModel: ObservableObject, @unchecked Sendable {private func log(_ line: String) {logLines.append(line)- if logLines.count > 40 { logLines.removeFirst(logLines.count - 40) }+ if logLines.count > 60 { logLines.removeFirst(logLines.count - 60) }logText = logLines.joined(separator: "\n")}++ // MARK: automated flows (launch arguments; results on the console)++ private func report(_ step: String) {+ let line = "AUTOTEST \(step): \(core.stats())"+ print(line)+ NSLog("%@", line)+ log(line)+ }++ private func scheduleAutotest() {+ let q = DispatchQueue.main+ q.asyncAfter(deadline: .now() + 2.0) { self.report("start") }+ q.asyncAfter(deadline: .now() + 2.1) { self.toggleAnimating() }+ q.asyncAfter(deadline: .now() + 4.1) { self.toggleAnimating(); self.report("after 2s animating") }+ q.asyncAfter(deadline: .now() + 4.5) { self.cycleAttachDetach(times: 20); self.report("after 20 cycles") }+ q.asyncAfter(deadline: .now() + 5.0) { self.requestOneFrame() }+ q.asyncAfter(deadline: .now() + 5.5) { self.toggleInset() }+ q.asyncAfter(deadline: .now() + 6.5) { self.report("after shrink"); self.toggleInset() }+ q.asyncAfter(deadline: .now() + 7.5) { self.report("after grow"); self.detach() }+ q.asyncAfter(deadline: .now() + 8.0) { self.requestOneFrame(); self.report("detached, frame requested") }+ q.asyncAfter(deadline: .now() + 8.5) { self.toggleAttached() }+ q.asyncAfter(deadline: .now() + 9.5) { self.report("reattached"); print("AUTOTEST DONE") }+ }++ private func scheduleAutoconnect() {+ let q = DispatchQueue.main+ q.asyncAfter(deadline: .now() + 1.5) { self.connectProbe(); self.report("connect sent") }+ q.asyncAfter(deadline: .now() + 5.0) { self.report("after connect") }+ q.asyncAfter(deadline: .now() + 5.2) {+ self.core.text(text: "echo '你好, 世界 🙂 hello from iOS'")+ self.key("Enter")+ }+ q.asyncAfter(deadline: .now() + 7.5) { self.report("after typing") }+ q.asyncAfter(deadline: .now() + 7.6) {+ self.core.text(text: "sleep 2; echo WOKE-BY-OUTPUT")+ self.key("Enter")+ }+ q.asyncAfter(deadline: .now() + 8.6) { self.report("before wake") }+ q.asyncAfter(deadline: .now() + 11.0) { self.report("after wake") }+ q.asyncAfter(deadline: .now() + 11.2) { self.cycleAttachDetach(times: 5); self.report("after 5 cycles connected") }+ q.asyncAfter(deadline: .now() + 12.5) { self.report("final") }+ q.asyncAfter(deadline: .now() + 15.0) { self.report("during reconnect") }+ q.asyncAfter(deadline: .now() + 19.0) {+ self.core.text(text: "echo AFTER-RECONNECT")+ self.key("Enter")+ }+ q.asyncAfter(deadline: .now() + 21.0) { self.report("after reconnect"); print("AUTOCONNECT DONE") }+ }++ /// The App's chrome over the FFI: split, list the tabs and bars, open a+ /// new tab, switch, close, and the sidebar rows.+ private func scheduleUiTest() {+ let q = DispatchQueue.main+ q.asyncAfter(deadline: .now() + 1.5) { self.connectProbe() }+ q.asyncAfter(deadline: .now() + 5.0) {+ self.refreshViews()+ self.check("tabs view", (self.tabs?.tabs.count ?? 0) >= 1, "\(self.tabs?.tabs.count ?? -1) tabs")+ self.check("nav bars", self.navs.count == 1, "\(self.navs.count) bars")+ self.chromeClick("split-right")+ }+ q.asyncAfter(deadline: .now() + 7.0) {+ self.refreshViews()+ self.check("split drew two bars", self.navs.count == 2, "\(self.navs.count) bars")+ let sidebar = self.sidebar?.rows.count ?? 0+ self.check("sidebar rows", sidebar >= 1, "\(sidebar) rows")+ self.chromeClick("new-tab")+ }+ q.asyncAfter(deadline: .now() + 9.0) {+ self.refreshViews()+ let n = self.tabs?.tabs.count ?? 0+ self.check("new tab listed", n >= 2, "\(n) tabs")+ if let first = self.tabs?.tabs.first(where: { !$0.current }) {+ self.chromeClick("pane", pane: first.target)+ }+ }+ q.asyncAfter(deadline: .now() + 11.0) {+ self.refreshViews()+ self.check("switched tab", self.tabs?.tabs.first(where: { $0.current })?.panes.count == 2, "current has \(self.tabs?.tabs.first(where: { $0.current })?.panes.count ?? -1) panes")+ let menu = self.contextMenu("pane", id: String(self.tabs?.tabs.first(where: { $0.current })?.target ?? 0))+ self.check("pane menu", !menu.isEmpty, "\(menu.count) items")+ self.chromeClick("close")+ }+ q.asyncAfter(deadline: .now() + 13.0) {+ self.refreshViews()+ self.check("closed pane", self.navs.count == 1, "\(self.navs.count) bars")+ self.report("ui done")+ print("UITEST DONE")+ }+ }++ private func scheduleImeTest() {+ let q = DispatchQueue.main+ var sent: Int { Int(inputsSent()) }+ var sizeBefore = ""+ q.asyncAfter(deadline: .now() + 1.5) { self.connectProbe() }+ q.asyncAfter(deadline: .now() + 5.0) {+ sizeBefore = self.sizeString()+ self.focusKeyboard()+ }+ q.asyncAfter(deadline: .now() + 6.5) {+ let after = self.sizeString()+ self.check("keyboard resize", after != sizeBefore, "\(sizeBefore) -> \(after)")+ }+ q.asyncAfter(deadline: .now() + 7.0) {+ guard let v = self.inputView else { self.check("input view", false, "missing"); return }+ let base = sent+ v.setMarkedText("n", selectedRange: NSRange(location: 1, length: 0))+ v.setMarkedText("ni", selectedRange: NSRange(location: 2, length: 0))+ v.setMarkedText("nih", selectedRange: NSRange(location: 3, length: 0))+ q.asyncAfter(deadline: .now() + 0.3) {+ self.check("composing sends nothing", sent == base, "sent \(sent - base), composing=\(self.composingFlag())")+ v.insertText("你")+ v.unmarkText()+ q.asyncAfter(deadline: .now() + 0.3) {+ self.check("candidate commits once", sent == base + 1, "sent \(sent - base)")+ let b2 = sent+ v.setMarkedText("hao", selectedRange: NSRange(location: 3, length: 0))+ v.setMarkedText("", selectedRange: NSRange(location: 0, length: 0))+ q.asyncAfter(deadline: .now() + 0.3) {+ self.check("cancel sends nothing", sent == b2, "sent \(sent - b2)")+ v.setMarkedText("hao", selectedRange: NSRange(location: 3, length: 0))+ v.deleteBackward()+ v.setMarkedText("ha", selectedRange: NSRange(location: 2, length: 0))+ q.asyncAfter(deadline: .now() + 0.3) {+ self.check("backspace edits composition only", sent == b2 && v.marked == "ha", "sent \(sent - b2), marked=\(v.marked ?? "nil")")+ v.unmarkText()+ q.asyncAfter(deadline: .now() + 0.3) {+ self.check("leftover composition commits once", sent == b2 + 1, "sent \(sent - b2)")+ self.key("Enter")+ q.asyncAfter(deadline: .now() + 1.5) {+ self.report("ime done")+ print("IMETEST DONE")+ }+ }+ }+ }+ }+ }+ }+ }++ private func check(_ name: String, _ ok: Bool, _ detail: String) {+ let line = "UICHECK \(ok ? "PASS" : "FAIL") \(name): \(detail)"+ print(line)+ log(line)+ }++ private func statsField(_ key: String) -> String {+ let s = core.stats()+ guard let r = s.range(of: "\"\(key)\":") else { return "" }+ let rest = s[r.upperBound...]+ return String(rest.prefix { $0 != "," && $0 != "}" }).replacingOccurrences(of: "\"", with: "")+ }++ private func inputsSent() -> Int64 { Int64(statsField("inputs_sent")) ?? -1 }+ private func composingFlag() -> String { statsField("composing") }+ private func sizeString() -> String { statsField("size") }}/// UniFFI hands the callback object to the core thread; it forwards to the/// model without touching anything that needs the main thread.private final class NotifySink: Notify, @unchecked Sendable {- weak var model: ProbeModel?+ weak var model: TerminalModel?func onFrameNeeded() { model?.coreWantsFrame() }func onStatus(status: String) { model?.coreStatus(status) }func onLog(line: String) { model?.coreLogged(line) }- func onTitle(title: String) { model?.coreLogged("title: " + title) }- func onChange() {}+ func onTitle(title: String) { model?.coreTitle(title) }+ func onChange() { model?.coreChanged() }func onClipboard(text: String) {DispatchQueue.main.async { UIPasteboard.general.string = text }}@@ -413,6 +536,7 @@ private final class NotifySink: Notify, @unchecked Sendable {self.model?.cursorRect = CGRect(x: left, y: top, width: width, height: height)}}+ func onHostKey(fingerprint: String) { model?.coreHostKey(fingerprint) }}/// Paints the graphemes the bundled faces lack with CoreText, which falls@@ -423,8 +547,6 @@ final class CoreTextPainter: GlyphPainter, @unchecked Sendable {let w = Int(width), h = Int(height)guard w > 0, h > 0 else { return Data() }let colorSpace = CGColorSpaceCreateDeviceRGB()- // CoreGraphics only draws into premultiplied contexts; the bytes are- // un-premultiplied below, since the atlas expects straight alpha.guard let ctx = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w * 4,space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValuediff --git a/ios/Sources/TerminalScreen.swift b/ios/Sources/TerminalScreen.swiftnew file mode 100644index 00000000..06308fb3--- /dev/null+++ b/ios/Sources/TerminalScreen.swift@@ -0,0 +1,376 @@+import SwiftUI++/// One host: its terminal, the tab strip, the bars over the panes, the+/// key bar, and the sidebar and menus as sheets.+struct TerminalScreen: View {+ @StateObject private var model: TerminalModel+ @Environment(\.scenePhase) private var scenePhase+ @State private var showSidebar = false+ @State private var showTabs = false+ @State private var showLog = false+ @State private var menu: MenuSheet?++ init(host: Host?, store: HostStore?) {+ _model = StateObject(wrappedValue: TerminalModel(host: host, store: store))+ }++ var body: some View {+ VStack(spacing: 0) {+ tabStrip+ terminal+ statusLine+ KeyBar(model: model)+ }+ .background(Color.black)+ .ignoresSafeArea(.container, edges: .bottom)+ .navigationTitle(model.title.isEmpty ? (model.host?.display ?? "Terminal") : model.title)+ .navigationBarTitleDisplayMode(.inline)+ .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()+ 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") }+ }+ }+ .sheet(isPresented: $showSidebar) {+ SidebarSheet(model: model, isPresented: $showSidebar)+ }+ .sheet(item: $menu) { sheet in+ MenuList(model: model, sheet: sheet) { menu = nil }+ .presentationDetents([.medium, .large])+ }+ .onAppear {+ // The automated flows connect on their own schedule.+ if !ProcessInfo.processInfo.arguments.contains(where: { $0.hasSuffix("test") || $0 == "--autoconnect" }) {+ model.connect()+ }+ }+ .onDisappear {+ model.shutdown()+ }+ .onChange(of: scenePhase) { _, phase in+ switch phase {+ case .background: model.detachForBackground()+ case .active: model.reattachAfterBackground()+ default: break+ }+ }+ }++ // MARK: the terminal with its overlays++ private 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")+ }+ navBars+ if let composing = model.composing {+ Text(composing)+ .font(.system(size: 14, design: .monospaced))+ .padding(4)+ .background(Color.yellow.opacity(0.9))+ .foregroundColor(.black)+ .padding(8)+ }+ if let card = model.status?.card {+ takeOverCard(card)+ }+ if showLog {+ logView+ }+ }+ .environmentObject(model)+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .padding(model.inset)+ .background(Color.black)+ }++ /// 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 {+ ForEach(model.navs) { nav in+ HStack(spacing: 6) {+ ForEach(nav.members) { member in+ Button {+ model.chromeClick("pane", pane: member.pane)+ } label: {+ HStack(spacing: 4) {+ if member.busy {+ ProgressView().controlSize(.mini)+ }+ Text(member.title.isEmpty ? "shell" : member.title)+ .lineLimit(1)+ .font(.system(size: 11, weight: member.current ? .semibold : .regular))+ }+ .padding(.horizontal, 6)+ .padding(.vertical, 2)+ .background(member.current ? Color.white.opacity(nav.focused ? 0.22 : 0.12) : Color.clear)+ .clipShape(Capsule())+ }+ .buttonStyle(.plain)+ }+ Spacer(minLength: 0)+ Button { model.chromeClick("new-pane", pane: nav.rect.pane) } label: {+ Image(systemName: "plus").font(.system(size: 11))+ }+ .buttonStyle(.plain)+ Button { model.chromeClick("close-pane", pane: nav.rect.pane) } label: {+ Image(systemName: "xmark").font(.system(size: 11))+ }+ .buttonStyle(.plain)+ }+ .foregroundColor(nav.focused ? .white : .gray)+ .padding(.horizontal, 6)+ .frame(width: nav.rect.width, height: nav.rect.height, alignment: .leading)+ .background(Color(white: nav.focused ? 0.16 : 0.1))+ .contentShape(Rectangle())+ .onLongPressGesture {+ menu = MenuSheet(kind: "pane", id: String(nav.rect.pane), title: "Pane")+ }+ .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+ }++ private func takeOverCard(_ card: Card) -> some View {+ VStack(spacing: 8) {+ Text(card.title).font(.headline)+ Text(card.hint).font(.caption).multilineTextAlignment(.center)+ Button(card.action) { model.takeOver() }+ .buttonStyle(.borderedProminent)+ .disabled(card.state == "taking")+ }+ .padding(16)+ .frame(maxWidth: 320)+ .background(.ultraThinMaterial)+ .clipShape(RoundedRectangle(cornerRadius: 12))+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ }++ private var logView: some View {+ ScrollView {+ Text(model.logText + "\n" + model.stats)+ .font(.system(size: 9, design: .monospaced))+ .foregroundColor(.white)+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(6)+ }+ .frame(maxHeight: 220)+ .background(Color.black.opacity(0.8))+ .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++ @ViewBuilder+ private var statusLine: some View {+ let text = model.status?.toast?.text ?? ""+ 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)+ .font(.system(size: 11, design: .monospaced))+ .lineLimit(2)+ .foregroundColor(.white)+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(.horizontal, 8)+ .padding(.vertical, 4)+ .background(Color(white: 0.2))+ }+ }+}++/// What a menu is about, for the sheet.+struct MenuSheet: Identifiable {+ var kind: String+ var id: String+ var title: String+ var key: String { kind + ":" + id }+}++struct MenuList: View {+ @ObservedObject var model: TerminalModel+ var sheet: MenuSheet+ var dismiss: () -> Void+ @State private var items: [MenuItem] = []++ var body: some View {+ NavigationStack {+ List {+ ForEach(items, id: \.rowId) { item in+ row(item)+ }+ }+ .navigationTitle(sheet.title)+ .navigationBarTitleDisplayMode(.inline)+ .toolbar {+ ToolbarItem(placement: .cancellationAction) { Button("Done", action: dismiss) }+ }+ }+ .onAppear { items = model.contextMenu(sheet.kind, id: sheet.id) }+ }++ /// Rows nest (a submenu is a row that pushes more rows), so the view+ /// is erased rather than recursively opaque.+ private func row(_ item: MenuItem) -> AnyView {+ switch item.kind {+ case "separator":+ return AnyView(Divider())+ case "header":+ return AnyView(Text(item.label).font(.caption).foregroundColor(.secondary))+ default:+ if !item.submenu.isEmpty {+ let subs = item.submenu+ return AnyView(+ NavigationLink(item.label) {+ List {+ ForEach(subs, id: \.rowId) { sub in row(sub) }+ }+ .navigationTitle(item.label)+ }+ )+ }+ return AnyView(+ Button {+ model.menuAction(item.id)+ dismiss()+ } label: {+ HStack {+ Text(item.label)+ Spacer()+ if item.checked { Image(systemName: "checkmark") }+ }+ }+ .disabled(!item.enabled)+ )+ }+ }+}++/// 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") }+ key("⌨︎") { model.focusKeyboard() }+ key("⌨︎✕") { model.dismissKeyboard() }+ }+ .padding(.horizontal, 6)+ }+ .frame(height: 38)+ .background(Color(white: 0.12))+ }++ 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)+ }+}diff --git a/ios/Sources/ThinkTermApp.swift b/ios/Sources/ThinkTermApp.swiftnew file mode 100644index 00000000..b4a77f7d--- /dev/null+++ b/ios/Sources/ThinkTermApp.swift@@ -0,0 +1,21 @@+import SwiftUI++@main+struct ThinkTermApp: App {+ @StateObject private var store = HostStore()++ var body: some Scene {+ WindowGroup {+ NavigationStack {+ 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)+ } else {+ HostsView()+ }+ }+ .environmentObject(store)+ .preferredColorScheme(.dark)+ }+ }+}diff --git a/ios/Sources/Views.swift b/ios/Sources/Views.swiftnew file mode 100644index 00000000..5e49570f--- /dev/null+++ b/ios/Sources/Views.swift@@ -0,0 +1,201 @@+import Foundation++// The App's views, as its JSON names them (thinkterm-web/src/views.rs and+// ui/src/model.ts are the reference). Field names follow the JSON.++struct PaneView: Decodable, Hashable {+ var pane: Int+ var title: String+ var current: Bool+}++struct TabView: Decodable, Hashable, Identifiable {+ var tab: Int+ var window: Int+ var title: String+ var label: String+ var target: Int+ var current: Bool+ var panes: [PaneView]+ var id: Int { tab }+}++struct Controls: Decodable, Hashable {+ var following: Bool+ var fit: Bool+ var closing: Int?+ var clipped: [Int]?+}++struct TabsView: Decodable, Hashable {+ var tabs: [TabView]+ var controls: Controls+}++struct NavRect: Decodable, Hashable {+ var pane: Int+ var left: Double+ var top: Double+ var width: Double+ var height: Double+}++struct CapsuleView: Decodable, Hashable, Identifiable {+ var pane: Int+ var title: String+ var busy: Bool+ var current: Bool+ var id: Int { pane }+}++struct NavView: Decodable, Hashable, Identifiable {+ var rect: NavRect+ var members: [CapsuleView]+ var focused: Bool+ var zoomed: Bool+ var closing: Bool+ var id: Int { rect.pane }+}++struct Toast: Decodable, Hashable {+ var text: String+ var sticky: Bool+ var at: Double+}++struct Card: Decodable, Hashable {+ var title: String+ var hint: String+ var state: String+ var action: String+}++struct StatusView: Decodable, Hashable {+ var toast: Toast?+ var card: Card?+ var summary: String+}++/// One row of the sidebar. Tagged by `kind` in the JSON.+enum SideRow: Decodable, Hashable, Identifiable {+ case space(id: String, name: String)+ case newThread+ case pinned+ case workspaces+ case project(id: String, name: String, path: String, collapsed: Bool, archived: Bool)+ case thread(ThreadRow)+ case archived(count: Int, open: Bool, label: String)+ case others+ case window(id: Int, title: String, selected: Bool)++ var id: String {+ switch self {+ case .space(let id, _): return "space:" + id+ case .newThread: return "new-thread"+ case .pinned: return "pinned"+ case .workspaces: return "workspaces"+ case .project(let id, _, _, _, _): return "project:" + id+ case .thread(let t): return "thread:" + t.id+ case .archived: return "archived"+ case .others: return "others"+ case .window(let id, _, _): return "window:\(id)"+ }+ }++ private enum Keys: String, CodingKey {+ case kind, id, name, path, collapsed, archived, count, open, label, title, selected+ }++ init(from decoder: Decoder) throws {+ let c = try decoder.container(keyedBy: Keys.self)+ switch try c.decode(String.self, forKey: .kind) {+ case "space":+ self = .space(id: try c.decode(String.self, forKey: .id), name: try c.decode(String.self, forKey: .name))+ case "new-thread": self = .newThread+ case "pinned": self = .pinned+ case "workspaces": self = .workspaces+ case "project":+ self = .project(+ id: try c.decode(String.self, forKey: .id),+ name: try c.decode(String.self, forKey: .name),+ path: try c.decode(String.self, forKey: .path),+ collapsed: try c.decode(Bool.self, forKey: .collapsed),+ archived: try c.decode(Bool.self, forKey: .archived)+ )+ case "thread": self = .thread(try ThreadRow(from: decoder))+ case "archived":+ self = .archived(+ count: try c.decode(Int.self, forKey: .count),+ open: try c.decode(Bool.self, forKey: .open),+ label: try c.decode(String.self, forKey: .label)+ )+ case "others": self = .others+ case "window":+ self = .window(+ id: try c.decode(Int.self, forKey: .id),+ title: try c.decode(String.self, forKey: .title),+ selected: try c.decode(Bool.self, forKey: .selected)+ )+ case let other:+ throw DecodingError.dataCorruptedError(forKey: .kind, in: c, debugDescription: "unknown row kind \(other)")+ }+ }+}++struct ThreadRow: Decodable, Hashable {+ var id: String+ var project: String+ var name: String+ var status: String+ var dot: String+ var pinned: Bool+ var unread: Bool+ var live: Bool+ var selected: Bool+ var deleting: Bool+}++struct Editing: Decodable, Hashable {+ var kind: String+ var id: String?+}++struct SidebarView: Decodable, Hashable {+ var rows: [SideRow]+ var editing: Editing+ var space: String?+ var new_project_error: String?+}++struct MenuItem: Decodable, Hashable, Identifiable {+ var id: String+ var label: String+ var icon: String?+ var kind: String+ var enabled: Bool+ var checked: Bool+ var submenu: [MenuItem]++ /// Separators and headers share an empty id; rows need a stable one.+ var rowId: String { id.isEmpty ? kind + ":" + label : id }+}++struct MenuOutcome: Decodable {+ var handled: Bool+ var copy: String?+ var paste: Bool+}++enum ViewJSON {+ static let decoder = JSONDecoder()++ static func decode<T: Decodable>(_ type: T.Type, _ json: String) -> T? {+ guard json != "null", let data = json.data(using: .utf8) else { return nil }+ do {+ return try decoder.decode(type, from: data)+ } catch {+ NSLog("view decode failed: %@ in %@", "\(error)", String(json.prefix(300)))+ return nil+ }+ }+}diff --git a/ios/build.sh b/ios/build.shindex 5fa0ebf2..f085cb36 100755--- a/ios/build.sh+++ b/ios/build.sh@@ -1,5 +1,5 @@#!/bin/sh-# Build the S0 iOS probe for the simulator and, optionally, run it.+# Build the iOS app for the simulator and, optionally, run it.## ios/build.sh build the Rust library, bindings, project and app# ios/build.sh run ...and boot a simulator, install, launch@@ -12,7 +12,7 @@ ROOT=$PWDSIM_TARGET=aarch64-apple-ios-simSIM_NAME=${SIM_NAME:-iPhone 17}DERIVED=${DERIVED:-$ROOT/target/xcode}-BUNDLE=com.roversx.thinkterm.ThinkTermProbe+BUNDLE=com.roversx.thinkterm.iosecho "== rust ($SIM_TARGET, release)"cargo build -p thinkterm-mobile --release --target $SIM_TARGET@@ -33,11 +33,11 @@ echo "== project"(cd ios && xcodegen generate --quiet)echo "== xcodebuild"-xcodebuild -project ios/ThinkTermProbe.xcodeproj -scheme ThinkTermProbe \+xcodebuild -project ios/ThinkTerm.xcodeproj -scheme ThinkTerm \-configuration Debug -sdk iphonesimulator \-destination "platform=iOS Simulator,name=$SIM_NAME" \-derivedDataPath "$DERIVED" build 2>&1 | grep -E "error:|warning: .*Sources/|BUILD (SUCCEEDED|FAILED)" || true-APP="$DERIVED/Build/Products/Debug-iphonesimulator/ThinkTermProbe.app"+APP="$DERIVED/Build/Products/Debug-iphonesimulator/ThinkTerm.app"test -d "$APP" || { echo "no app bundle at $APP" >&2; exit 1; }[ "${1:-}" = run ] || [ "${1:-}" = shot ] || exit 0diff --git a/ios/project.yml b/ios/project.ymlindex 1d61a689..6c112427 100644--- a/ios/project.yml+++ b/ios/project.yml@@ -1,15 +1,15 @@-# xcodegen spec for the S0 iOS probe: a SwiftUI shell around the Rust core+# xcodegen spec for the iOS app: a SwiftUI shell around the Rust core# (thinkterm-mobile, linked as a static library) that drives a CAMetalLayer# through the UniFFI bindings in Generated/. `ios/build.sh` regenerates the# bindings and the project and builds for the simulator.-name: ThinkTermProbe+name: ThinkTermoptions:bundleIdPrefix: com.roversx.thinktermdeploymentTarget:iOS: "17.0"createIntermediateGroups: truetargets:- ThinkTermProbe:+ ThinkTerm:type: applicationplatform: iOSsources:@@ -31,6 +31,8 @@ targets:base:GENERATE_INFOPLIST_FILE: YESINFOPLIST_KEY_UILaunchScreen_Generation: YES+ INFOPLIST_KEY_CFBundleDisplayName: ThinkTerm+ PRODUCT_BUNDLE_IDENTIFIER: com.roversx.thinkterm.iosINFOPLIST_KEY_UISupportedInterfaceOrientations: UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRightSWIFT_VERSION: "5.9"SWIFT_INCLUDE_PATHS: $(SRCROOT)/Generateddiff --git a/thinkterm-mobile/Cargo.toml b/thinkterm-mobile/Cargo.tomlindex 7fc1e6bc..a34ac028 100644--- a/thinkterm-mobile/Cargo.toml+++ b/thinkterm-mobile/Cargo.toml@@ -25,6 +25,8 @@ codec.workspace = truefutures.workspace = truelog.workspace = truerussh = { version = "0.63.3", default-features = false, features = ["ring"] }+serde.workspace = true+serde_json.workspace = truetermwiz = { workspace = true, features = ["use_serde"] }thinkterm-font-core.workspace = truethinkterm-font-web.workspace = truediff --git a/thinkterm-mobile/src/core.rs b/thinkterm-mobile/src/core.rsindex 6ed13e83..85c1d27a 100644--- a/thinkterm-mobile/src/core.rs+++ b/thinkterm-mobile/src/core.rs@@ -31,7 +31,7 @@ use thinkterm_web::glyphs::GlyphCache;use thinkterm_web::gpu::Gpu;use thinkterm_web::host::AppHost;use thinkterm_web::keymap::{map_key, DomKey};-use thinkterm_web::platform::{Link, Platform, WheelDelta, WheelInput};+use thinkterm_web::platform::{Link, Platform, PointerInput, WheelDelta, WheelInput};use wezterm_term::KeyModifiers;pub type MobileApp = App<MobilePlatform, SshLink>;@@ -87,6 +87,46 @@ pub enum Cmd {Paste(String),Scroll(i32),Composing(bool),+ View {+ name: String,+ reply: Sender<String>,+ },+ ChromeClick {+ action: String,+ pane: Option<u32>,+ tab: Option<u32>,+ },+ SideClick {+ kind: String,+ id: Option<String>,+ flag: Option<bool>,+ },+ SideKey {+ key: String,+ value: String,+ },+ ContextMenu {+ kind: String,+ id: String,+ reply: Sender<String>,+ },+ MenuAction {+ id: String,+ reply: Sender<String>,+ },+ SetSpace(String),+ TakeOver,+ Pointer {+ kind: String,+ x: f64,+ y: f64,+ },+ Wheel {+ x: f64,+ y: f64,+ lines: f64,+ },+ StepFont(f64),}/// The surface currently lent, if any.@@ -327,6 +367,116 @@ impl State {app.composing(on);}}+ Cmd::View { name, reply } => {+ let _ = reply.send(self.view(&name));+ }+ Cmd::ChromeClick { action, pane, tab } => {+ if let Some(app) = self.app.clone() {+ let click = thinkterm_web::commands::chrome_click(+ &action,+ pane.map(|p| p as usize),+ tab.map(|t| t as usize),+ );+ match click {+ Some(click) => app.on_chrome_click(click),+ None => self+ .notify+ .on_log(format!("chrome click {action:?} is not a thing")),+ }+ }+ }+ Cmd::SideClick { kind, id, flag } => {+ if let Some(app) = self.app.clone() {+ match thinkterm_web::commands::side_click(&kind, id, flag) {+ Some(click) => app.on_side_click(click),+ None => self+ .notify+ .on_log(format!("side click {kind:?} is not a thing")),+ }+ }+ }+ Cmd::SideKey { key, value } => {+ if let Some(app) = self.app.clone() {+ app.on_side_key(&key, value);+ }+ }+ Cmd::ContextMenu { kind, id, reply } => {+ let json = self+ .app+ .as_ref()+ .map(|app| json(&app.context_menu(&kind, &id)))+ .unwrap_or_else(|| "[]".into());+ let _ = reply.send(json);+ }+ Cmd::MenuAction { id, reply } => {+ let json = self+ .app+ .clone()+ .map(|app| json(&app.menu_action(&id)))+ .unwrap_or_else(|| "{\"handled\":false,\"copy\":null,\"paste\":false}".into());+ let _ = reply.send(json);+ }+ Cmd::SetSpace(id) => {+ if let Some(app) = &self.app {+ app.set_space(&id);+ }+ }+ Cmd::TakeOver => {+ if let Some(app) = self.app.clone() {+ app.take_over();+ }+ }+ Cmd::Pointer { kind, x, y } => {+ if let Some(app) = self.app.clone() {+ let what = match kind.as_str() {+ "down" => thinkterm_web::app::Pointer::Down,+ "move" => thinkterm_web::app::Pointer::Move,+ _ => thinkterm_web::app::Pointer::Up,+ };+ app.pointer(+ &PointerInput {+ x,+ y,+ button: 0,+ buttons_down: what != thinkterm_web::app::Pointer::Up,+ mods: KeyModifiers::NONE,+ },+ what,+ );+ }+ }+ Cmd::Wheel { x, y, lines } => {+ if let Some(app) = self.app.clone() {+ app.wheel(&WheelInput {+ x,+ y,+ delta: WheelDelta::Lines(-lines),+ mods: KeyModifiers::NONE,+ ctrl: false,+ trusted: true,+ });+ }+ }+ Cmd::StepFont(by) => {+ if let Some(app) = self.app.clone() {+ app.step_font(by);+ }+ }+ }+ }++ fn view(&self, name: &str) -> String {+ let Some(app) = &self.app else {+ return "null".into();+ };+ match name {+ "tabs" => json(&app.tabs_view()),+ "sidebar" => json(&app.sidebar_view()),+ "navs" => json(&app.navs_view()),+ "status" => json(&app.status_view()),+ "layout" => app.layout_view(),+ "strings" => json(&thinkterm_web::views::strings()),+ _ => "null".into(),}}@@ -402,15 +552,22 @@ impl State {link.shutdown();}if let Some(app) = self.app.take() {- // The App's GPU state cannot be moved out of it; a connection- // that ends takes the device with it and the next one makes a- // fresh one from the surface the shell lends again.- drop(app);- self.gpu = None;- self.white = None;- self.target = None;- self.notify- .on_log("the App and its GPU state are gone; attach the surface again".into());+ // The device, the pipeline and the surface come back to the+ // core for the next connection (or the demo).+ match App::into_gpu(app) {+ Ok(gpu) => self.gpu = Some(gpu),+ Err(app) => {+ // A task still holds the App: let it go with its GPU+ // state; the shell's next attach makes a fresh one.+ drop(app);+ self.gpu = None;+ self.white = None;+ self.target = None;+ self.notify.on_log(+ "the App was still in use; its GPU state went with it -- attach the surface again".into(),+ );+ }+ }}self.conn = Conn::Idle;}@@ -444,6 +601,7 @@ impl State {link.closed(format!("{err:#}"));}}+ Net::HostKey(fingerprint) => self.notify.on_host_key(fingerprint),Net::Stderr(text) => self.notify.on_log(format!("remote: {}", text.trim_end())),Net::Exit(code) => self.notify@@ -852,6 +1010,11 @@ impl State {}}+fn json<T: serde::Serialize>(value: &T) -> String {+ serde_json::to_string(value)+ .unwrap_or_else(|err| format!("{{\"error\":{:?}}}", err.to_string()))+}+fn white_texture(gpu: &Gpu) -> Result<GpuTexture> {let white = GpuTexture::new(&gpu.device, Arc::clone(&gpu.queue), 1, 1)?;gpu.queue.write_texture(diff --git a/thinkterm-mobile/src/lib.rs b/thinkterm-mobile/src/lib.rsindex 0da3d177..ddc67a66 100644--- a/thinkterm-mobile/src/lib.rs+++ b/thinkterm-mobile/src/lib.rs@@ -48,6 +48,9 @@ pub trait Notify: Send + Sync {fn on_focus_input(&self);/// Where the cursor cell is, in points, in the terminal view.fn on_ime_anchor(&self, left: f64, top: f64, width: f64, height: f64);+ /// The host's key fingerprint, seen before authentication: the shell+ /// remembers it and passes it back as `known_host` next time.+ fn on_host_key(&self, fingerprint: String);}/// Rust's `log` output goes to stdout, which the simulator's console shows;@@ -166,25 +169,41 @@ impl Core {/// Connect over ssh, exec the proxy on the host and attach to its/// active pane. `font_paths` are the TTF files to shape with (base face/// first); `painter` draws what they lack.+ /// `auth_kind` is "key-path" (the secret is a file path), "key" (the+ /// secret is the private key's text, `passphrase` its passphrase) or+ /// "password". `known_host` is the fingerprint remembered from an+ /// earlier connection, if any.#[allow(clippy::too_many_arguments)]pub fn connect(&self,host: String,port: u16,user: String,- key_path: String,+ auth_kind: String,+ secret: String,+ passphrase: Option<String>,+ known_host: Option<String>,remote_command: String,font_paths: Vec<String>,size_pt: f64,painter: Box<dyn painter::GlyphPainter>,) {+ let auth = match auth_kind.as_str() {+ "password" => ssh::Auth::Password(secret),+ "key" => ssh::Auth::KeyPem {+ pem: secret,+ passphrase: passphrase.filter(|p| !p.is_empty()),+ },+ _ => ssh::Auth::KeyPath(secret),+ };let _ = self.tx.send(core::Cmd::Connect {params: core::ConnectParams {ssh: ssh::SshParams {host,port,user,- key_path,+ auth,+ known_host: known_host.filter(|k| !k.is_empty()),remote_command,},font_paths,@@ -194,6 +213,84 @@ impl Core {});}+ // ----- the App's views and commands, for the shell's own interface -----++ /// One of the App's views as JSON: "tabs", "sidebar", "navs",+ /// "status", "layout" or "strings". "null" while there is no App.+ pub fn view(&self, name: String) -> String {+ let (reply, ack) = mpsc::channel();+ if self.tx.send(core::Cmd::View { name, reply }).is_err() {+ return "null".into();+ }+ ack.recv().unwrap_or_else(|_| "null".into())+ }++ /// A click on the tab strip or a pane's bar: "pane", "new-tab",+ /// "new-pane", "split-right", "split-below", "zoom", "close",+ /// "close-pane", "close-tab", "follow".+ pub fn chrome_click(&self, action: String, pane: Option<u32>, tab: Option<u32>) {+ let _ = self.tx.send(core::Cmd::ChromeClick { action, pane, tab });+ }++ /// A click in the sidebar: "thread", "window", "toggle-project",+ /// "new-thread", "pin", "delete", "archive", "unarchive"...+ pub fn side_click(&self, kind: String, id: Option<String>, flag: Option<bool>) {+ let _ = self.tx.send(core::Cmd::SideClick { kind, id, flag });+ }++ /// A key in the sidebar's text field ("Enter" commits, "Escape"+ /// cancels) with the field's text.+ pub fn side_key(&self, key: String, value: String) {+ let _ = self.tx.send(core::Cmd::SideKey { key, value });+ }++ /// The context menu for `kind` ("pane", "tab", "thread", "project",+ /// "space"...) and `id`, as JSON.+ pub fn context_menu(&self, kind: String, id: String) -> String {+ let (reply, ack) = mpsc::channel();+ if self+ .tx+ .send(core::Cmd::ContextMenu { kind, id, reply })+ .is_err()+ {+ return "[]".into();+ }+ ack.recv().unwrap_or_else(|_| "[]".into())+ }++ /// Do what a menu row asks; the outcome says whether it was handled+ /// and whether the shell should copy or paste.+ pub fn menu_action(&self, id: String) -> String {+ let (reply, ack) = mpsc::channel();+ if self.tx.send(core::Cmd::MenuAction { id, reply }).is_err() {+ return "{\"handled\":false,\"copy\":null,\"paste\":false}".into();+ }+ ack.recv().unwrap_or_default()+ }++ pub fn set_space(&self, id: String) {+ let _ = self.tx.send(core::Cmd::SetSpace(id));+ }++ pub fn take_over(&self) {+ let _ = self.tx.send(core::Cmd::TakeOver);+ }++ /// A touch on the terminal, in points: "down", "move" or "up".+ pub fn pointer(&self, kind: String, x: f64, y: f64) {+ let _ = self.tx.send(core::Cmd::Pointer { kind, x, y });+ }++ /// Scroll at a point by `lines`; positive is back into history.+ pub fn wheel(&self, x: f64, y: f64, lines: f64) {+ let _ = self.tx.send(core::Cmd::Wheel { x, y, lines });+ }++ /// Scale the focused pane's font by a tenth per step; 0 resets.+ pub fn step_font(&self, by: f64) {+ let _ = self.tx.send(core::Cmd::StepFont(by));+ }+pub fn disconnect(&self) {let _ = self.tx.send(core::Cmd::Disconnect);}diff --git a/thinkterm-mobile/src/ssh.rs b/thinkterm-mobile/src/ssh.rsindex f8a0227a..31f6ab8f 100644--- a/thinkterm-mobile/src/ssh.rs+++ b/thinkterm-mobile/src/ssh.rs@@ -5,22 +5,39 @@//! channel and are written in order; everything that comes back -- data,//! stderr, the exit status, the close -- is delivered to the core thread//! through the callback it gave us, which must not block.+//!+//! The host key is trusted on first use: its fingerprint is reported so+//! the shell can remember it, and a remembered one that no longer matches+//! ends the dial before any authentication.-use anyhow::{Context, Result};+use anyhow::{anyhow, Context, Result};use russh::client::{self, Handler};-use russh::keys::{PrivateKeyWithHashAlg, PublicKeyOrCertificate};+use russh::keys::{HashAlg, PrivateKeyWithHashAlg, PublicKeyOrCertificate};use russh::ChannelMsg;-use std::sync::Arc;+use std::sync::{Arc, Mutex};use std::time::Duration;use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};+#[derive(Debug, Clone)]+pub enum Auth {+ /// An OpenSSH private key file on disk (the probe's throwaway key).+ KeyPath(String),+ /// A private key in OpenSSH or PEM text, with its passphrase if any.+ KeyPem {+ pem: String,+ passphrase: Option<String>,+ },+ Password(String),+}+#[derive(Debug, Clone)]pub struct SshParams {pub host: String,pub port: u16,pub user: String,- /// Path to an OpenSSH private key file (unencrypted for the probe).- pub key_path: String,+ pub auth: Auth,+ /// The host key fingerprint seen last time (`SHA256:...`), if any.+ pub known_host: Option<String>,/// The command to exec; empty means the default proxy invocation.pub remote_command: String,}@@ -32,6 +49,8 @@ pub enum Out {#[derive(Debug)]pub enum Net {+ /// The host's key fingerprint, before authentication.+ HostKey(String),Connected,Data(Vec<u8>),Stderr(String),@@ -39,14 +58,29 @@ pub enum Net {Closed(String),}-struct Trusting;+struct HostKeyCheck {+ known: Option<String>,+ seen: Arc<Mutex<Option<String>>>,+}-impl Handler for Trusting {+impl Handler for HostKeyCheck {type Error = anyhow::Error;- async fn check_server_key(&mut self, _key: &PublicKeyOrCertificate) -> Result<bool> {- // The probe trusts any host key; the real client pins it on first- // use and refuses a change.- Ok(true)+ async fn check_server_key(&mut self, key: &PublicKeyOrCertificate) -> Result<bool> {+ let fingerprint = match key {+ PublicKeyOrCertificate::PublicKey { key, .. } => {+ key.fingerprint(HashAlg::Sha256).to_string()+ }+ PublicKeyOrCertificate::Certificate(cert) => {+ cert.public_key().fingerprint(HashAlg::Sha256).to_string()+ }+ };+ *self.seen.lock().unwrap() = Some(fingerprint.clone());+ match &self.known {+ Some(known) if known != &fingerprint => Err(anyhow!(+ "the host's key changed: expected {known}, got {fingerprint}. If the host was reinstalled, forget it and add it again"+ )),+ _ => Ok(true),+ }}}@@ -94,25 +128,52 @@ async fn run(keepalive_max: 3,..Default::default()});- let mut session = tokio::time::timeout(+ let seen = Arc::new(Mutex::new(None));+ let handler = HostKeyCheck {+ known: params.known_host.clone(),+ seen: Arc::clone(&seen),+ };+ let dial = tokio::time::timeout(Duration::from_secs(15),- client::connect(config, (params.host.as_str(), params.port), Trusting),+ client::connect(config, (params.host.as_str(), params.port), handler),).await- .context("connecting timed out")?- .context("ssh transport")?;+ .context("connecting timed out")?;+ if let Some(fingerprint) = seen.lock().unwrap().clone() {+ deliver(Net::HostKey(fingerprint));+ }+ let mut session = dial.context("ssh transport")?;- let key = russh::keys::load_secret_key(¶ms.key_path, None)- .with_context(|| format!("loading the key {}", params.key_path))?;- let auth = session- .authenticate_publickey(- ¶ms.user,- PrivateKeyWithHashAlg::new(Arc::new(key), None),- )- .await- .context("publickey auth")?;+ let auth = match ¶ms.auth {+ Auth::KeyPath(path) => {+ let key = russh::keys::load_secret_key(path, None)+ .with_context(|| format!("loading the key {path}"))?;+ session+ .authenticate_publickey(+ ¶ms.user,+ PrivateKeyWithHashAlg::new(Arc::new(key), None),+ )+ .await+ .context("publickey auth")?+ }+ Auth::KeyPem { pem, passphrase } => {+ let key = russh::keys::decode_secret_key(pem, passphrase.as_deref())+ .context("reading the private key")?;+ session+ .authenticate_publickey(+ ¶ms.user,+ PrivateKeyWithHashAlg::new(Arc::new(key), None),+ )+ .await+ .context("publickey auth")?+ }+ Auth::Password(password) => session+ .authenticate_password(¶ms.user, password.as_str())+ .await+ .context("password auth")?,+ };if !auth.success() {- anyhow::bail!("the host refused the key for {}", params.user);+ anyhow::bail!("the host refused the login for {}", params.user);}let mut channel = sessiondiff --git a/thinkterm-web/src/app.rs b/thinkterm-web/src/app.rsindex 6ae21c47..08ed6fa9 100644--- a/thinkterm-web/src/app.rs+++ b/thinkterm-web/src/app.rs@@ -4010,6 +4010,20 @@ impl<P: Platform, L: Link> App<P, L> {f(&mut self.inner.borrow_mut().gpu)}+ /// Let the link go and take the GPU state back, for a platform that+ /// keeps its device across connections. Fails (handing the App back)+ /// while something else still holds it -- a task on the wire, say.+ pub fn into_gpu(app: Rc<Self>) -> std::result::Result<Gpu, Rc<Self>> {+ {+ // The link's handlers hold the App; the App holds the link.+ let inner = app.inner.borrow();+ inner.link.set_push_handler(Box::new(|_| {}));+ inner.link.set_close_handler(Box::new(|_| {}));+ inner.link.shutdown();+ }+ Rc::try_unwrap(app).map(|app| app.inner.into_inner().gpu)+ }+/// See `GlyphCache::warm`. Called once, after the first frame.pub fn warm_glyph_canvas(&self) {self.inner.borrow_mut().glyphs.warm();diff --git a/thinkterm-web/src/bridge.rs b/thinkterm-web/src/bridge.rsindex 6e40fd3e..994467a3 100644--- a/thinkterm-web/src/bridge.rs+++ b/thinkterm-web/src/bridge.rs@@ -89,25 +89,8 @@ impl Client {/// thread, project or window it is about, `flag` the pin state./// Returns false for a kind the model does not know.pub fn side_click(&self, kind: String, id: Option<String>, flag: Option<bool>) -> bool {- use crate::sidebar::SideClick;- let click = match (kind.as_str(), id) {- ("thread", Some(id)) => SideClick::Thread(id),- ("window", Some(id)) => match id.parse() {- Ok(w) => SideClick::Window(w),- Err(_) => return false,- },- ("toggle-project", Some(id)) => SideClick::ToggleProject(id),- ("toggle-archived", _) => SideClick::ToggleArchived,- ("new-thread", project) => SideClick::NewThread(project),- ("new-project", _) => SideClick::NewProject,- ("pin", Some(id)) => SideClick::Pin(id, flag.unwrap_or(true)),- ("delete", Some(id)) => SideClick::Delete(id),- ("rename-thread", Some(id)) => SideClick::RenameThread(id),- ("rename-project", Some(id)) => SideClick::RenameProject(id),- ("archive", Some(id)) => SideClick::Archive(id),- ("unarchive", Some(id)) => SideClick::Unarchive(id),- ("space-menu", _) => SideClick::SpaceMenu,- _ => return false,+ let Some(click) = crate::commands::side_click(&kind, id, flag) else {+ return false;};self.app.on_side_click(click);true@@ -227,7 +210,6 @@ impl Client {/// False when the model refuses; the listing or tree that follows/// redraws the page.pub fn drop(&self, kind: String, id: String, target: Option<String>, edge: Option<String>, at: Option<u32>) -> bool {- use thinkterm_proto::SplitDirection;match kind.as_str() {"tab" => match (id.parse(), at) {(Ok(tab), Some(at)) => self.app.move_tab(tab, at as usize),@@ -237,12 +219,8 @@ impl Client {let (Ok(pane), Some(Ok(target))) = (id.parse(), target.map(|t| t.parse())) else {return false;};- let (direction, second) = match edge.as_deref() {- Some("left") => (SplitDirection::Horizontal, false),- Some("right") => (SplitDirection::Horizontal, true),- Some("top") => (SplitDirection::Vertical, false),- Some("bottom") => (SplitDirection::Vertical, true),- _ => return false,+ let Some((direction, second)) = edge.as_deref().and_then(crate::commands::drop_edge) else {+ return false;};self.app.move_pane(pane, target, direction, second)}@@ -253,20 +231,9 @@ impl Client {}pub fn chrome_click(&self, action: String, pane: Option<u32>, tab: Option<u32>) -> bool {- use crate::chrome::Click;let pane = pane.map(|p| p as usize);- let click = match (action.as_str(), pane, tab) {- ("pane", Some(p), _) => Click::Pane(p),- ("follow", _, _) => Click::Follow,- ("new-tab", _, _) => Click::NewTab,- ("new-pane", Some(p), _) => Click::NewInStack(p),- ("split-right", p, _) => Click::SplitRight(p),- ("split-below", p, _) => Click::SplitBelow(p),- ("zoom", p, _) => Click::Zoom(p),- ("close", _, _) => Click::Close,- ("close-pane", Some(p), _) => Click::ClosePane(p),- ("close-tab", _, Some(t)) => Click::CloseTab(t as usize),- _ => return false,+ let Some(click) = crate::commands::chrome_click(&action, pane, tab.map(|t| t as usize)) else {+ return false;};self.app.on_chrome_click(click);truediff --git a/thinkterm-web/src/commands.rs b/thinkterm-web/src/commands.rsnew file mode 100644index 00000000..71377ab2--- /dev/null+++ b/thinkterm-web/src/commands.rs@@ -0,0 +1,53 @@+//! The display layer's commands as strings, turned into the App's enums.+//! Shared by the page's bridge and the phone's FFI so both name a click+//! the same way.++use crate::chrome::Click;+use crate::sidebar::SideClick;+use thinkterm_proto::{PaneId, SplitDirection, TabId};++pub fn side_click(kind: &str, id: Option<String>, flag: Option<bool>) -> Option<SideClick> {+ Some(match (kind, id) {+ ("thread", Some(id)) => SideClick::Thread(id),+ ("window", Some(id)) => SideClick::Window(id.parse().ok()?),+ ("toggle-project", Some(id)) => SideClick::ToggleProject(id),+ ("toggle-archived", _) => SideClick::ToggleArchived,+ ("new-thread", project) => SideClick::NewThread(project),+ ("new-project", _) => SideClick::NewProject,+ ("pin", Some(id)) => SideClick::Pin(id, flag.unwrap_or(true)),+ ("delete", Some(id)) => SideClick::Delete(id),+ ("rename-thread", Some(id)) => SideClick::RenameThread(id),+ ("rename-project", Some(id)) => SideClick::RenameProject(id),+ ("archive", Some(id)) => SideClick::Archive(id),+ ("unarchive", Some(id)) => SideClick::Unarchive(id),+ ("space-menu", _) => SideClick::SpaceMenu,+ _ => return None,+ })+}++pub fn chrome_click(action: &str, pane: Option<PaneId>, tab: Option<TabId>) -> Option<Click> {+ Some(match (action, pane, tab) {+ ("pane", Some(p), _) => Click::Pane(p),+ ("follow", _, _) => Click::Follow,+ ("new-tab", _, _) => Click::NewTab,+ ("new-pane", Some(p), _) => Click::NewInStack(p),+ ("split-right", p, _) => Click::SplitRight(p),+ ("split-below", p, _) => Click::SplitBelow(p),+ ("zoom", p, _) => Click::Zoom(p),+ ("close", _, _) => Click::Close,+ ("close-pane", Some(p), _) => Click::ClosePane(p),+ ("close-tab", _, Some(t)) => Click::CloseTab(t),+ _ => return None,+ })+}++/// A drop's target edge, as the page names it.+pub fn drop_edge(edge: &str) -> Option<(SplitDirection, bool)> {+ Some(match edge {+ "left" => (SplitDirection::Horizontal, false),+ "right" => (SplitDirection::Horizontal, true),+ "top" => (SplitDirection::Vertical, false),+ "bottom" => (SplitDirection::Vertical, true),+ _ => return None,+ })+}diff --git a/thinkterm-web/src/lib.rs b/thinkterm-web/src/lib.rsindex be8254ea..ad7bcdd3 100644--- a/thinkterm-web/src/lib.rs+++ b/thinkterm-web/src/lib.rs@@ -10,6 +10,7 @@ pub mod app;pub mod attach;pub mod braille;pub mod chrome;+pub mod commands;pub mod emit;pub mod fallback;pub mod glyphs;