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: add the S0 probe app
RoversX5f5fdb94bc9b
diff --git a/ios/.gitignore b/ios/.gitignorenew file mode 100644index 00000000..d3abbfdf--- /dev/null+++ b/ios/.gitignore@@ -0,0 +1,3 @@+# Regenerated by ios/build.sh+Generated/+ThinkTermProbe.xcodeproj/diff --git a/ios/Resources/.gitignore b/ios/Resources/.gitignorenew file mode 100644index 00000000..d259f058--- /dev/null+++ b/ios/Resources/.gitignore@@ -0,0 +1 @@+*.ttfdiff --git a/ios/Sources/MetalView.swift b/ios/Sources/MetalView.swiftnew file mode 100644index 00000000..b2456192--- /dev/null+++ b/ios/Sources/MetalView.swift@@ -0,0 +1,57 @@+import SwiftUI+import UIKit+import QuartzCore++/// A UIView whose backing layer is the CAMetalLayer the core draws on. The+/// view reports its layer and drawable size to the model on every layout,+/// 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?++ var metalLayer: CAMetalLayer { layer as! CAMetalLayer }++ override func didMoveToWindow() {+ super.didMoveToWindow()+ if let window {+ metalLayer.contentsScale = window.screen.scale+ report()+ } else {+ model?.surfaceGone()+ }+ }++ override func layoutSubviews() {+ super.layoutSubviews()+ report()+ }++ private func report() {+ guard let model, window != nil else { return }+ let scale = Double(metalLayer.contentsScale)+ let w = Int((Double(bounds.width) * scale).rounded())+ let h = Int((Double(bounds.height) * scale).rounded())+ guard w > 0, h > 0 else { return }+ // wgpu sets drawableSize on configure; keeping the layer's own value+ // in step avoids a one-frame stretch on rotation.+ metalLayer.drawableSize = CGSize(width: w, height: h)+ model.surfaceReady(metalLayer, width: w, height: h, scale: scale)+ }+}++struct MetalView: UIViewRepresentable {+ @EnvironmentObject var model: ProbeModel++ func makeUIView(context: Context) -> MetalLayerView {+ let view = MetalLayerView()+ view.model = model+ view.backgroundColor = .black+ return view+ }++ func updateUIView(_ uiView: MetalLayerView, context: Context) {}++ static func dismantleUIView(_ uiView: MetalLayerView, coordinator: ()) {+ uiView.model?.surfaceGone()+ }+}diff --git a/ios/Sources/ProbeApp.swift b/ios/Sources/ProbeApp.swiftnew file mode 100644index 00000000..69efe226--- /dev/null+++ b/ios/Sources/ProbeApp.swift@@ -0,0 +1,131 @@+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/ProbeModel.swift b/ios/Sources/ProbeModel.swiftnew file mode 100644index 00000000..00427fab--- /dev/null+++ b/ios/Sources/ProbeModel.swift@@ -0,0 +1,462 @@+import Foundation+import UIKit+import QuartzCore+import Combine+import CoreText+import CoreGraphics++/// The shell's side of the thread contract. `Notify` calls arrive on the+/// 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 {+ @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?+ 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: Core+ private let frameNeeded = AtomicFlag()+ private var displayLink: CADisplayLink?+ private var statsTimer: Timer?+ private var logLines: [String] = []++ /// The layer currently attached, and the generation the core gave it.+ weak var layer: CAMetalLayer?+ private(set) var generation: UInt64 = 0+ private var wantsSurface = false+ private 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"++ init() {+ let sink = NotifySink()+ core = Core(notify: sink)+ sink.model = self++ let args = ProcessInfo.processInfo.arguments+ func arg(_ name: String) -> String? {+ 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 }++ let link = CADisplayLink(target: self, selector: #selector(tick))+ link.add(to: .main, forMode: .common)+ displayLink = link+ statsTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { [weak self] _ in+ 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()+ }++ func dismissKeyboard() {+ inputView?.resignFirstResponder()+ }++ // MARK: connection++ var fontPaths: [String] {+ ["JetBrainsMono-Regular", "SymbolsNerdFontMono-Regular"].compactMap {+ Bundle.main.path(forResource: $0, ofType: "ttf")+ }+ }++ func connect() {+ let paths = fontPaths+ guard 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,+ painter: CoreTextPainter()+ )+ }++ func disconnect() { core.disconnect() }++ func send() {+ guard !input.isEmpty else { return }+ core.text(text: input)+ input = ""+ }++ func sendLine() {+ core.text(text: input)+ core.key(name: "Enter", ctrl: false, alt: false, shift: false)+ input = ""+ }++ func key(_ name: String, ctrl: Bool = false, alt: Bool = false, shift: Bool = false) {+ core.key(name: name, ctrl: ctrl, alt: alt, shift: shift)+ }++ func scroll(_ lines: Int32) { core.scroll(lines: lines) }++ // MARK: autotest (driven by launch arguments; results go to 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") }+ }++ /// 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") }+ }++ /// 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")+ }+ }+ }+ }+ }+ }+ }+ }++ private func check(_ name: String, _ ok: Bool, _ detail: String) {+ let line = "IMECHECK \(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") }++ // 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 = layer+ wantsSurface = true+ if generation == 0 {+ attach(layer, width: width, height: height, scale: scale)+ } else if lastSize != (width, height, scale) {+ lastSize = (width, height, scale)+ core.resize(generation: generation, width: UInt32(width), height: UInt32(height), scale: scale)+ }+ }++ /// Called by the view before its layer goes away.+ func surfaceGone() {+ wantsSurface = false+ detach()+ }++ private func attach(_ layer: CAMetalLayer, width: Int, height: Int, scale: Double) {+ let ptr = UInt64(UInt(bitPattern: Unmanaged.passUnretained(layer).toOpaque()))+ let gen = core.attachSurface(layer: ptr, width: UInt32(width), height: UInt32(height), scale: scale)+ generation = gen+ lastSize = (width, height, scale)+ attached = gen != 0+ if gen == 0 { log("shell: attach failed") }+ }++ 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+ log(String(format: "shell: detach %d took %.2f ms", generation, ms))+ generation = 0+ attached = false+ }++ func toggleAttached() {+ if attached {+ detach()+ } else if let layer, let size = drawableSize(of: layer) {+ attach(layer, width: size.0, height: size.1, scale: size.2)+ }+ }++ func detachForBackground() {+ detach()+ report("background")+ }++ func reattachAfterBackground() {+ guard wantsSurface, generation == 0, let layer, let size = drawableSize(of: layer) else { return }+ attach(layer, width: size.0, height: size.1, scale: size.2)+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { self.report("foreground") }+ }++ func cycleAttachDetach(times: Int) {+ guard let layer, let size = drawableSize(of: layer) else { return }+ let started = CACurrentMediaTime()+ for _ in 0..<times {+ detach()+ attach(layer, width: size.0, height: size.1, scale: size.2)+ }+ let ms = (CACurrentMediaTime() - started) * 1000+ log(String(format: "shell: %d detach/attach cycles in %.1f ms", times, ms))+ }++ private func drawableSize(of layer: CAMetalLayer) -> (Int, Int, Double)? {+ let scale = Double(layer.contentsScale)+ let w = Int((Double(layer.bounds.width) * scale).rounded())+ let h = Int((Double(layer.bounds.height) * scale).rounded())+ guard w > 0, h > 0 else { return nil }+ return (w, h, scale)+ }++ // MARK: frames++ @objc private func tick() {+ if frameNeeded.take() {+ core.render()+ }+ }++ func requestOneFrame() { frameNeeded.set() }++ func toggleAnimating() {+ animating.toggle()+ core.setAnimating(on: animating)+ }++ func toggleInset() {+ inset = inset > 0 ? 0 : 60+ }++ // MARK: notify (core thread)++ fileprivate func coreWantsFrame() {+ frameNeeded.set()+ }++ fileprivate func coreStatus(_ status: String) {+ DispatchQueue.main.async {+ self.status = status+ self.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()+ }+ }+ }++ fileprivate func coreLogged(_ line: String) {+ print("core: " + line)+ DispatchQueue.main.async { self.log("core: " + line) }+ }++ private func log(_ line: String) {+ logLines.append(line)+ if logLines.count > 40 { logLines.removeFirst(logLines.count - 40) }+ logText = logLines.joined(separator: "\n")+ }+}++/// 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?+ func onFrameNeeded() { model?.coreWantsFrame() }+ func onStatus(status: String) { model?.coreStatus(status) }+ func onLog(line: String) { model?.coreLogged(line) }+}++/// Paints the graphemes the bundled faces lack with CoreText, which falls+/// through the system's cascade list (PingFang for Han, Apple Color Emoji+/// for emoji) on its own. Called on the core thread.+final class CoreTextPainter: GlyphPainter, @unchecked Sendable {+ func paint(text: String, px: Double, width: UInt32, height: UInt32, penX: Double, baseline: Double, red: UInt8, green: UInt8, blue: UInt8) -> Data {+ 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.rawValue+ ) else { return Data() }+ ctx.clear(CGRect(x: 0, y: 0, width: w, height: h))+ // Menlo's own cascade list does not reach Apple Color Emoji on iOS;+ // asking CoreText for the font that can draw this string does.+ let base = CTFontCreateWithName("Menlo" as CFString, CGFloat(px), nil)+ let font = CTFontCreateForString(base, text as CFString, CFRange(location: 0, length: (text as NSString).length))+ let color = CGColor(red: CGFloat(red) / 255, green: CGFloat(green) / 255, blue: CGFloat(blue) / 255, alpha: 1)+ let attrs: [NSAttributedString.Key: Any] = [+ NSAttributedString.Key(kCTFontAttributeName as String): font,+ NSAttributedString.Key(kCTForegroundColorAttributeName as String): color,+ ]+ let line = CTLineCreateWithAttributedString(NSAttributedString(string: text, attributes: attrs))+ // CoreGraphics draws with the origin at the bottom-left, but a+ // bitmap context's first row in memory is the top of the image, so+ // the baseline is flipped for drawing and the rows are read as-is.+ ctx.textMatrix = .identity+ ctx.textPosition = CGPoint(x: penX, y: Double(h) - baseline)+ CTLineDraw(line, ctx)+ guard let base = ctx.data else { return Data() }+ let src = base.assumingMemoryBound(to: UInt8.self)+ var out = [UInt8](repeating: 0, count: w * h * 4)+ for row in 0..<h {+ let srcRow = row * w * 4+ let dstRow = row * w * 4+ for x in 0..<w {+ let s = srcRow + x * 4, d = dstRow + x * 4+ let a = src[s + 3]+ if a == 0 { continue }+ let scale = 255.0 / Double(a)+ out[d] = UInt8(min(255.0, Double(src[s]) * scale))+ out[d + 1] = UInt8(min(255.0, Double(src[s + 1]) * scale))+ out[d + 2] = UInt8(min(255.0, Double(src[s + 2]) * scale))+ out[d + 3] = a+ }+ }+ return Data(out)+ }+}++final class AtomicFlag: @unchecked Sendable {+ private let lock = NSLock()+ private var value = false+ func set() { lock.lock(); value = true; lock.unlock() }+ func take() -> Bool { lock.lock(); defer { lock.unlock() }; let v = value; value = false; return v }+}diff --git a/ios/Sources/TerminalInputView.swift b/ios/Sources/TerminalInputView.swiftnew file mode 100644index 00000000..044b49b0--- /dev/null+++ b/ios/Sources/TerminalInputView.swift@@ -0,0 +1,299 @@+import SwiftUI+import 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 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.+ private(set) var marked: String?+ /// Selection inside the marked text, for the IME's own bookkeeping.+ private var markedSelection = NSRange(location: 0, length: 0)++ override init(frame: CGRect) {+ super.init(frame: frame)+ isUserInteractionEnabled = true+ backgroundColor = .clear+ addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapped)))+ }++ required init?(coder: NSCoder) { fatalError() }++ @objc private func tapped() {+ if !isFirstResponder {+ becomeFirstResponder()+ }+ }++ override var canBecomeFirstResponder: Bool { true }++ // MARK: composition bookkeeping++ private func beginComposing() {+ if marked == nil {+ model?.core.setComposing(on: true)+ }+ }++ private func endComposing() {+ if marked != nil {+ marked = nil+ markedSelection = NSRange(location: 0, length: 0)+ model?.core.setComposing(on: false)+ }+ 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.+ func dropComposition() {+ endComposing()+ }++ // MARK: UIKeyInput++ 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)+ }+ }++ 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")+ }++ // MARK: UITextInput -- marked text++ var markedTextRange: UITextRange? {+ guard let marked, !marked.isEmpty else { return nil }+ return Range(0, marked.utf16.count)+ }++ var markedTextStyle: [NSAttributedString.Key: Any]? {+ get { nil }+ set {}+ }++ func setMarkedText(_ markedText: String?, selectedRange: NSRange) {+ let text = markedText ?? ""+ if text.isEmpty {+ // The IME cleared its buffer without committing: a cancel.+ endComposing()+ return+ }+ beginComposing()+ marked = text+ markedSelection = selectedRange+ model?.compositionChanged(text)+ }++ 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 = nil+ model?.core.setComposing(on: false)+ model?.compositionChanged(nil)+ model?.core.text(text: marked)+ return+ }+ endComposing()+ }++ // 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+ return Range(n, n)+ }+ set {}+ }++ var beginningOfDocument: UITextPosition { Pos(0) }+ var endOfDocument: UITextPosition { Pos(marked?.utf16.count ?? 0) }++ func text(in range: UITextRange) -> String? {+ guard let r = range as? Range, let marked else { return nil }+ let s = marked.utf16+ guard r.a <= s.count, r.b <= s.count, r.a <= r.b else { return nil }+ let start = s.index(s.startIndex, offsetBy: r.a)+ let end = s.index(s.startIndex, offsetBy: r.b)+ return String(s[start..<end])+ }++ 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)+ }++ func textRange(from fromPosition: UITextPosition, to toPosition: UITextPosition) -> UITextRange? {+ guard let a = fromPosition as? Pos, let b = toPosition as? Pos else { return nil }+ return Range(min(a.i, b.i), max(a.i, b.i))+ }++ func position(from position: UITextPosition, offset: Int) -> UITextPosition? {+ guard let p = position as? Pos else { return nil }+ let n = p.i + offset+ let max = marked?.utf16.count ?? 0+ return (0...max).contains(n) ? Pos(n) : nil+ }++ func position(from position: UITextPosition, in direction: UITextLayoutDirection, offset: Int) -> UITextPosition? {+ switch direction {+ case .right, .down: return self.position(from: position, offset: offset)+ case .left, .up: return self.position(from: position, offset: -offset)+ @unknown default: return nil+ }+ }++ func compare(_ position: UITextPosition, to other: UITextPosition) -> ComparisonResult {+ guard let a = position as? Pos, let b = other as? Pos else { return .orderedSame }+ return a.i < b.i ? .orderedAscending : a.i > b.i ? .orderedDescending : .orderedSame+ }++ func offset(from: UITextPosition, to toPosition: UITextPosition) -> Int {+ guard let a = from as? Pos, let b = toPosition as? Pos else { return 0 }+ return b.i - a.i+ }++ var inputDelegate: UITextInputDelegate? {+ get { nil }+ set {}+ }++ var tokenizer: UITextInputTokenizer { UITextInputStringTokenizer(textInput: self) }++ func position(within range: UITextRange, farthestIn direction: UITextLayoutDirection) -> UITextPosition? {+ guard let r = range as? Range else { return nil }+ switch direction {+ case .left, .up: return Pos(r.a)+ default: return Pos(r.b)+ }+ }++ func characterRange(byExtending position: UITextPosition, in direction: UITextLayoutDirection) -> UITextRange? {+ guard let p = position as? Pos else { return nil }+ return Range(p.i, p.i)+ }++ func baseWritingDirection(for position: UITextPosition, in direction: UITextStorageDirection) -> NSWritingDirection {+ .leftToRight+ }++ 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] { [] }+ func closestPosition(to point: CGPoint) -> UITextPosition? { endOfDocument }+ func closestPosition(to point: CGPoint, within range: UITextRange) -> UITextPosition? { endOfDocument }+ func characterRange(at point: CGPoint) -> UITextRange? { nil }++ // MARK: traits: a terminal wants raw keys, no autocorrect++ var keyboardType: UIKeyboardType { .asciiCapable }+ var autocorrectionType: UITextAutocorrectionType { .no }+ var autocapitalizationType: UITextAutocapitalizationType { .none }+ var spellCheckingType: UITextSpellCheckingType { .no }+ var smartQuotesType: UITextSmartQuotesType { .no }+ var smartDashesType: UITextSmartDashesType { .no }+ var smartInsertDeleteType: UITextSmartInsertDeleteType { .no }+ var returnKeyType: UIReturnKeyType { .default }+ var enablesReturnKeyAutomatically: Bool { false }++ // MARK: hardware keyboard++ 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"),+ ]+ for (input, _) in arrows {+ let c = UIKeyCommand(input: input, modifierFlags: [], action: #selector(hardwareKey(_:)))+ c.wantsPriorityOverSystemBehavior = true+ cmds.append(c)+ }+ for ch in "abcdefghijklmnopqrstuvwxyz[]\\" {+ let c = UIKeyCommand(input: String(ch), modifierFlags: .control, action: #selector(hardwareKey(_:)))+ c.wantsPriorityOverSystemBehavior = true+ cmds.append(c)+ }+ return cmds+ }++ @objc private func hardwareKey(_ cmd: UIKeyCommand) {+ guard let input = cmd.input else { return }+ let name: String+ switch input {+ case UIKeyCommand.inputUpArrow: name = "ArrowUp"+ case UIKeyCommand.inputDownArrow: name = "ArrowDown"+ case UIKeyCommand.inputLeftArrow: name = "ArrowLeft"+ case UIKeyCommand.inputRightArrow: name = "ArrowRight"+ case UIKeyCommand.inputEscape: name = "Escape"+ case "\t": name = "Tab"+ default: name = input+ }+ model?.key(name, ctrl: cmd.modifierFlags.contains(.control), alt: cmd.modifierFlags.contains(.alternate), shift: cmd.modifierFlags.contains(.shift))+ }++ // MARK: positions++ final class Pos: UITextPosition {+ let i: Int+ init(_ i: Int) { self.i = i }+ }++ final class Range: UITextRange {+ let a: Int, b: Int+ init(_ a: Int, _ b: Int) { self.a = a; self.b = b }+ override var isEmpty: Bool { a == b }+ override var start: UITextPosition { Pos(a) }+ override var end: UITextPosition { Pos(b) }+ }+}++struct TerminalInput: UIViewRepresentable {+ @EnvironmentObject var model: ProbeModel++ func makeUIView(context: Context) -> TerminalInputView {+ let view = TerminalInputView()+ view.model = model+ model.inputView = view+ return view+ }++ func updateUIView(_ uiView: TerminalInputView, context: Context) {}+}diff --git a/ios/build.sh b/ios/build.shnew file mode 100755index 00000000..5fa0ebf2--- /dev/null+++ b/ios/build.sh@@ -0,0 +1,56 @@+#!/bin/sh+# Build the S0 iOS probe 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+# ios/build.sh shot FILE ...and save a screenshot to FILE after launch+#+# Device builds (aarch64-apple-ios) need a signing team; not wired here yet.+set -eu+cd "$(dirname "$0")/.."+ROOT=$PWD+SIM_TARGET=aarch64-apple-ios-sim+SIM_NAME=${SIM_NAME:-iPhone 17}+DERIVED=${DERIVED:-$ROOT/target/xcode}+BUNDLE=com.roversx.thinkterm.ThinkTermProbe++echo "== rust ($SIM_TARGET, release)"+cargo build -p thinkterm-mobile --release --target $SIM_TARGET++echo "== bindings"+rm -rf ios/Generated && mkdir -p ios/Generated+cargo run -q -p thinkterm-mobile --bin uniffi-bindgen -- generate \+ --library target/$SIM_TARGET/release/libthinkterm_mobile.a \+ --language swift --out-dir ios/Generated+# Swift finds a module by a `module.modulemap` on its include path.+mv ios/Generated/thinkterm_mobileFFI.modulemap ios/Generated/module.modulemap++echo "== fonts"+mkdir -p ios/Resources+cp assets/fonts/JetBrainsMono-Regular.ttf assets/fonts/SymbolsNerdFontMono-Regular.ttf ios/Resources/++echo "== project"+(cd ios && xcodegen generate --quiet)++echo "== xcodebuild"+xcodebuild -project ios/ThinkTermProbe.xcodeproj -scheme ThinkTermProbe \+ -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"+test -d "$APP" || { echo "no app bundle at $APP" >&2; exit 1; }++[ "${1:-}" = run ] || [ "${1:-}" = shot ] || exit 0++echo "== simulator"+UDID=$(xcrun simctl list devices available | grep "$SIM_NAME (" | head -1 | sed -E 's/.*\(([0-9A-F-]+)\).*/\1/')+xcrun simctl boot "$UDID" 2>/dev/null || true+xcrun simctl bootstatus "$UDID" -b >/dev/null+xcrun simctl install "$UDID" "$APP"+xcrun simctl terminate "$UDID" $BUNDLE 2>/dev/null || true+xcrun simctl launch "$UDID" $BUNDLE+if [ "${1:-}" = shot ]; then+ sleep "${SHOT_DELAY:-3}"+ xcrun simctl io "$UDID" screenshot "$2"+ echo "screenshot: $2"+fidiff --git a/ios/project.yml b/ios/project.ymlnew file mode 100644index 00000000..1d61a689--- /dev/null+++ b/ios/project.yml@@ -0,0 +1,46 @@+# xcodegen spec for the S0 iOS probe: 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+options:+ bundleIdPrefix: com.roversx.thinkterm+ deploymentTarget:+ iOS: "17.0"+ createIntermediateGroups: true+targets:+ ThinkTermProbe:+ type: application+ platform: iOS+ sources:+ - path: Sources+ - path: Generated+ excludes:+ - "*.h"+ - "*.modulemap"+ # Listed file by file: an iOS bundle is flat, and a folder reference+ # would nest a Resources/ directory the installer rejects.+ - path: Resources+ buildPhase: resources+ excludes:+ - ".gitignore"+ dependencies:+ - sdk: Metal.framework+ - sdk: QuartzCore.framework+ settings:+ base:+ GENERATE_INFOPLIST_FILE: YES+ INFOPLIST_KEY_UILaunchScreen_Generation: YES+ INFOPLIST_KEY_UISupportedInterfaceOrientations: UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight+ SWIFT_VERSION: "5.9"+ SWIFT_INCLUDE_PATHS: $(SRCROOT)/Generated+ # The crate also emits a cdylib (for Android later); naming the .a by+ # path keeps the linker from preferring the .dylib next to it.+ "OTHER_LDFLAGS[sdk=iphonesimulator*]": $(SRCROOT)/../target/aarch64-apple-ios-sim/release/libthinkterm_mobile.a+ "OTHER_LDFLAGS[sdk=iphoneos*]": $(SRCROOT)/../target/aarch64-apple-ios/release/libthinkterm_mobile.a+ ENABLE_USER_SCRIPT_SANDBOXING: NO+ CODE_SIGN_STYLE: Automatic+ DEVELOPMENT_TEAM: ""+ configs:+ Debug:+ "CODE_SIGNING_ALLOWED[sdk=iphonesimulator*]": NO