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
feat(ios): redo the sidebar, top bar and live overview
RoversXf6d458c78374
diff --git a/ios/Resources/strings.json b/ios/Resources/strings.jsonindex 7a96935a..24ab45ef 100644--- a/ios/Resources/strings.json+++ b/ios/Resources/strings.json@@ -209,7 +209,9 @@"zoom": "Bereich zoomen","hostkey.approve.title": "Diesem SSH-Hostschlüssel vertrauen?","hostkey.approve.body": "Bevor Sie ein Passwort senden oder sich mit einem Schlüssel authentifizieren, gleichen Sie diesen SHA-256-Fingerabdruck über einen vertrauenswürdigen Kanal mit dem Serveradministrator ab. Brechen Sie bei einer Abweichung ab.",- "hostkey.approve.accept": "Vertrauen und verbinden"+ "hostkey.approve.accept": "Vertrauen und verbinden",+ "thread.find": "Thread finden",+ "thread.find.none": "Kein Thread passt"},"en-US": {"archived": "Archived",@@ -421,7 +423,9 @@"zoom": "Zoom pane","hostkey.approve.title": "Trust this SSH host key?","hostkey.approve.body": "Before sending a password or authenticating with a key, verify this SHA-256 fingerprint with the server administrator over a trusted channel. Cancel if it differs.",- "hostkey.approve.accept": "Trust and connect"+ "hostkey.approve.accept": "Trust and connect",+ "thread.find": "Find Thread",+ "thread.find.none": "No thread matches"},"fr-FR": {"archived": "Archivés",@@ -633,7 +637,9 @@"zoom": "Zoomer le volet","hostkey.approve.title": "Faire confiance à cette clé d’hôte SSH ?","hostkey.approve.body": "Avant d’envoyer un mot de passe ou de vous authentifier avec une clé, vérifiez cette empreinte SHA-256 auprès de l’administrateur du serveur via un canal de confiance. Annulez si elle ne correspond pas.",- "hostkey.approve.accept": "Faire confiance et se connecter"+ "hostkey.approve.accept": "Faire confiance et se connecter",+ "thread.find": "Rechercher une session",+ "thread.find.none": "Aucune session ne correspond"},"ja-JP": {"archived": "アーカイブ済み",@@ -845,7 +851,9 @@"zoom": "ペインをズーム","hostkey.approve.title": "この SSH ホスト鍵を信頼しますか?","hostkey.approve.body": "パスワードを送信したり鍵で認証したりする前に、信頼できる通信手段でサーバー管理者にこの SHA-256 フィンガープリントを確認してください。一致しない場合はキャンセルしてください。",- "hostkey.approve.accept": "信頼して接続"+ "hostkey.approve.accept": "信頼して接続",+ "thread.find": "セッションを検索",+ "thread.find.none": "一致するセッションはありません"},"zh-CN": {"archived": "已归档",@@ -1057,6 +1065,8 @@"zoom": "缩放 pane","hostkey.approve.title": "信任这个 SSH 主机密钥?","hostkey.approve.body": "发送密码或进行密钥认证前,请通过可信渠道与服务器管理员核对以上 SHA-256 指纹。不一致请取消。",- "hostkey.approve.accept": "信任并连接"+ "hostkey.approve.accept": "信任并连接",+ "thread.find": "查找会话",+ "thread.find.none": "没有匹配的会话"}}diff --git a/ios/Sources/AppSettings.swift b/ios/Sources/AppSettings.swiftindex 796b0400..5aeedfe5 100644--- a/ios/Sources/AppSettings.swift+++ b/ios/Sources/AppSettings.swift@@ -69,10 +69,6 @@ final class AppSettings: ObservableObject {// MARK: interface- /// "one" or "two" levels of tabs: threads over tabs, or tabs alone.- @Published var tabBarLevels: String {- didSet { defaults.set(tabBarLevels, forKey: "ui.tabbar") }- }/// The bars over split panes; off, the rows go to the terminal.@Published var paneBars: Bool {didSet { defaults.set(paneBars, forKey: "ui.panebars") }@@ -144,7 +140,6 @@ final class AppSettings: ObservableObject {cursorBlink = d.object(forKey: "cursor.blink") as? Bool ?? truebell = d.object(forKey: "bell") as? Bool ?? falseresizeMode = d.string(forKey: "resize.mode") ?? "auto"- tabBarLevels = d.string(forKey: "ui.tabbar") ?? "two"paneBars = d.object(forKey: "ui.panebars") as? Bool ?? truehapticKeys = d.object(forKey: "key.haptics") as? Bool ?? trueautoKeyPanel = d.object(forKey: "key.autopanel") as? Bool ?? falsediff --git a/ios/Sources/HostsView.swift b/ios/Sources/HostsView.swiftindex 85dc67c8..70a644f2 100644--- a/ios/Sources/HostsView.swift+++ b/ios/Sources/HostsView.swift@@ -67,11 +67,17 @@ struct HostsView: View {.navigationBarTitleDisplayMode(.large).searchable(text: $search, placement: .navigationBarDrawer, prompt: tr("hosts.search")).navigationDestination(for: Host.self) { host in- if host.name == "probe" {+ #if DEBUG+ // The development row's stand-in host, told by its id: a real+ // host may well be called "probe".+ if host.id == probe.id {TerminalScreen(model: sessions.model(for: nil, store: store))} else {TerminalScreen(model: sessions.model(for: host, store: store))}+ #else+ TerminalScreen(model: sessions.model(for: host, store: store))+ #endif}// A separate destination type so the context menu's Connect can push// without fighting the value-based destination above.diff --git a/ios/Sources/KeyBar.swift b/ios/Sources/KeyBar.swiftindex cce94953..49a775f9 100644--- a/ios/Sources/KeyBar.swift+++ b/ios/Sources/KeyBar.swift@@ -11,12 +11,16 @@ struct KeyBar: View {@State private var tab: KeyPanelTab = KeyBar.debugTab@ObservedObject private var settings = AppSettings.shared- /// `--keypanel snippets` also picks the face it opens on.+ /// `--keypanel snippets` also picks the face it opens on (debug builds).private static var debugTab: KeyPanelTab {+ #if DEBUGlet args = ProcessInfo.processInfo.argumentsguard let i = args.firstIndex(of: "--keypanel"), i + 1 < args.count,let tab = KeyPanelTab(rawValue: args[i + 1]) else { return .keys }return tab+ #else+ return .keys+ #endif}var body: some View {diff --git a/ios/Sources/KeyPanel.swift b/ios/Sources/KeyPanel.swiftindex dd9516d8..eac4bf36 100644--- a/ios/Sources/KeyPanel.swift+++ b/ios/Sources/KeyPanel.swift@@ -178,7 +178,11 @@ struct KeyPanel: View {@State private var draft: SnippetDraft?/// `--settings` alongside `--keypanel` opens the settings sheet at/// launch: the simulator cannot be tapped, and a screenshot needs it.+ #if DEBUG@State private var showSettings = ProcessInfo.processInfo.arguments.contains("--settings")+ #else+ @State private var showSettings = false+ #endifprivate let columns = Array(repeating: GridItem(.flexible(), spacing: 8), count: 6)@@ -216,7 +220,7 @@ struct KeyPanel: View {}.sheet(isPresented: $showSettings) {NavigationStack {- SettingsView(model: model, showLog: nil)+ SettingsView(showLog: nil).toolbar {ToolbarItem(placement: .confirmationAction) {Button(tr("done")) { showSettings = false }diff --git a/ios/Sources/Overview.swift b/ios/Sources/Overview.swiftnew file mode 100644index 00000000..4b3eccb9--- /dev/null+++ b/ios/Sources/Overview.swift@@ -0,0 +1,582 @@+import SwiftUI+import CoreText++/// The desktop's Live Overview: a card for each thread running in the+/// Space on show, as many to a row as the width takes, each in the+/// terminal's own shape with its whole screen in it -- the server's rows,+/// in the terminal's face and colours, fetched again while the overview+/// is up. The thread on show is the terminal itself on the way in and out+/// (`TerminalScreen`): its card's picture shows once the terminal has+/// faded into it.+struct OverviewScreen: View {+ @ObservedObject var model: TerminalModel+ @ObservedObject private var lang = AppLanguage.shared+ @Environment(\.scenePhase) private var phase+ /// The terminal's size: every picture has its shape.+ var stage: CGSize+ var liveThread: String?+ /// The live card's picture shows: the terminal has faded into it.+ var liveShown: Bool+ /// Where a card's picture is, in the screen's space, as it moves.+ var onThumb: (String, CGRect) -> Void+ var onPick: (ThreadView) -> Void+ var onClose: () -> Void+ @State private var sight = Sight()++ /// The cards in sight, once any has said: only their screens are+ /// fetched again. Not the view's state: a card scrolled in or out+ /// changes nothing on show.+ private final class Sight {+ var shown: Set<String>?+ }++ static let gap: CGFloat = 12+ private static let margin: CGFloat = 14+ /// Above the heading, under it, and round a card's picture.+ private static let top: CGFloat = 4+ private static let headingGap: CGFloat = 10+ private static let inset: CGFloat = 6+ /// The picture's corners; the zoom rounds the terminal to them.+ static let thumbRadius: CGFloat = 10+ /// Behind the cards, and the bar over them.+ static let backdrop = Color(white: 0.06)++ /// The terminal's shape, a phone's before it is measured.+ private var aspect: CGFloat {+ stage.width > 0 && stage.height > 0 ? stage.width / stage.height : 0.6+ }++ /// Running threads only, as on the desktop: a thread that runs nothing+ /// has no screen to show.+ private var threads: [ThreadView] { (model.threads?.threads ?? []).filter(\.live) }++ /// A card's width: at least this, at most that, as on the desktop.+ private static let minCard: CGFloat = 160+ private static let maxCard: CGFloat = 640+ /// Below this, a column goes sooner than a lone card in the last row.+ private static let comfortCard: CGFloat = 240++ /// The desktop's columns (`shared_grid_columns`): as many as fit at the+ /// least width, up to four, never more than there are cards; one fewer+ /// when that leaves no lone card under a full row and the cards are+ /// narrow anyway.+ static func columns(for width: CGFloat, count: Int) -> Int {+ var columns = max(1, min(4, Int((width + gap) / (minCard + gap)), count))+ let lone = { (columns: Int) in count > columns && count % columns == 1 }+ if columns > 2, cardWidth(for: width, columns: columns) < comfortCard, lone(columns), !lone(columns - 1) {+ columns -= 1+ }+ return columns+ }++ /// Never below a point: a first pass may offer no width at all.+ static func cardWidth(for width: CGFloat, columns: Int) -> CGFloat {+ max(1, min(maxCard, (width - gap * CGFloat(columns - 1)) / CGFloat(columns)))+ }++ /// Where the picture of the card at `index` of `count` will be, `width`+ /// across, before the cards are laid out: the terminal's flight sets off+ /// for it at once, and turns to where the card turns out to be.+ static func estimatedThumb(index: Int, count: Int, width: CGFloat, aspect: CGFloat) -> CGRect {+ let inner = width - 2 * margin+ let columns = columns(for: inner, count: count)+ let cardWidth = cardWidth(for: inner, columns: columns)+ let (row, column) = (index / columns, index % columns)+ let inRow = min(columns, count - row * columns)+ let rowWidth = CGFloat(inRow) * cardWidth + gap * CGFloat(inRow - 1)+ let thumbWidth = max(1, cardWidth - 2 * inset)+ let thumbHeight = thumbWidth / max(aspect, 0.1)+ let heading = UIFont.preferredFont(forTextStyle: .footnote).lineHeight+ let cardHeading = UIFont.preferredFont(forTextStyle: .subheadline).lineHeight + CardHeading.padding+ let cardHeight = cardHeading + thumbHeight + inset+ return CGRect(+ x: margin + (inner - rowWidth) / 2 + CGFloat(column) * (cardWidth + gap) + inset,+ y: top + heading + headingGap + CGFloat(row) * (cardHeight + gap) + cardHeading,+ width: thumbWidth,+ height: thumbHeight+ )+ }++ var body: some View {+ GeometryReader { geo in+ let inner = geo.size.width - 2 * Self.margin+ let columns = Self.columns(for: inner, count: threads.count)+ ScrollViewReader { reader in+ ScrollView {+ VStack(alignment: .leading, spacing: Self.headingGap) {+ heading+ if threads.isEmpty {+ Text(tr("overview.empty"))+ .font(.callout)+ .foregroundStyle(.secondary)+ .frame(maxWidth: .infinity)+ .padding(.top, 60)+ } else {+ grid(columns: columns, cardWidth: Self.cardWidth(for: inner, columns: columns))+ }+ }+ .padding(.horizontal, Self.margin)+ .padding(.top, Self.top)+ .padding(.bottom, 24 + TerminalScreen.bottomInset)+ }+ .onAppear {+ // The thread on show in sight before the terminal goes+ // into its card.+ if let live = liveThread { reader.scrollTo(live, anchor: .center) }+ }+ }+ }+ .foregroundColor(.white)+ .dynamicTypeSize(...DynamicTypeSize.xxLarge)+ // Pinching back in returns to the terminal.+ .simultaneousGesture(MagnifyGesture().onEnded { value in+ if value.magnification > 1.25 { onClose() }+ })+ .task(id: phase) {+ // One ticker while the overview is up and the app in front.+ guard phase == .active else { return }+ while !Task.isCancelled {+ for thread in threads where sight.shown?.contains(thread.id) ?? true {+ if let pane = Self.pane(of: thread) { model.requestScreen(pane: pane) }+ }+ try? await Task.sleep(for: .milliseconds(1500))+ }+ }+ }++ /// The Space and how many of its threads run.+ private var heading: some View {+ HStack(spacing: 8) {+ Text(model.threads?.space ?? "").font(.footnote.weight(.semibold))+ Rectangle().fill(Color.white.opacity(0.1)).frame(height: 1)+ Text(verbatim: "\(threads.count)").font(.footnote.monospacedDigit())+ }+ .foregroundStyle(.secondary)+ }++ /// Rows of cards of one width, each row centred as the desktop's are.+ private func grid(columns: Int, cardWidth: CGFloat) -> some View {+ VStack(spacing: Self.gap) {+ ForEach(Array(stride(from: 0, to: threads.count, by: columns)), id: \.self) { start in+ HStack(alignment: .top, spacing: Self.gap) {+ ForEach(threads[start..<min(start + columns, threads.count)]) { card($0).frame(width: cardWidth) }+ }+ .frame(maxWidth: .infinity)+ }+ }+ }++ /// The pane a thread's card shows: its current tab's.+ static func pane(of thread: ThreadView) -> Int? {+ (thread.tabs.first(where: \.current) ?? thread.tabs.first)?.target+ }++ private func card(_ thread: ThreadView) -> some View {+ let live = thread.id == liveThread+ let pane = Self.pane(of: thread)+ let screen = pane.flatMap { model.screens[$0] }+ return Button { onPick(thread) } label: {+ VStack(alignment: .leading, spacing: 0) {+ CardHeading(thread: thread)+ ScreenThumb(model: model, pane: pane, picture: pane.flatMap { model.pictures[$0] }, serial: pane.flatMap { model.screenSerials[$0] } ?? 0)+ .opacity(live && !liveShown ? 0 : 1)+ // The terminal's own background under its picture, so a+ // fade between the two never shows the card through.+ .background(live ? model.background : (screen.flatMap { Color(hex: $0.background) } ?? model.background))+ .aspectRatio(aspect, contentMode: .fit)+ .clipShape(RoundedRectangle(cornerRadius: Self.thumbRadius, style: .continuous))+ .onGeometryChange(for: CGRect.self) { $0.frame(in: .named("screen")) } action: { onThumb(thread.id, $0) }+ .padding([.horizontal, .bottom], Self.inset)+ }+ .background(Color(white: 0.13), in: RoundedRectangle(cornerRadius: 16, style: .continuous))+ .overlay {+ if live {+ RoundedRectangle(cornerRadius: 16, style: .continuous).strokeBorder(Color.accentColor, lineWidth: 2)+ }+ }+ .contentShape(RoundedRectangle(cornerRadius: 16, style: .continuous))+ }+ .buttonStyle(.plain)+ .contextMenu { AppMenuItems(model: model, kind: "thread", id: thread.id) }+ .onScrollVisibilityChange(threshold: 0.05) { visible in+ var shown = sight.shown ?? []+ if visible {+ shown.insert(thread.id)+ // Scrolled into sight: its screen as it is now, not at the+ // next tick.+ if let pane = Self.pane(of: thread) { model.requestScreen(pane: pane) }+ } else {+ shown.remove(thread.id)+ }+ sight.shown = shown+ }+ .id(thread.id)+ }+}++/// A card's top: the thread's mark, its project and name as the desktop+/// titles a card, and what its current tab runs.+private struct CardHeading: View {+ let thread: ThreadView+ /// Above and below the line.+ static let padding: CGFloat = 16++ private var title: String {+ thread.project.isEmpty || thread.project == thread.name ? thread.name : "\(thread.project) · \(thread.name)"+ }++ var body: some View {+ let running = (thread.tabs.first(where: \.current) ?? thread.tabs.first)?.title ?? ""+ HStack(spacing: 6) {+ ThreadMark(status: thread.status, dot: thread.dot, size: 7)+ // The title keeps its room; what runs gives way first.+ Text(title).font(.subheadline.weight(.semibold)).lineLimit(1).layoutPriority(1)+ Spacer(minLength: 4)+ Text(running).font(.caption2.monospaced()).foregroundStyle(.secondary).lineLimit(1)+ }+ .padding(.horizontal, 10)+ .padding(.top, 9)+ .padding(.bottom, Self.padding - 9)+ }+}++/// A pane's whole screen in miniature: the picture `ScreenPainter` drew+/// of it at the box's size, drawn again when the screen or the box+/// changes. Its picture and the screen's serial come from the card, so a+/// card is looked at again only when they or the box change.+struct ScreenThumb: View {+ let model: TerminalModel+ let pane: Int?+ let picture: CGImage?+ let serial: Int+ @Environment(\.displayScale) private var scale++ private struct Turn: Equatable {+ var pane: Int?+ var serial: Int+ var size: CGSize+ }++ var body: some View {+ GeometryReader { geo in+ let turn = Turn(pane: pane, serial: serial, size: geo.size)+ ZStack(alignment: .topLeading) {+ if let picture {+ Image(decorative: picture, scale: scale)+ .resizable()+ .frame(width: geo.size.width, height: geo.size.height)+ }+ }+ .task(id: turn) {+ guard let pane = turn.pane, turn.serial > 0, turn.size.width > 0 else { return }+ model.paintScreen(pane: pane, pixels: CGSize(width: turn.size.width * scale, height: turn.size.height * scale))+ }+ }+ .allowsHitTesting(false)+ }+}++/// Draws a tab as a picture, split as it is: every pane's runs at their+/// own columns where the pane lies, in the terminal's face and colours,+/// the cells as large as the picture lets the tab's columns and rows fit,+/// from the top left. Runs off the main thread (`TerminalModel.paintScreen`).+enum ScreenPainter {+ static func paint(_ tab: TabPreview, pixels: CGSize, face: String) -> CGImage? {+ let width = Int(pixels.width.rounded()), height = Int(pixels.height.rounded())+ guard width > 0, height > 0, tab.cols > 0, tab.rows > 0,+ let space = CGColorSpace(name: CGColorSpace.sRGB),+ let context = CGContext(+ data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: space,+ bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue+ ) else { return nil }+ context.setFillColor(color(tab.background) ?? CGColor(gray: 0, alpha: 1))+ context.fill(CGRect(x: 0, y: 0, width: width, height: height))++ let unit = TerminalFaces.font(face, size: 100)+ let advance = max(Self.advance(of: unit) / 100, 0.3)+ let line = max((CTFontGetAscent(unit) + CTFontGetDescent(unit) + CTFontGetLeading(unit)) / 100, 1)+ // A cell's width: the tab's columns across, or its rows down,+ // whichever runs out first.+ let cell = min(CGFloat(width) / CGFloat(tab.cols), CGFloat(height) / CGFloat(tab.rows) / line * advance)+ let font = TerminalFaces.font(face, size: cell / advance)+ let rowHeight = cell / advance * line+ let ascent = CTFontGetAscent(font)+ // The rows go down from the top; CoreGraphics counts up.+ let top = { (row: Int) in CGFloat(height) - CGFloat(row) * rowHeight }++ for pane in tab.panes {+ let screen = pane.screen+ let x0 = CGFloat(pane.left) * cell+ let area = CGRect(x: x0, y: top(pane.top + screen.rows), width: CGFloat(screen.cols) * cell, height: CGFloat(screen.rows) * rowHeight)+ // Nothing of a pane past its own place: a line longer than it,+ // or one wider since its place was listed, stops at its edge.+ context.saveGState()+ defer { context.restoreGState() }+ context.clip(to: area)+ if screen.background != tab.background, let back = color(screen.background) {+ context.setFillColor(back)+ context.fill(area)+ }+ let foreground = color(screen.foreground) ?? CGColor(gray: 1, alpha: 1)+ for (row, runs) in screen.lines.enumerated() {+ let y = top(pane.top + row)+ for run in runs {+ let x = x0 + CGFloat(run.col) * cell+ if let back = color(run.bg) {+ context.setFillColor(back)+ context.fill(CGRect(x: x, y: y - rowHeight, width: CGFloat(run.width) * cell, height: rowHeight))+ }+ guard !run.text.allSatisfy({ $0 == " " }) else { continue }+ draw(run, font: font, color: color(run.fg) ?? foreground, at: CGPoint(x: x, y: y - ascent), cell: cell, in: context)+ }+ }+ }+ dividers(of: tab, cell: cell, rowHeight: rowHeight, top: top, in: context)+ return context.makeImage()+ }++ /// The splits: a hairline down or across the middle of the cells+ /// between one pane and the next, as the terminal draws them.+ private static func dividers(of tab: TabPreview, cell: CGFloat, rowHeight: CGFloat, top: (Int) -> CGFloat, in context: CGContext) {+ guard tab.panes.count > 1 else { return }+ context.setFillColor((color(tab.foreground) ?? CGColor(gray: 1, alpha: 1)).copy(alpha: 0.3) ?? CGColor(gray: 0.5, alpha: 1))+ let thickness = max(1, cell / 8)+ for pane in tab.panes {+ let (cols, rows) = (pane.screen.cols, pane.screen.rows)+ if pane.left + cols < tab.cols {+ let x = (CGFloat(pane.left + cols) + 0.5) * cell - thickness / 2+ context.fill(CGRect(x: x, y: top(pane.top + rows), width: thickness, height: CGFloat(rows) * rowHeight))+ }+ if pane.top + rows < tab.rows {+ let y = top(pane.top + rows) - rowHeight / 2 - thickness / 2+ context.fill(CGRect(x: CGFloat(pane.left) * cell, y: y, width: CGFloat(cols) * cell, height: thickness))+ }+ }+ }++ /// A run from its baseline at `origin`: as one line when it is letters+ /// of the face, each a cell wide, or one wide character; else each+ /// character at its own cell, so one another face draws (an icon, a+ /// box's line) at its own width moves none of the rest off its column.+ private static func draw(_ run: ScreenRun, font: CTFont, color: CGColor, at origin: CGPoint, cell: CGFloat, in context: CGContext) {+ let text = NSAttributedString(string: run.text, attributes: [+ NSAttributedString.Key(kCTFontAttributeName as String): font,+ NSAttributedString.Key(kCTForegroundColorAttributeName as String): color,+ ])+ let line = CTLineCreateWithAttributedString(text)+ // A character as the terminal has one, a cell's: a letter and its+ // marks, a flag's two halves.+ guard !run.text.allSatisfy(\.isASCII), run.text.count == run.width else {+ context.textPosition = origin+ CTLineDraw(line, context)+ return+ }+ // The cell of each UTF-16 offset in the text: a character a cell.+ var cells: [Int] = []+ for (index, character) in run.text.enumerated() {+ cells.append(contentsOf: repeatElement(index, count: character.utf16.count))+ }+ // Where the line put each cell's first glyph: its marks keep their+ // places beside it.+ var firsts: [Int: CGFloat] = [:]+ context.setFillColor(color)+ // The glyphs' places are the context's own: none of the text+ // position a line drawn before left behind.+ context.textPosition = .zero+ for glyphs in CTLineGetGlyphRuns(line) as? [CTRun] ?? [] {+ let count = CTRunGetGlyphCount(glyphs)+ guard count > 0 else { continue }+ var ids = [CGGlyph](repeating: 0, count: count)+ var offsets = [CFIndex](repeating: 0, count: count)+ var places = [CGPoint](repeating: .zero, count: count)+ CTRunGetGlyphs(glyphs, CFRange(location: 0, length: count), &ids)+ CTRunGetStringIndices(glyphs, CFRange(location: 0, length: count), &offsets)+ CTRunGetPositions(glyphs, CFRange(location: 0, length: count), &places)+ let positions = zip(offsets, places).map { offset, place in+ let at = cells[min(max(offset, 0), cells.count - 1)]+ let first = firsts[at] ?? place.x+ firsts[at] = first+ return CGPoint(x: origin.x + CGFloat(at) * cell + place.x - first, y: origin.y + place.y)+ }+ // The face the line fell back to for these, if not the terminal's.+ let attributes = CTRunGetAttributes(glyphs) as NSDictionary+ let face = attributes[kCTFontAttributeName as String].map { $0 as! CTFont } ?? font+ CTFontDrawGlyphs(face, ids, positions, count, context)+ }+ }++ /// The face's width for one cell, at its size.+ private static func advance(of font: CTFont) -> CGFloat {+ var glyph = CGGlyph()+ var character = UniChar(("M" as Unicode.Scalar).value)+ guard CTFontGetGlyphsForCharacters(font, &character, &glyph, 1) else { return CTFontGetSize(font) * 0.6 }+ return CTFontGetAdvancesForGlyphs(font, .horizontal, &glyph, nil, 1)+ }++ /// "#rrggbb" as a colour; anything else, none.+ private static func color(_ hex: String) -> CGColor? {+ guard hex.count == 7, hex.hasPrefix("#"), let value = UInt32(hex.dropFirst(), radix: 16) else { return nil }+ return CGColor(+ srgbRed: CGFloat((value >> 16) & 0xff) / 255,+ green: CGFloat((value >> 8) & 0xff) / 255,+ blue: CGFloat(value & 0xff) / 255,+ alpha: 1+ )+ }+}++/// The terminal's faces, which the core reads from the app's files, made+/// known to CoreText too, for the pictures of screens; the icons' face+/// after either, as the core falls back to it.+enum TerminalFaces {+ private static let symbols: [CTFontDescriptor] = {+ for name in ["JetBrainsMono-Regular", "FiraCode-Regular", "SymbolsNerdFontMono-Regular"] {+ if let url = Bundle.main.url(forResource: name, withExtension: "ttf") {+ CTFontManagerRegisterFontsForURL(url as CFURL, .process, nil)+ }+ }+ guard let url = Bundle.main.url(forResource: "SymbolsNerdFontMono-Regular", withExtension: "ttf") else { return [] }+ return CTFontManagerCreateFontDescriptorsFromURL(url as CFURL) as? [CTFontDescriptor] ?? []+ }()++ /// `face`, by its PostScript name, at `size`; what it lacks is looked+ /// for in the icons' face before the system's.+ static func font(_ face: String, size: CGFloat) -> CTFont {+ let descriptor = CTFontDescriptorCreateWithAttributes([+ kCTFontNameAttribute: face,+ kCTFontCascadeListAttribute: symbols,+ ] as CFDictionary)+ return CTFontCreateWithFontDescriptor(descriptor, size, nil)+ }+}++/// A picture of the terminal flown between the screen and a card by Core+/// Animation, which the render server runs: a main thread busy making or+/// laying out the cards does not stop it. It flies over the screen's+/// content (`Flyway`), laid out where the terminal is and moved by its+/// transform, over a cover that hides the content while the cards come+/// and go under it.+final class Flight {+ fileprivate weak var stage: UIView?+ private var picture: UIView?+ private var cover: UIView?+ private var frame: CGRect = .zero+ /// Counts the moves: the end of one overtaken is not this one's.+ private var turn = 0++ var flying: Bool { picture != nil }++ /// What the screen shows over `rect` (in the stage's space) now, as a+ /// view: the terminal as drawn, before it is hidden.+ func snapshot(_ rect: CGRect) -> UIView? {+ guard let stage, let window = stage.window, rect.width > 0, rect.height > 0 else { return nil }+ return window.resizableSnapshotView(from: stage.convert(rect, to: window), afterScreenUpdates: false, withCapInsets: .zero)+ }++ /// The screen's content under `color`, at `alpha`.+ func cover(_ color: UIColor, alpha: CGFloat) {+ guard let stage else { return }+ let view: UIView+ if let cover {+ view = cover+ } else {+ view = UIView(frame: stage.bounds)+ view.autoresizingMask = [.flexibleWidth, .flexibleHeight]+ view.isUserInteractionEnabled = false+ stage.insertSubview(view, at: 0)+ cover = view+ }+ view.backgroundColor = color+ view.alpha = alpha+ }++ func fadeCover(to alpha: CGFloat, duration: TimeInterval) {+ guard let cover else { return }+ UIView.animate(withDuration: duration, delay: 0, options: [.beginFromCurrentState, .curveEaseOut]) {+ cover.alpha = alpha+ }+ }++ /// `view`, laid out over `frame`, shown over `rect` straight away, over+ /// the cover.+ func begin(with view: UIView, frame: CGRect, at rect: CGRect, radius: CGFloat) {+ turn += 1+ picture?.removeFromSuperview()+ guard let stage else { return }+ view.frame = frame+ view.isUserInteractionEnabled = false+ view.layer.masksToBounds = true+ view.layer.cornerCurve = .continuous+ self.frame = frame+ place(view, at: rect, radius: radius)+ stage.addSubview(view)+ picture = view+ }++ /// To `rect`, rounded to `radius` there, in a spring; `done` once it+ /// is there and no later move has taken over.+ func move(to rect: CGRect, radius: CGFloat, duration: TimeInterval, done: @escaping () -> Void) {+ guard let picture else { return done() }+ turn += 1+ let mine = turn+ UIView.animate(springDuration: duration, bounce: 0, options: [.beginFromCurrentState]) {+ self.place(picture, at: rect, radius: radius)+ } completion: { _ in+ if mine == self.turn { done() }+ }+ }++ /// The picture and the cover gone in a fade, showing what is under them.+ func fadeOut(duration: TimeInterval, done: @escaping () -> Void) {+ guard picture != nil || cover != nil else { return done() }+ turn += 1+ let mine = turn+ let (picture, cover) = (self.picture, self.cover)+ UIView.animate(withDuration: duration, delay: 0, options: [.beginFromCurrentState, .curveEaseOut]) {+ picture?.alpha = 0+ cover?.alpha = 0+ } completion: { _ in+ guard mine == self.turn else { return }+ self.end()+ done()+ }+ }++ func end() {+ turn += 1+ picture?.removeFromSuperview()+ cover?.removeFromSuperview()+ picture = nil+ cover = nil+ }++ /// Scaled about its middle from `frame` to `rect`'s width and moved+ /// onto it; the corners' radius in the view's own points.+ private func place(_ view: UIView, at rect: CGRect, radius: CGFloat) {+ let scale = rect.width / max(frame.width, 1)+ view.transform = CGAffineTransform(translationX: rect.midX - frame.midX, y: rect.midY - frame.midY)+ .scaledBy(x: scale, y: scale)+ view.layer.cornerRadius = radius / max(scale, 0.01)+ }+}++/// Where a `Flight` flies: a clear view over the screen's content, every+/// touch going through it.+struct Flyway: UIViewRepresentable {+ let flight: Flight++ func makeUIView(context: Context) -> UIView {+ let view = PassThrough()+ view.backgroundColor = .clear+ flight.stage = view+ return view+ }++ func updateUIView(_ view: UIView, context: Context) {+ flight.stage = view+ }++ private final class PassThrough: UIView {+ override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { nil }+ }+}diff --git a/ios/Sources/SettingsSheet.swift b/ios/Sources/SettingsSheet.swiftindex f0f23aad..daaebe31 100644--- a/ios/Sources/SettingsSheet.swift+++ b/ios/Sources/SettingsSheet.swift@@ -1,12 +1,11 @@import SwiftUI/// The app's preferences, in the prototype's eight sections. The Settings-/// tab shows it with no terminal; a terminal's menu shows it with one,-/// and then the text size is the live pane's and the log is offered.+/// tab and a terminal's menu show the same page; from a terminal it also+/// offers the log. Every open terminal follows a change at once.struct SettingsView: View {@ObservedObject var settings = AppSettings.shared@ObservedObject private var lang = AppLanguage.shared- var model: TerminalModel?var showLog: Binding<Bool>?var body: some View {@@ -28,17 +27,15 @@ struct SettingsView: View {.lineLimit(1)}}- if let model {- LiveTextSize(model: model)- } else {- Stepper(value: $settings.fontSize, in: 6...40, step: 1) {- HStack {- Text(tr("textsize"))- Spacer()- Text(String(format: "%.0f pt", settings.fontSize))- .foregroundColor(.secondary)- .monospacedDigit()- }+ // The same here and in a terminal's settings: every open+ // terminal takes the size live, and a new connection starts at it.+ Stepper(value: $settings.fontSize, in: 6...40, step: 1) {+ HStack {+ Text(tr("textsize"))+ Spacer()+ Text(String(format: "%.0f pt", settings.fontSize))+ .foregroundColor(.secondary)+ .monospacedDigit()}}push(tr("font.family"), selection: $settings.fontFamily, options: Self.fonts)@@ -55,8 +52,6 @@ struct SettingsView: View {}Section(tr("sec.interface")) {- segment(tr("i.tabbar"), selection: $settings.tabBarLevels,- ("one", tr("i.onelevel")), ("two", tr("i.twolevel")))Toggle(tr("i.panebars"), isOn: $settings.paneBars)}@@ -267,33 +262,6 @@ struct KeyBarKeys: View {}}-/// The open terminal's text size, stepped live; the size a new-/// connection starts at follows it.-private struct LiveTextSize: View {- @ObservedObject var model: TerminalModel- @ObservedObject var settings = AppSettings.shared- @ObservedObject private var lang = AppLanguage.shared-- var body: some View {- HStack {- Text(tr("textsize"))- Spacer()- Button { step(-1) } label: { Image(systemName: "textformat.size.smaller") }- .buttonStyle(.bordered)- Text(String(format: "%.1f pt", model.fontPt))- .font(.callout.monospacedDigit())- .frame(minWidth: 56)- Button { step(1) } label: { Image(systemName: "textformat.size.larger") }- .buttonStyle(.bordered)- }- }-- private func step(_ by: Double) {- model.stepFont(by)- settings.fontSize = max(6, min(40, (model.fontPt * (1 + 0.1 * by)).rounded()))- }-}-/// The colour schemes by name, searchable, each with its background as a/// swatch; the host's own scheme first.struct ThemePicker: View {diff --git a/ios/Sources/Sidebar.swift b/ios/Sources/Sidebar.swiftindex fbb31c06..3887ba54 100644--- a/ios/Sources/Sidebar.swift+++ b/ios/Sources/Sidebar.swift@@ -1,22 +1,36 @@import SwiftUI-/// The desktop's sidebar, as the TUI lays it out: a panel from the left-/// with the tree — the host, its Spaces, their projects, their threads —-/// each level folding, New Thread at the top, Settings at the bottom.-/// Everything is named as the desktop names it.+/// The desktop's sidebar, as the TUI lays it out -- the host, its Spaces,+/// their projects, their threads -- drawn the system's way: large rows+/// with line icons, section titles, a rounded fill on the thread on show.+/// On a phone held upright it is the drawer the screen slides off; on a+/// wide screen it stays at the left. Everything is named as the desktop+/// names it.struct SidebarPanel: View {@ObservedObject var model: TerminalModel@ObservedObject private var lang = AppLanguage.shared- @Binding var isPresented: Boolvar hostName: Stringvar connected: Bool+ /// Something was picked: a drawer closes, a column stays.+ var done: () -> Voidvar onEditHost: () -> Voidvar onSettings: () -> Voidvar onOverview: () -> Void+ /// The overview is up: its row is lit.+ var overviewOn = false+ /// Someone sees it: a drawer shut under the screen makes no rows, and+ /// keeps its folds and search for when it opens.+ var live = true/// Folded nodes; every Space but the one on show starts folded.@State private var folded: Set<String>?- @State private var renaming: (kind: String, id: String)?- @State private var renameText = ""+ @State private var searching = false+ @State private var search = ThreadSearch()+ /// Where the system puts bars along the top and bottom (`barRoom`):+ /// on some screens further in than the safe area's edges.+ @State private var headerRoom = EdgeInsets()+ @State private var footerRoom = EdgeInsets()++ private var spaces: [TreeSpace] { model.tree?.spaces ?? [] }private var connectionColor: Color {if model.reconnecting { return .orange }@@ -25,206 +39,308 @@ struct SidebarPanel: View {return .red}+ private static let backdrop = Color(white: 0.07)+ /// The header's row and the footer's, their padding included.+ private static let headerHeight: CGFloat = 60+ private static let footerHeight: CGFloat = 64+var body: some View {- ZStack(alignment: .leading) {- if isPresented {- Color.black.opacity(0.45)- .ignoresSafeArea()- .onTapGesture { isPresented = false }- .transition(.opacity)- panel- .frame(width: 300)- .background(Color(white: 0.09))- .ignoresSafeArea(edges: .bottom)- .transition(.move(edge: .leading))+ Group {+ if live { list } else { Color.clear }+ }+ .foregroundColor(.white)+ .background(Self.backdrop.ignoresSafeArea())+ .onChange(of: spaces.isEmpty, initial: true) { _, empty in+ // Once the tree is in: the panel is made before it arrives.+ if folded == nil, !empty {+ folded = Set(spaces.filter { !$0.current }.map { "space:" + $0.id })}}- .animation(.easeOut(duration: 0.22), value: isPresented)- .onChange(of: isPresented) { _, shown in- if shown {- model.refreshViews()- if folded == nil {- folded = Set((model.tree?.spaces ?? []).filter { !$0.current }.map { "space:" + $0.id })+ }++ /// The list runs the panel's full height, under the host at the top+ /// and the buttons at the bottom, fading as it goes.+ private var list: some View {+ ScrollView {+ LazyVStack(alignment: .leading, spacing: 2) {+ if searching {+ ThreadSearchResults(search: search, spaces: spaces) { space, thread in+ unfold("space:" + space.id)+ model.openThread(thread.id, space: space.id)+ searching = false+ search.query = ""+ done()+ }+ } else {+ tree}}+ .padding(.horizontal, 10)+ .padding(.bottom, 12)}- .onChange(of: model.sidebar?.editing) { _, editing in- // A new project has no id yet: the same field, asking for the- // name of what is about to exist.- guard let editing, editing.kind != "none" else { return }- if renaming == nil {- renameText = ""- renaming = (editing.kind, editing.id ?? "")+ .scrollDismissesKeyboard(.immediately)+ .floatingBar(edge: .top, fading: Self.backdrop, scrim: true) {+ VStack(spacing: 0) {+ header+ if searching { searchField }}}- .alert(- renaming?.kind == "new-project" ? tr("project.new") : tr("rename"),- isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })- ) {- TextField(tr("f.name"), text: $renameText)- Button(tr("save")) {- model.sideKey("Enter", value: renameText)- renaming = nil- }- Button(tr("cancel"), role: .cancel) {- model.sideKey("Escape", value: "")- renaming = nil- }+ .floatingBar(edge: .bottom, fading: Self.backdrop) {+ if !searching { footer }}+ .barRoom(.top, height: Self.headerHeight, $headerRoom)+ .barRoom(.bottom, height: Self.footerHeight, $footerRoom)}- private func isFolded(_ key: String) -> Bool { folded?.contains(key) ?? false }+ // MARK: the top- private func toggle(_ key: String) {- var set = folded ?? []- if set.contains(key) { set.remove(key) } else { set.insert(key) }- folded = set- }-- private var panel: some View {- VStack(spacing: 0) {- ScrollView {- VStack(alignment: .leading, spacing: 0) {- // The host: the root of the tree, and the connection's actions.- Menu {- Button(connected ? tr("disconnect") : tr("reconnect")) {- if connected { model.disconnect() } else { model.connect() }- }- if model.host != nil {- Button(tr("edithost")) { onEditHost() }- }- } label: {- treeRow(depth: 0, expandable: true, collapsed: isFolded("host"), onToggle: { toggle("host") }) {- Circle().fill(connectionColor).frame(width: 8, height: 8)- Text(hostName).fontWeight(.semibold).lineLimit(1)- Spacer(minLength: 0)- Image(systemName: "ellipsis").foregroundColor(.secondary)- }- }- .buttonStyle(.plain)-- if !isFolded("host") {- Button {- model.sideClick("new-thread")- isPresented = false- } label: {- Label(tr("thread.new"), systemImage: "plus")- .foregroundColor(.accentColor)- .padding(.horizontal, 16)- .padding(.vertical, 10)- }- .buttonStyle(.plain)-- HStack {- Text(tr("workspaces").uppercased()).font(.caption2).foregroundColor(.secondary)- Spacer()- Button { model.sideClick("new-project") } label: {- Image(systemName: "plus").font(.caption).foregroundColor(.secondary).frame(width: 28, height: 28)- }- .buttonStyle(.plain)- }- .padding(.leading, 16)- .padding(.trailing, 4)-- ForEach(model.tree?.spaces ?? []) { space in- spaceRows(space)- }- tailRows- if let error = model.sidebar?.new_project_error {- Text(error).font(.caption).foregroundColor(.red).padding(.horizontal, 16).padding(.vertical, 8)- }- }+ /// The host -- the tree's root and the connection's menu -- and the+ /// search button.+ private var header: some View {+ HStack(spacing: 10) {+ Menu {+ Button(connected ? tr("disconnect") : tr("reconnect")) {+ if connected { model.disconnect() } else { model.connect() }+ }+ if model.host != nil {+ Button(tr("edithost")) { onEditHost() }+ }+ } label: {+ HStack(spacing: 8) {+ Text(hostName)+ .font(.title2.weight(.bold))+ .lineLimit(1)+ Circle().fill(connectionColor).frame(width: 8, height: 8)}- .padding(.top, 8)}- Divider()- Button(action: onOverview) {- Label(tr("overview"), systemImage: "square.grid.2x2")- .foregroundColor(.secondary)- .frame(maxWidth: .infinity, alignment: .leading)- .padding(.horizontal, 16)- .padding(.vertical, 12)+ .buttonStyle(.plain)+ Spacer(minLength: 0)+ Button {+ withAnimation(.easeOut(duration: 0.2)) {+ searching.toggle()+ if !searching { search.query = "" }+ }+ // The field takes the keyboard as it comes up, not each+ // time the panel makes it again.+ search.focusNext = searching+ } label: {+ Image(systemName: searching ? "xmark" : "magnifyingglass")+ .font(.body.weight(.medium))+ .frame(width: 44, height: 44)+ .contentShape(Circle())}.buttonStyle(.plain)- Button(action: onSettings) {- Label(tr("settings"), systemImage: "gearshape")- .foregroundColor(.secondary)- .frame(maxWidth: .infinity, alignment: .leading)- .padding(.horizontal, 16)- .padding(.vertical, 12)+ .glassCircle()+ .accessibilityLabel(tr(searching ? "cancel" : "thread.find"))+ }+ .padding(.leading, max(20, headerRoom.leading))+ .padding(.trailing, 14)+ .padding(.top, 6 + max(0, headerRoom.top))+ .padding(.bottom, 10)+ }++ private var searchField: some View {+ HStack(spacing: 8) {+ Image(systemName: "magnifyingglass").foregroundColor(.secondary)+ SearchField(search: search, prompt: tr("thread.find"))+ }+ .padding(.horizontal, 14)+ .frame(height: 40)+ .glassCapsule()+ .padding(.horizontal, 14)+ .padding(.bottom, 8)+ .transition(.move(edge: .top).combined(with: .opacity))+ }++ // MARK: the bottom++ /// A new thread, where the thumb is, and the settings, floating over+ /// the end of the list. Searching puts them away.+ private var footer: some View {+ HStack(spacing: 12) {+ Button {+ model.sideClick("new-thread")+ done()+ } label: {+ Label(tr("thread.new"), systemImage: "square.and.pencil")+ .font(.body.weight(.semibold))+ .lineLimit(1)+ .minimumScaleFactor(0.8)+ .padding(.horizontal, 18)+ .frame(height: 50)+ .contentShape(Capsule())}.buttonStyle(.plain)+ .glassCapsule(tint: .accentColor)+ Spacer(minLength: 0)+ Button { done(); onSettings() } label: {+ Image(systemName: "gearshape")+ .font(.title3)+ .frame(width: 50, height: 50)+ .contentShape(Circle())+ }+ .buttonStyle(.plain)+ .glassCircle()+ .accessibilityLabel(tr("settings"))}- .foregroundColor(.white)+ .dynamicTypeSize(...DynamicTypeSize.xxLarge)+ .padding(.leading, max(14, footerRoom.leading))+ .padding(.trailing, 14)+ .padding(.top, 6)+ // Below the safe area's edge where the system's bars go there.+ .padding(.bottom, 8 + footerRoom.bottom)}+ // MARK: the tree+@ViewBuilder- private func spaceRows(_ space: TreeSpace) -> some View {- let key = "space:" + space.id- treeRow(depth: 1, expandable: !space.projects.isEmpty, collapsed: isFolded(key), onToggle: { toggle(key) }) {- Text(space.name).fontWeight(space.current ? .semibold : .regular).lineLimit(1)- Spacer(minLength: 0)+ private var tree: some View {+ // The screen shuts the drawer itself, and waits for it.+ SidebarRow(icon: "square.grid.2x2", title: tr("overview"), selected: overviewOn) { onOverview() }++ // The Space on show's, as the desktop pins them; they leave their+ // projects' lists.+ let pinned = spaces.filter(\.current).flatMap { space in+ space.projects.flatMap { project in+ project.threads.filter(\.pinned).map { (space: space, project: project, thread: $0) }+ }+ }+ if !pinned.isEmpty {+ sectionTitle(tr("pinned"))+ ForEach(pinned, id: \.thread.id) { entry in+ threadRow(entry.thread, space: entry.space, depth: 0, subtitle: entry.project.name)+ }+ }++ HStack {+ sectionTitle(tr("workspaces"))+ Spacer()Button {- model.setSpace(space.id)model.sideClick("new-project")+ model.askName()} label: {- Image(systemName: "plus").font(.caption).foregroundColor(.secondary).frame(width: 28, height: 28)+ Image(systemName: "plus")+ .font(.subheadline.weight(.medium))+ .foregroundColor(.secondary)+ .frame(width: 36, height: 36)+ .contentShape(Rectangle())}.buttonStyle(.plain)+ .accessibilityLabel(tr("project.new"))}.contentShape(Rectangle())- .onTapGesture {- if !space.current { model.setSpace(space.id) }- if isFolded(key) { toggle(key) }+ // A lone Space has no row (below): its menu -- a new Space, a new+ // name -- is held here.+ .contextMenu {+ if spaces.count == 1 { AppMenuItems(model: model, kind: "space", id: "") }}- .contextMenu { AppMenuItems(model: model, kind: "space", id: "") }- if !isFolded(key) {- ForEach(space.projects) { project in- projectRows(space, project)- }+ // One Space needs no row of its own: its projects stand at the top.+ if spaces.count == 1, let space = spaces.first {+ ForEach(space.projects) { project in projectRows(space, project, depth: 0) }+ } else {+ ForEach(spaces) { space in spaceRows(space) }+ }+ tailRows+ if let error = model.sidebar?.new_project_error {+ Text(error).font(.footnote).foregroundColor(.red).padding(.horizontal, 12).padding(.vertical, 8)}}+ private func sectionTitle(_ text: String) -> some View {+ Text(text)+ .font(.subheadline)+ .foregroundColor(.secondary)+ .padding(.horizontal, 12)+ .padding(.top, 16)+ .padding(.bottom, 2)+ }++ private func isFolded(_ key: String) -> Bool { folded?.contains(key) ?? false }++ private func toggle(_ key: String) {+ var set = folded ?? []+ if set.contains(key) { set.remove(key) } else { set.insert(key) }+ withAnimation(.easeOut(duration: 0.18)) { folded = set }+ }++ private func unfold(_ key: String) {+ guard isFolded(key) else { return }+ toggle(key)+ }+@ViewBuilder- private func projectRows(_ space: TreeSpace, _ project: TreeProject) -> some View {- let key = "project:" + project.id- treeRow(depth: 2, expandable: !project.threads.isEmpty, collapsed: isFolded(key), onToggle: { toggle(key) }) {- Text(project.name).lineLimit(1)- Spacer(minLength: 0)- Button {+ private func spaceRows(_ space: TreeSpace) -> some View {+ let key = "space:" + space.id+ SidebarRow(+ icon: "square.stack.3d.up",+ title: space.name,+ bold: space.current,+ chevron: space.projects.isEmpty ? nil : !isFolded(key)+ ) {+ // Another Space is gone to, open; the one on show folds.+ if space.current {+ toggle(key)+ } else {model.setSpace(space.id)- model.sideClick("new-thread", id: project.id)- } label: {- Image(systemName: "plus").font(.caption).foregroundColor(.secondary).frame(width: 28, height: 28)+ unfold(key)}- .buttonStyle(.plain)}- .contentShape(Rectangle())- .onTapGesture { toggle(key) }- .contextMenu { AppMenuItems(model: model, kind: "project", id: project.id) }+ .contextMenu { AppMenuItems(model: model, kind: "space", id: "") }if !isFolded(key) {- ForEach(project.threads) { thread in- treeRow(depth: 3, expandable: false, collapsed: false, selected: thread.selected, onToggle: {}) {- Circle().fill(TerminalScreen.threadColor(status: thread.status, live: thread.live)).frame(width: 8, height: 8)- if thread.pinned {- Image(systemName: "star.fill").font(.system(size: 9)).foregroundColor(.secondary)- }- Text(thread.name)- .fontWeight(thread.unread || thread.selected ? .semibold : .regular)- .foregroundColor(thread.live ? .white : .secondary)- .lineLimit(1)- Spacer(minLength: 0)- }- .contentShape(Rectangle())- .onTapGesture {- model.openThread(thread.id, space: space.id)- isPresented = false+ ForEach(space.projects) { project in projectRows(space, project, depth: 1) }+ }+ }++ @ViewBuilder+ private func projectRows(_ space: TreeSpace, _ project: TreeProject, depth: Int) -> some View {+ let key = "project:" + project.id+ // Pinned threads have their own rows, the Space on show's only.+ let threads = space.current ? project.threads.filter { !$0.pinned } : project.threads+ SidebarRow(+ icon: "folder",+ title: project.name,+ depth: depth,+ chevron: threads.isEmpty ? nil : !isFolded(key),+ trailing: AnyView(+ Button {+ model.setSpace(space.id)+ model.sideClick("new-thread", id: project.id)+ done()+ } label: {+ Image(systemName: "plus")+ .font(.subheadline)+ .foregroundColor(.secondary)+ .frame(width: 32, height: 32)+ .contentShape(Rectangle())}- .contextMenu { AppMenuItems(model: model, kind: "thread", id: thread.id) }+ .buttonStyle(.plain)+ .accessibilityLabel(tr("thread.new"))+ )+ ) { toggle(key) }+ .contextMenu { AppMenuItems(model: model, kind: "project", id: project.id) }+ if !isFolded(key) {+ ForEach(threads) { thread in+ threadRow(thread, space: space, depth: depth + 1)}}}+ private func threadRow(_ thread: ThreadRow, space: TreeSpace, depth: Int, subtitle: String? = nil) -> some View {+ SidebarRow(+ mark: AnyView(ThreadMark(status: thread.status, dot: thread.dot, size: 9)),+ title: thread.name,+ subtitle: subtitle,+ depth: depth,+ bold: thread.unread,+ dim: !thread.live,+ selected: thread.selected+ ) {+ model.openThread(thread.id, space: space.id)+ done()+ }+ .contextMenu { AppMenuItems(model: model, kind: "thread", id: thread.id) }+ }+/// What the desktop lists after the tree: archived projects of the/// Space on show, and windows no thread claims.@ViewBuilder@@ -237,77 +353,397 @@ struct SidebarPanel: View {}))ForEach(tail) { row inswitch row {- case .archived(let count, let open, let label):- Button { model.sideClick("toggle-archived", flag: !open) } label: {- HStack(spacing: 6) {- Image(systemName: "chevron.right").rotationEffect(.degrees(open ? 90 : 0)).font(.caption)- Text("\(label) (\(count))")- }- .font(.footnote)- .foregroundColor(.secondary)- .padding(.leading, 16)- .padding(.vertical, 6)+ case .archived(_, let open, let label):+ // The label carries the count.+ SidebarRow(icon: "archivebox", title: label, dim: true, chevron: open) {+ model.sideClick("toggle-archived", flag: !open)}- .buttonStyle(.plain)case .project(let id, let name, _, _, true):- treeRow(depth: 2, expandable: false, collapsed: true, onToggle: {}) {- Text(name).foregroundColor(.secondary).lineLimit(1)- Spacer(minLength: 0)- }- .contextMenu { AppMenuItems(model: model, kind: "archived-project", id: id) }+ SidebarRow(icon: "folder", title: name, depth: 1, dim: true) {}+ .contextMenu { AppMenuItems(model: model, kind: "archived-project", id: id) }case .others:- Text(tr("otherwindows").uppercased()).font(.caption2).foregroundColor(.secondary)- .padding(.leading, 16).padding(.top, 10).padding(.bottom, 2)+ sectionTitle(tr("otherwindows"))case .window(let id, let title, let selected):- Button {+ SidebarRow(icon: "macwindow", title: title.isEmpty ? tr("window.n", id) : title, selected: selected) {model.sideClick("window", id: String(id))- isPresented = false- } label: {- HStack(spacing: 8) {- Image(systemName: "macwindow").foregroundColor(.secondary)- Text(title.isEmpty ? tr("window.n", id) : title).lineLimit(1)- Spacer(minLength: 0)- }- .padding(.horizontal, 16)- .padding(.vertical, 8)- .background(selected ? Color.accentColor.opacity(0.18) : Color.clear)+ done()}- .buttonStyle(.plain)default:EmptyView()}}}+}- /// One row of the tree: indented by its depth, a fold chevron when it- /// has children, and its content.- private func treeRow<Content: View>(- depth: Int,- expandable: Bool,- collapsed: Bool,- selected: Bool = false,- onToggle: @escaping () -> Void,- @ViewBuilder content: () -> Content- ) -> some View {- HStack(spacing: 8) {- if expandable {- Button(action: onToggle) {- Image(systemName: "chevron.down")- .font(.caption)- .foregroundColor(.secondary)- .rotationEffect(.degrees(collapsed ? -90 : 0))- .frame(width: 20, height: 20)+// MARK: finding a thread++/// What the sidebar's search looks for, apart from the panel: only the+/// field and the results read it, so typing redraws them and not the+/// panel round them (its bars, their glass).+@Observable final class ThreadSearch {+ var query = ""+ /// The field takes the keyboard as it comes up next.+ @ObservationIgnored var focusNext = false+}++/// Every thread whose name holds the query, wherever it is, with the+/// project it is in.+private struct ThreadSearchResults: View {+ let search: ThreadSearch+ let spaces: [TreeSpace]+ let pick: (TreeSpace, ThreadRow) -> Void++ var body: some View {+ let needle = search.query.trimmingCharacters(in: .whitespaces)+ let found = spaces.flatMap { space in+ space.projects.flatMap { project in+ project.threads+ .filter { needle.isEmpty || $0.name.localizedCaseInsensitiveContains(needle) }+ .map { (space: space, project: project, thread: $0) }+ }+ }+ if found.isEmpty {+ Text(tr("thread.find.none"))+ .font(.subheadline)+ .foregroundColor(.secondary)+ .padding(12)+ }+ ForEach(found, id: \.thread.id) { entry in+ SidebarRow(+ mark: AnyView(ThreadMark(status: entry.thread.status, dot: entry.thread.dot, size: 9)),+ title: entry.thread.name,+ subtitle: entry.project.name,+ selected: entry.thread.selected+ ) {+ pick(entry.space, entry.thread)+ }+ }+ }+}++/// The search's field as UIKit has it, which tells when a word is still+/// being put together -- pinyin before its characters are picked: the+/// query waits for the characters, as no thread is named in the letters.+private struct SearchField: UIViewRepresentable {+ let search: ThreadSearch+ let prompt: String++ func makeCoordinator() -> Coordinator { Coordinator(search: search) }++ func makeUIView(context: Context) -> UITextField {+ let field = UITextField()+ // What it held when the panel last made it (a drawer shut and+ // opened again).+ field.text = search.query+ field.attributedPlaceholder = NSAttributedString(string: prompt, attributes: [.foregroundColor: UIColor.placeholderText])+ field.font = .preferredFont(forTextStyle: .body)+ field.adjustsFontForContentSizeCategory = true+ field.maximumContentSizeCategory = .extraExtraLarge+ field.textColor = .white+ field.autocapitalizationType = .none+ field.autocorrectionType = .no+ field.spellCheckingType = .no+ field.returnKeyType = .search+ field.delegate = context.coordinator+ field.addTarget(context.coordinator, action: #selector(Coordinator.edited(_:)), for: .editingChanged)+ field.setContentHuggingPriority(.defaultLow, for: .horizontal)+ field.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)+ DispatchQueue.main.async {+ if search.focusNext {+ search.focusNext = false+ field.becomeFirstResponder()+ }+ }+ return field+ }++ func updateUIView(_ field: UITextField, context: Context) {+ context.coordinator.search = search+ }++ final class Coordinator: NSObject, UITextFieldDelegate {+ var search: ThreadSearch++ init(search: ThreadSearch) { self.search = search }++ @objc func edited(_ field: UITextField) {+ guard field.markedTextRange == nil else { return }+ search.query = field.text ?? ""+ }++ func textFieldShouldReturn(_ field: UITextField) -> Bool {+ field.resignFirstResponder()+ return true+ }+ }+}++/// One row of the sidebar: an icon or a status mark, the title, an+/// optional fold chevron and trailing button; a rounded fill when it is+/// the one on show. Its text follows the system's size.+private struct SidebarRow: View {+ var icon: String?+ var mark: AnyView?+ var title: String+ var subtitle: String?+ var depth = 0+ var bold = false+ var dim = false+ var selected = false+ /// Unfolded (true), folded (false), or nothing to fold (nil).+ var chevron: Bool?+ var trailing: AnyView?+ var action: () -> Void++ init(+ icon: String? = nil, mark: AnyView? = nil, title: String, subtitle: String? = nil,+ depth: Int = 0, bold: Bool = false, dim: Bool = false, selected: Bool = false,+ chevron: Bool? = nil, trailing: AnyView? = nil, action: @escaping () -> Void+ ) {+ self.icon = icon+ self.mark = mark+ self.title = title+ self.subtitle = subtitle+ self.depth = depth+ self.bold = bold+ self.dim = dim+ self.selected = selected+ self.chevron = chevron+ self.trailing = trailing+ self.action = action+ }++ var body: some View {+ HStack(spacing: 12) {+ Group {+ if let mark {+ mark+ } else if let icon {+ Image(systemName: icon).font(.body).foregroundColor(.secondary)}- .buttonStyle(.plain)+ }+ .frame(width: 24)+ VStack(alignment: .leading, spacing: 1) {+ Text(title)+ .font(.body.weight(bold ? .semibold : .regular))+ .foregroundColor(dim ? .secondary : .primary)+ .lineLimit(1)+ if let subtitle {+ Text(subtitle).font(.footnote).foregroundColor(.secondary).lineLimit(1)+ }+ }+ Spacer(minLength: 0)+ if let trailing { trailing }+ if let chevron {+ Image(systemName: "chevron.right")+ .font(.footnote.weight(.semibold))+ .foregroundColor(.secondary)+ .rotationEffect(.degrees(chevron ? 90 : 0))+ }+ }+ .padding(.leading, 12 + CGFloat(depth) * 18)+ .padding(.trailing, 10)+ .frame(minHeight: 44)+ .background(+ RoundedRectangle(cornerRadius: 12, style: .continuous)+ .fill(selected ? Color.white.opacity(0.13) : Color.clear)+ )+ .contentShape(Rectangle())+ .onTapGesture(perform: action)+ .accessibilityElement(children: .combine)+ .accessibilityAddTraits(.isButton)+ }+}++extension View {+ /// The system's Liquid Glass round a button, from iOS 26; a material+ /// before it.+ @ViewBuilder+ func glassCircle() -> some View {+ if #available(iOS 26.0, *) {+ glassEffect(.regular.interactive(), in: .circle)+ } else {+ background(.ultraThinMaterial, in: Circle())+ }+ }++ /// The same, in a capsule (a field, a row of buttons); tinted, the one+ /// button that leads.+ @ViewBuilder+ func glassCapsule(tint: Color? = nil) -> some View {+ if #available(iOS 26.0, *) {+ if let tint {+ glassEffect(.regular.tint(tint).interactive(), in: .capsule)} else {- Spacer().frame(width: 20)+ glassEffect(.regular, in: .capsule)+ }+ } else if let tint {+ background(tint, in: Capsule())+ } else {+ background(.ultraThinMaterial, in: Capsule())+ }+ }++ /// A bar at one end of a scrolling list that the list runs under,+ /// fading there rather than cut: the system's soft scroll edge from+ /// iOS 26, a fade into `color` before it. A bar whose words must stay+ /// readable over the list (`scrim`) keeps the fade on every version.+ func floatingBar<Bar: View>(+ edge: VerticalEdge, fading color: Color, scrim: Bool = false, @ViewBuilder _ bar: () -> Bar+ ) -> some View {+ modifier(FloatingBar(edge: edge, color: color, scrim: scrim, bar: bar()))+ }++ /// Reads where the system puts a bar `height` tall along `edge` of the+ /// screen: how far that is from the safe area's edges (`BarRoom`), for+ /// a bar there to add to its margins -- at the sides, a bar that+ /// reaches that side of the screen.+ func barRoom(_ edge: VerticalEdge, height: CGFloat, _ room: Binding<EdgeInsets>) -> some View {+ background(BarRoom(edge: edge, height: height, room: room))+ }++ /// Glass shapes side by side, drawn together as the system draws its+ /// own groups of buttons, from iOS 26.+ @ViewBuilder+ func glassGroup(spacing: CGFloat) -> some View {+ if #available(iOS 26.0, *) {+ GlassEffectContainer(spacing: spacing) { self }+ } else {+ self+ }+ }++ /// A tab's capsule in the glass of the buttons beside it, the tab on+ /// show lit with the bar's ink.+ @ViewBuilder+ func glassPill(lit: Bool, ink: Color) -> some View {+ if #available(iOS 26.0, *) {+ glassEffect(lit ? .regular.tint(ink.opacity(0.2)).interactive() : .regular.interactive(), in: .capsule)+ } else {+ background(ink.opacity(lit ? 0.18 : 0.06), in: Capsule())+ }+ }+}++private struct FloatingBar<Bar: View>: ViewModifier {+ let edge: VerticalEdge+ let color: Color+ let scrim: Bool+ let bar: Bar++ private var edges: Edge.Set { edge == .top ? .top : .bottom }++ @ViewBuilder+ func body(content: Content) -> some View {+ if #available(iOS 26.0, *) {+ content+ .safeAreaBar(edge: edge) { system }+ .scrollEdgeEffectStyle(.soft, for: edges)+ } else {+ content.safeAreaInset(edge: edge, spacing: 0) { faded }+ }+ }++ @ViewBuilder+ private var system: some View {+ if scrim { faded } else { bar }+ }++ /// The bar over `color`, solid at the screen's edge and clear at the+ /// bar's inner one.+ private var faded: some View {+ bar.background(+ LinearGradient(+ stops: [+ .init(color: color, location: 0),+ .init(color: color, location: 0.7),+ .init(color: color.opacity(0), location: 1),+ ],+ startPoint: edge == .top ? .top : .bottom,+ endPoint: edge == .top ? .bottom : .top+ )+ .ignoresSafeArea(edges: edges)+ )+ }+}++/// Where the system lays a bar along the top or bottom of the screen,+/// which is not always the safe area's edge: an unfolded Duo, its status+/// bar at the side, has no safe area at the top, and a bar there belongs+/// below the rounded corners; at the bottom of a phone a bar sits partly+/// over the home indicator, as the system's tab bar does. iOS 27.1 says+/// where (`UIView.LayoutRegion.bar`); from iOS 26 the tab bar's place+/// stands in at the bottom. Measured on the window, from its safe area's+/// edges (a bottom bar's room below it is negative): the view backing a+/// SwiftUI one can be read mid-layout, somewhere it never shows, and is+/// given no safe area of its own.+private struct BarRoom: UIViewRepresentable {+ let edge: VerticalEdge+ let height: CGFloat+ @Binding var room: EdgeInsets++ func makeUIView(context: Context) -> Reader {+ let reader = Reader()+ reader.isUserInteractionEnabled = false+ return reader+ }++ func updateUIView(_ reader: Reader, context: Context) {+ let room = $room+ reader.found = { if room.wrappedValue != $0 { room.wrappedValue = $0 } }+ reader.edge = edge+ reader.height = height+ reader.read()+ }++ /// Reads the room again whenever the screen may have changed under+ /// it, and tells only a change, after the pass.+ final class Reader: UIView {+ var edge = VerticalEdge.top+ var height: CGFloat = 0+ var found: ((EdgeInsets) -> Void)?+ private var told: EdgeInsets?++ override func didMoveToWindow() {+ super.didMoveToWindow()+ read()+ }++ override func layoutSubviews() {+ super.layoutSubviews()+ read()+ }++ func read() {+ guard let window, height > 0 else { return }+ let rtl = window.effectiveUserInterfaceLayoutDirection == .rightToLeft+ let insets = window.safeAreaInsets+ let safe = NSDirectionalEdgeInsets(+ top: insets.top,+ leading: rtl ? insets.right : insets.left,+ bottom: insets.bottom,+ trailing: rtl ? insets.left : insets.right+ )+ var room = EdgeInsets()+ if #available(iOS 27.1, *) {+ let bar = window.directionalEdgeInsets(+ for: .bar(onEdge: edge == .top ? NSDirectionalRectEdge.top : .bottom, extent: height)+ )+ room = EdgeInsets(+ top: edge == .top ? bar.top - safe.top : 0,+ leading: bar.leading - safe.leading,+ bottom: edge == .bottom ? bar.bottom - safe.bottom : 0,+ trailing: bar.trailing - safe.trailing+ )+ } else if #available(iOS 26.0, *), edge == .bottom, safe.bottom >= 20 {+ // The tab bar's middle is 52 points above the edge of a+ // phone with a home indicator.+ room.bottom = min(0, 52 - height / 2 - safe.bottom)}- content()+ guard room != told else { return }+ told = room+ let found = self.found+ DispatchQueue.main.async { found?(room) }}- .padding(.leading, 8 + CGFloat(depth) * 14)- .padding(.trailing, 4)- .padding(.vertical, 6)- .frame(maxWidth: .infinity, alignment: .leading)- .background(selected ? Color.accentColor.opacity(0.18) : Color.clear)}}diff --git a/ios/Sources/TabIcons.swift b/ios/Sources/TabIcons.swiftnew file mode 100644index 00000000..6ad0fb74--- /dev/null+++ b/ios/Sources/TabIcons.swift@@ -0,0 +1,121 @@+import SwiftUI+import UIKit++/// The card heading a tab or a pane's capsule, as the desktop draws it: a+/// coloured circle carrying the mark of what the pane runs, in the card's+/// glyph colour (`Core.tabIcon`). A busy pane's mark gives way to the+/// spinner, which shows alone where there is no card (tab icons off, or+/// a card from before the host's came).+struct TabIconCard: View {+ let core: Core+ var id: String?+ var size: CGFloat+ var busy = false+ /// The cards' revision (`TerminalModel.iconsRevision`): a new one+ /// draws the card again.+ var revision: UInt64 = 0+ @Environment(\.displayScale) private var scale++ var body: some View {+ if let id, let icon = TabIconImages.shared.icon(id, points: size, scale: scale, core: core) {+ ZStack {+ Circle().fill(icon.circle)+ if busy {+ Spinner(color: icon.glyph).padding(size * 0.22)+ } else if let mask = icon.mask {+ Image(uiImage: mask)+ .renderingMode(.template)+ .resizable()+ .foregroundColor(icon.glyph)+ .frame(width: size * 0.56, height: size * 0.56)+ }+ }+ .frame(width: size, height: size)+ .accessibilityHidden(true)+ } else if busy {+ Spinner(color: .white.opacity(0.7))+ .frame(width: size * 0.7, height: size * 0.7)+ .frame(width: size, height: size)+ .accessibilityHidden(true)+ }+ }+}++/// The cards drawn so far, by id and pixel size: each is drawn once and+/// kept while the cards stay the same -- a few dozen built-in ones and at+/// most 64 of a host's own, at the one or two sizes the app uses.+final class TabIconImages {+ static let shared = TabIconImages()++ struct Icon {+ let circle: Color+ let glyph: Color+ /// The glyph's shape, white at its coverage; nil for a card without.+ let mask: UIImage?+ }++ private var cache: [String: Icon] = [:]+ /// Ids the cards have none for, so as not to ask again.+ private var missing: Set<String> = []+ /// The core's revision of the cards in `cache`.+ private var revision: UInt64 = 0++ private init() {+ // Drawn again when next shown: let the memory go when it is short.+ NotificationCenter.default.addObserver(+ forName: UIApplication.didReceiveMemoryWarningNotification, object: nil, queue: .main+ ) { [weak self] _ in+ self?.cache.removeAll()+ self?.missing.removeAll()+ }+ }++ func icon(_ id: String, points: CGFloat, scale: CGFloat, core: Core) -> Icon? {+ let now = core.tabIconsRevision()+ if now != revision {+ // Another host's cards, or the built-in ones again.+ cache.removeAll()+ missing.removeAll()+ revision = now+ }+ let pixels = UInt32((points * 0.56 * scale).rounded(.up))+ let key = "\(id)@\(pixels)"+ if let icon = cache[key] { return icon }+ if missing.contains(key) { return nil }+ guard let card = core.tabIcon(id: id, size: pixels) else {+ missing.insert(key)+ return nil+ }+ let icon = Icon(+ circle: Color(hex: card.circle) ?? .gray,+ glyph: Color(hex: card.glyph) ?? .white,+ mask: Self.image(card, scale: scale)+ )+ cache[key] = icon+ return icon+ }++ /// The core's coverage bytes as a white image with that alpha, which a+ /// template image is tinted through.+ private static func image(_ card: TabIcon, scale: CGFloat) -> UIImage? {+ let size = Int(card.size)+ guard size > 0, card.mask.count == size * size else { return nil }+ var rgba = [UInt8](repeating: 0, count: size * size * 4)+ for (i, alpha) in card.mask.enumerated() {+ // Premultiplied white: every channel at the coverage.+ rgba[i * 4] = alpha+ rgba[i * 4 + 1] = alpha+ rgba[i * 4 + 2] = alpha+ rgba[i * 4 + 3] = alpha+ }+ guard let provider = CGDataProvider(data: Data(rgba) as CFData),+ let image = CGImage(+ width: size, height: size, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: size * 4,+ space: CGColorSpaceCreateDeviceRGB(),+ bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),+ provider: provider, decode: nil, shouldInterpolate: true, intent: .defaultIntent+ )+ else { return nil }+ return UIImage(cgImage: image, scale: scale, orientation: .up).withRenderingMode(.alwaysTemplate)+ }+}diff --git a/ios/Sources/TerminalInputView.swift b/ios/Sources/TerminalInputView.swiftindex 2bebb7e4..9d0a31e1 100644--- a/ios/Sources/TerminalInputView.swift+++ b/ios/Sources/TerminalInputView.swift@@ -37,9 +37,8 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDelprivate var recentring = false/// Stepped mode: finger travel not yet a whole row.private var rowRemainder: CGFloat = 0- /// The document the text system reads: the pane's visible rows, as- /// the core last gave them. Fetched when a selection interaction asks- /// and dropped when the core reports a change.+ /// The document the text system reads: the pane's visible rows,+ /// decoded once and dropped when they change (`currentScreen`).private var screen: ScreenText?/// The system's selection, held so the gesture setting can take it/// away and put it back while the terminal stays open.@@ -181,6 +180,10 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDelguard g.state == .ended else { return }let t = g.translation(in: self)let v = g.velocity(in: self)+ // One from the screen's left edge opens the sidebar instead, where+ // that edge does.+ let start = g.location(in: nil).x - g.translation(in: nil).x+ if model?.edgePullsDrawer == true, start < TerminalScreen.edgeWidth { return }guard abs(t.x) > 70, abs(t.y) < 50, abs(v.x) > 400, abs(v.x) > abs(v.y) * 2 else { return }model?.switchTab(by: t.x < 0 ? 1 : -1)}@@ -228,6 +231,34 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDeloverride var canBecomeFirstResponder: Bool { true }+ @discardableResult+ override func becomeFirstResponder() -> Bool {+ let became = super.becomeFirstResponder()+ updateScreenWanted()+ return became+ }++ @discardableResult+ override func resignFirstResponder() -> Bool {+ let resigned = super.resignFirstResponder()+ // The handles go with the keyboard, and so does what they held:+ // unseen, it would still hold off the edge's swipe.+ if resigned, selected != nil {+ selected = nil+ tintColor = .clear+ inputDelegate?.selectionDidChange(self)+ }+ updateScreenWanted()+ return resigned+ }++ /// The text system reads the rows while the keyboard is up (marked+ /// text, the caret) or a selection is held: the core keeps them current+ /// then. Otherwise they are made when asked, at a wait.+ private func updateScreenWanted() {+ model?.setScreenWanted(isFirstResponder || selected != nil)+ }+// MARK: composition bookkeepingprivate func beginComposing() {@@ -271,17 +302,30 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDel// MARK: the document- /// The core changed something on screen: the rows are read again- /// when next asked for.+ /// The core published new rows: they are decoded again when next+ /// asked for. While a composition is open they change under it+ /// unannounced: told, the text system may reset the candidates.func screenChanged() {+ guard marked == nil else {+ screen = nil+ return+ }inputDelegate?.textWillChange(self)screen = nilinputDelegate?.textDidChange(self)}+ /// A frame was painted while the rows are not kept current: the next+ /// question reads them again.+ func dropScreen() { screen = nil }++ /// The rows: the core's published ones while they are wanted, read+ /// without a wait; otherwise asked for once, waiting for the core.private func currentScreen() -> ScreenText? {if let screen { return screen }- guard let model, let s = ViewJSON.decode(ScreenText.self, model.core.screenText()) else { return nil }+ guard let model else { return nil }+ let json = model.screenWanted && model.screenJSON != "null" ? model.screenJSON : model.core.screenText()+ guard let s = ViewJSON.decode(ScreenText.self, json) else { return nil }screen = sreturn s}@@ -375,8 +419,14 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDel/// end of the marked text (the keyboard's insertion point)./// The system's selection over the rows, as document offsets. It is/// the shell's alone: the core is not told, so it draws no highlight- /// of its own under the system's, and the copy reads the rows here.- private var selected: (a: Int, b: Int)?+ /// of its own under the system's. Only the copy asks the core, for+ /// the selected cells' own text.+ private var selected: (a: Int, b: Int)? {+ didSet { updateScreenWanted() }+ }++ /// A selection is up, its handles to be moved.+ var holdsSelection: Bool { selected != nil }var selectedTextRange: UITextRange? {get {@@ -567,17 +617,20 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDel}}- /// The selected rows' text, each row's trailing blanks dropped, as- /// a terminal copies: the rows are fixed-width, the words are not.+ /// The selected cells' text, each row's trailing blanks dropped, as+ /// a terminal copies. The core reads it from the cells: the rows here+ /// put a stand-in after every wide character and in place of any+ /// character outside the BMP, and a copy must carry neither.func selectedText() -> String? {- guard let selected, let raw = text(in: Range(selected.a, selected.b)) else { return nil }- let lines = raw.split(separator: "\n", omittingEmptySubsequences: false).map { line -> String in- var s = String(line)- while s.last == " " { s.removeLast() }- return s- }- let joined = lines.joined(separator: "\n")- return joined.isEmpty ? nil : joined+ guard let selected, selected.b > selected.a, let s = currentScreen() else { return nil }+ // A selection that starts on a row's line break starts on the next row.+ let stride = s.cols + 1+ let start = selected.a % stride == s.cols ? selected.a + 1 : selected.a+ // What is still on the rows, if they shrank since it was selected.+ let end = min(selected.b, screenLength)+ guard start < end, let first = cell(at: start), let last = cell(at: end - 1),+ let text = model?.copyText(from: first, to: last), !text.isEmpty else { return nil }+ return text}override func copy(_ sender: Any?) {diff --git a/ios/Sources/TerminalModel.swift b/ios/Sources/TerminalModel.swiftindex 01f422ac..bf1bb4cb 100644--- a/ios/Sources/TerminalModel.swift+++ b/ios/Sources/TerminalModel.swift@@ -17,19 +17,46 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {// The App's views, refreshed when the core says something changed.@Published var tabs: TabsView?@Published var threads: ThreadsView?- /// The last rows of panes the overview asked about, by pane.- @Published var previews: [Int: [PreviewRow]] = [:]+ /// Whole tabs, as they are split, by the pane a card shows, for the+ /// overview's cards, and their pictures, drawn off the main thread+ /// (`paintScreen`): asked for while it is up, let go when it closes+ /// (`releaseScreens`).+ @Published private(set) var screens: [Int: TabPreview] = [:]+ @Published private(set) var pictures: [Int: CGImage] = [:]+ /// Moves with each screen that comes in: its picture is drawn again.+ @Published private(set) var screenSerials: [Int: Int] = [:]+ private var screensWanted = false+ /// When each pane's screen was asked for, until it comes: one question+ /// a pane at a time, asked again only if it goes long unanswered.+ private var screenAsks: [Int: ContinuousClock.Instant] = [:]+ /// Moves when the screens are let go: a picture drawn before is not kept.+ private var paintTurn = 0+ private let painter = DispatchQueue(label: "thinkterm.screen-pictures", qos: .userInitiated)@Published var sidebar: SidebarView?+ /// Moves when the tab icon cards change (`Core.tabIconsRevision`): the+ /// cards on show are drawn again.+ @Published private(set) var iconsRevision: UInt64 = 0+ /// A menu action that ends something (`delete-thread:…`), awaiting a yes.+ @Published var confirming: String?+ /// Counts the sidebar's "+": the screen asks for the folder.+ @Published private(set) var nameAsks = 0@Published var tree: TreeView?@Published var navs: [NavView] = []@Published var status: StatusView?@Published var title = ""@Published var connection = ""/// The key panel is up in the keyboard's place.+ #if DEBUG@Published var panelOpen = ProcessInfo.processInfo.arguments.contains("--keypanel")+ #else+ @Published var panelOpen = false+ #endif/// A thread this phone was on last time it was in this host, put/// back once the threads are listed after a connect.private var restoredThread = false+ /// The connection whose views were out when this one was asked for:+ /// its listing is not this connection's first.+ private var connectionBefore: UInt64 = 0private var lastThreadKey: String? { host.map { "thread.last." + $0.id.uuidString } }var isConnected: Bool {@@ -53,7 +80,18 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {private var toastTimer: Timer?/// The terminal's background, as the App paints it: the chrome around/// the terminal takes the same colour.- @Published var background = Color(white: 0.11)+ @Published var background = Color(white: 0.11) {+ didSet { ink = Self.ink(over: background) }+ }+ /// The chrome's ink over `background`: white over a dark scheme, near+ /// black over a light one.+ @Published private(set) var ink = Color.white++ private static func ink(over color: Color) -> Color {+ var (r, g, b, a): (CGFloat, CGFloat, CGFloat, CGFloat) = (0, 0, 0, 0)+ guard UIColor(color).getRed(&r, green: &g, blue: &b, alpha: &a) else { return .white }+ return 0.2126 * r + 0.7152 * g + 0.0722 * b > 0.6 ? Color(white: 0.1) : .white+ }/// The App's font size in points, from its layout view.@Published private(set) var fontPt: Double = 11/// The focused pane's place in its scrollback: rows above the bottom,@@ -65,8 +103,25 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {/// the screen, for as long as iOS allows.private var backgroundTask: UIBackgroundTaskIdentifier = .invalid@Published var animating = false- /// The log view is open: the stats are worth refreshing.- var wantsStats = false+ /// The log view is open.+ var logShown = false+ /// The log view is open or developer mode is on: the stats are worth+ /// refreshing.+ var wantsStats: Bool { logShown || settings.devMode }+ /// The views last read from the core.+ private var lastViews: ViewSet?+ /// The focused pane's rows for the text input, kept current by the+ /// core while they are wanted (the keyboard is up, or a selection).+ private(set) var screenWanted = false+ /// A swipe from the screen's left edge pulls the sidebar out (a narrow+ /// screen, the drawer shut): a flick that starts there is not a tab's.+ var edgePullsDrawer = false+ private(set) var screenJSON = "null"+ private var screenRevision: UInt64 = 0+ /// This connection's terminal is on screen, and the app in front: the+ /// core is told, so a session behind the screen takes nothing.+ private var onScreen = false+ private var inFront = true/// The preferences, followed as they change.let settings = AppSettings.sharedvar smoothScroll: Bool { settings.smoothScroll }@@ -93,7 +148,6 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {var cursorRect = CGRect(x: 8, y: 8, width: 2, height: 20)private let frameNeeded = AtomicFlag()- private let changePending = AtomicFlag()private var displayLink: CADisplayLink?private var statsTimer: Timer?private var logLines: [String] = []@@ -110,6 +164,12 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {private var probeKeyPath = "/tmp/ttp-ssh/userkey"private var probeRemoteCommand = "/tmp/ttp-ssh/thinkterm-remote cli --prefer-mux proxy"private var probeUser = probeUserName()+ // The acceptance flow's requests answered, and its stall gauge.+ private var acceptTimer: Timer?+ private var acceptAnswered = 0+ private var measuringTicks = false+ private var lastTickAt: CFTimeInterval = 0+ private var longestTickGap: CFTimeInterval = 0#endifinit(host: Host?, store: HostStore?) {@@ -140,7 +200,9 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {let stats = self.core.stats()if stats != self.stats { self.stats = stats }}+ #if DEBUGif let name = arg("--scheme") { settings.schemeName = name }+ #endifapplyScrollMode()applyScheme()settings.$schemeName.dropFirst().sink { [weak self] _ in self?.applyScheme() }.store(in: &subscriptions)@@ -159,7 +221,9 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {self.disconnect()self.connect()}.store(in: &subscriptions)- settings.$devMode.sink { [weak self] on in self?.wantsStats = on || (self?.wantsStats ?? false) }.store(in: &subscriptions)+ // The size, though, every pane takes live, from either settings page.+ applyFontSize(settings.fontSize)+ settings.$fontSize.dropFirst().removeDuplicates().sink { [weak self] pt in self?.applyFontSize(pt) }.store(in: &subscriptions)#if DEBUGif args.contains("--autotest") { scheduleAutotest() }if args.contains("--autoconnect") { scheduleAutoconnect() }@@ -167,13 +231,30 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {if args.contains("--seltest") { scheduleSelectionTest() }if args.contains("--treetest") { scheduleTreeTest() }if args.contains("--uitest") { scheduleUiTest() }+ if args.contains("--accepttest") { scheduleAcceptTest() }#endif}+ /// The sidebar's "+": the screen asks for the folder.+ func askName() { nameAsks += 1 }+/// The screen went away but the connection stays: the frame loop/// rests until the screen is back. The surface goes with the view.- func leaveScreen() { displayLink?.isPaused = true }- func enterScreen() { displayLink?.isPaused = false }+ func leaveScreen() {+ // Its text input goes with it: nothing reads the rows.+ setScreenWanted(false)+ displayLink?.isPaused = true+ onScreen = false+ updateShown()+ }++ func enterScreen() {+ displayLink?.isPaused = false+ onScreen = true+ updateShown()+ }++ private func updateShown() { core.setShown(shown: onScreen && inFront) }func shutdown() {clearHostKeyRequest()@@ -188,8 +269,7 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {/// The chosen face first, the symbols fallback after it.var fontPaths: [String] {- let face = settings.fontFamily == "Fira Code" ? "FiraCode-Regular" : "JetBrainsMono-Regular"- return [face, "SymbolsNerdFontMono-Regular"].compactMap {+ [terminalFace, "SymbolsNerdFontMono-Regular"].compactMap {Bundle.main.path(forResource: $0, ofType: "ttf")}}@@ -206,6 +286,11 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {/// Connect to the model's host with the secret from the Keychain.func connect() {restoredThread = false+ // A new connection's views are all new, even ones that read the+ // same: the first listing puts the phone back on its thread. The+ // core may still have the last connection's out until it gets here.+ lastViews = nil+ connectionBefore = core.viewsConnection()guard let host else {// Only the automated flows open a screen with no host.#if DEBUG@@ -377,6 +462,11 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {core.setSetting(key: "language", value: "\"\(L10n.currentTag)\"")}+ /// The base text size of every pane; a pinch scales one pane on top.+ private func applyFontSize(_ pt: Double) {+ core.setSetting(key: "font", value: "{\"mode\":\"pinned\",\"pt\":\(pt)}")+ }+/// The tab `by` places along the strip from the current one, shown.func switchTab(by: Int) {guard let tabs = tabs?.tabs, !tabs.isEmpty,@@ -386,11 +476,64 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {chromeClick("pane", pane: tabs[next].target)}- /// The last rows of a pane, for a thumbnail; `previews` fills in.- func requestPreview(pane: Int, rows: Int = 8) {- core.requestPreview(pane: UInt32(pane), rows: UInt32(rows))+ /// The overview opened: the screens asked for are kept until it+ /// closes (`releaseScreens`).+ func keepScreens() { screensWanted = true }++ /// The whole tab a pane is in, as it is split, for a picture of it;+ /// `screens` fills in. Asked only while they are kept.+ func requestScreen(pane: Int) {+ guard screensWanted else { return }+ let now = ContinuousClock.now+ if let asked = screenAsks[pane], now - asked < .seconds(5) { return }+ screenAsks[pane] = now+ core.requestScreenPreview(pane: UInt32(pane))+ }++ /// The overview closed: its screens and pictures go, and answers on+ /// the way find nobody waiting.+ func releaseScreens() {+ screensWanted = false+ paintTurn += 1+ screens = [:]+ pictures = [:]+ screenSerials = [:]+ screenAsks = [:]+ }++ fileprivate func coreScreen(_ pane: Int, _ screen: TabPreview) {+ screenAsks[pane] = nil+ // One as it was is not drawn again.+ guard screensWanted, screens[pane] != screen else { return }+ screens[pane] = screen+ screenSerials[pane, default: 0] += 1+ }++ /// Draw a pane's screen `pixels` large off the main thread: `done` has+ /// it, unless the screens were let go meanwhile. Not kept: a flight to+ /// the terminal's size wants it once.+ func paint(pane: Int, pixels: CGSize, done: @escaping (CGImage) -> Void) {+ guard let screen = screens[pane] else { return }+ let face = terminalFace+ let turn = paintTurn+ painter.async { [weak self] in+ let picture = ScreenPainter.paint(screen, pixels: pixels, face: face)+ DispatchQueue.main.async {+ guard let self, self.screensWanted, turn == self.paintTurn, let picture else { return }+ done(picture)+ }+ }}+ /// Draw a pane's screen for its card; `pictures` has it once it is.+ func paintScreen(pane: Int, pixels: CGSize) {+ paint(pane: pane, pixels: pixels) { [weak self] picture in self?.pictures[pane] = picture }+ }++ /// The face the terminal draws in, by its PostScript name, which is+ /// its file's name too.+ var terminalFace: String { settings.fontFamily == "Fira Code" ? "FiraCode-Regular" : "JetBrainsMono-Regular" }+/// A pane rang its bell: a buzz, if the setting says so.fileprivate func coreBell() {DispatchQueue.main.async {@@ -457,29 +600,77 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {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.+ /// The text between two visible cells of the focused pane, for the+ /// clipboard, as the core reads it from the cells; the pane's own+ /// selection is left be. A copy waits for the core.+ func copyText(from first: (row: Int, col: Int), to last: (row: Int, col: Int)) -> String? {+ core.textBetween(anchorRow: UInt32(first.row), anchorCol: UInt32(first.col),+ headRow: UInt32(last.row), headCol: UInt32(last.col))+ }++ /// The text input reads the rows (the keyboard is up, or there is a+ /// selection): the core keeps them current while it does.+ func setScreenWanted(_ wanted: Bool) {+ guard wanted != screenWanted else { return }+ screenWanted = wanted+ if wanted {+ // What is out was made while nobody read it: the next made (the+ // core makes one at once) is read, and until then the rows are+ // asked for. Taken before asking, so that one is not missed.+ screenRevision = core.screenRevision()+ } else {+ screenJSON = "null"+ }+ core.setScreenWanted(wanted: wanted)+ }++ /// Read the views the core last published. Called on the main thread+ /// each frame the revision moved; a burst of changes is one read, and+ /// it never waits for the core thread.func refreshViews() {- inputView?.screenChanged()- // Assigned only on a change: a published write redraws the whole- // screen, and the core reports changes as often as output comes.- let tabs = ViewJSON.decode(TabsView.self, core.view(name: "tabs"))- if tabs != self.tabs { self.tabs = tabs }- let sidebar = ViewJSON.decode(SidebarView.self, core.view(name: "sidebar"))- if sidebar != self.sidebar { self.sidebar = sidebar }- let threads = ViewJSON.decode(ThreadsView.self, core.view(name: "threads"))- if threads != self.threads { self.threads = threads }- rememberThread(threads)- let tree = ViewJSON.decode(TreeView.self, core.view(name: "tree"))- if tree != self.tree { self.tree = tree }- let navs = ViewJSON.decode([NavView].self, core.view(name: "navs")) ?? []- if navs != self.navs { self.navs = navs }- let status = ViewJSON.decode(StatusView.self, core.view(name: "status"))- if status != self.status {- self.status = status- showToast(status?.toast)+ let views = core.views()+ guard views.revision != lastViews?.revision else { return }+ let last = lastViews+ lastViews = views+ // A change of cards marks the views stale, so it is seen here.+ let icons = core.tabIconsRevision()+ if icons != iconsRevision { iconsRevision = icons }+ // Decoded only when the text changed, and assigned only on a+ // change: a published write redraws the whole screen, and the+ // core publishes as often as output comes.+ if views.tabs != last?.tabs {+ let tabs = ViewJSON.decode(TabsView.self, views.tabs)+ if tabs != self.tabs { self.tabs = tabs }+ }+ if views.sidebar != last?.sidebar {+ let sidebar = ViewJSON.decode(SidebarView.self, views.sidebar)+ if sidebar != self.sidebar { self.sidebar = sidebar }+ }+ let threadsChanged = views.threads != last?.threads+ if threadsChanged {+ let threads = ViewJSON.decode(ThreadsView.self, views.threads)+ if threads != self.threads { self.threads = threads }}- let layout = core.view(name: "layout")+ if views.connection > connectionBefore, threadsChanged || !restoredThread {+ rememberThread(threads)+ }+ if views.tree != last?.tree {+ let tree = ViewJSON.decode(TreeView.self, views.tree)+ if tree != self.tree { self.tree = tree }+ }+ if views.navs != last?.navs {+ let navs = ViewJSON.decode([NavView].self, views.navs) ?? []+ if navs != self.navs { self.navs = navs }+ }+ if views.status != last?.status {+ let status = ViewJSON.decode(StatusView.self, views.status)+ if status != self.status {+ self.status = status+ showToast(status?.toast)+ }+ }+ guard views.layout != last?.layout else { return }+ let layout = views.layoutif let r = layout.range(of: "\"cell\":["),let end = layout[r.upperBound...].firstIndex(of: "]") {let parts = layout[r.upperBound..<end].split(separator: ",")@@ -554,6 +745,8 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {private var pausedForBackground = falsefunc detachForBackground() {+ inFront = false+ updateShown()detach()report("background")if settings.keepSessionInBackground {@@ -578,6 +771,8 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {}func reattachAfterBackground() {+ inFront = true+ updateShown()endBackgroundTask()if pausedForBackground {pausedForBackground = false@@ -609,13 +804,32 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {// MARK: frames+ /// The display link: paint if asked, then read what the core published+ /// -- the counts say whether there is anything new, without a wait.@objc private func tick() {+ #if DEBUG+ if measuringTicks {+ let now = CACurrentMediaTime()+ if lastTickAt > 0 { longestTickGap = max(longestTickGap, now - lastTickAt) }+ lastTickAt = now+ }+ #endifif frameNeeded.take() {core.render()+ // Unwanted rows are not kept current: read again when asked.+ if !screenWanted { inputView?.dropScreen() }}- if changePending.take() {+ if core.viewsRevision() != lastViews?.revision {refreshViews()}+ if screenWanted {+ let revision = core.screenRevision()+ if revision != screenRevision {+ screenRevision = revision+ screenJSON = core.screen()+ inputView?.screenChanged()+ }+ }}func requestOneFrame() { frameNeeded.set() }@@ -640,7 +854,6 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {// MARK: notify (core thread)fileprivate func coreWantsFrame() { frameNeeded.set() }- fileprivate func coreChanged() { changePending.set() }fileprivate func coreStatus(_ status: String) {DispatchQueue.main.async {@@ -652,7 +865,6 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {if status.hasPrefix("connecting") || status.contains("reconnect") || status.hasPrefix("disconnected") {self.inputView?.dropComposition()}- self.changePending.set()}}@@ -670,11 +882,31 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {guard host.hostname == endpoint.hostname, host.port == endpoint.port,host.knownHost == nil else { return }}- self.pendingHostKey = HostKeyChallenge(id: requestID, hostname: endpoint.hostname,+ let challenge = HostKeyChallenge(id: requestID, hostname: endpoint.hostname,port: endpoint.port, hostID: endpoint.hostID, fingerprint: fingerprint)+ #if DEBUG+ // The automated flows dial the probe's throwaway sshd, and no+ // one is there to read its fingerprint.+ if self.host == nil, Self.automated {+ self.approveHostKey(challenge)+ return+ }+ #endif+ self.pendingHostKey = challenge}}+ /// Launched for an automated flow (`--autoconnect`, `--uitest`, ...):+ /// the app opens straight on the probe's terminal and connects on the+ /// flow's schedule. Never in a release.+ static let automated: Bool = {+ #if DEBUG+ return ProcessInfo.processInfo.arguments.contains { $0.hasPrefix("--auto") || $0.hasSuffix("test") }+ #else+ return false+ #endif+ }()+fileprivate func coreLogged(_ line: String) {print("core: " + line)DispatchQueue.main.async { self.log("core: " + line) }@@ -739,6 +971,74 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {q.asyncAfter(deadline: .now() + 21.0) { self.report("after reconnect"); print("AUTOCONNECT DONE") }}+ /// `--accepttest`: connect to the probe and do what ios/tools/accept.sh+ /// asks, the driver that cuts the connection, restarts the server and+ /// sends the app to the background from the Mac. Its requests come one+ /// at a time through a file the simulator shares with the Mac, as+ /// "<n> <verb> <argument>"; each is answered on the console with+ /// "ACCEPT ack <n> <detail>".+ private func scheduleAcceptTest() {+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { self.connectProbe() }+ acceptTimer = Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { [weak self] _ in+ self?.pollAcceptRequest()+ }+ }++ private static let acceptRequests = "/tmp/ttp-ssh/accept-request"++ private func pollAcceptRequest() {+ guard let text = try? String(contentsOfFile: Self.acceptRequests, encoding: .utf8) else { return }+ let parts = text.trimmingCharacters(in: .whitespacesAndNewlines)+ .split(separator: " ", maxSplits: 2).map(String.init)+ guard parts.count >= 2, let n = Int(parts[0]), n > acceptAnswered else { return }+ acceptAnswered = n+ let argument = parts.count > 2 ? parts[2] : ""+ switch parts[1] {+ case "state":+ acceptAnswer(n, acceptState())+ case "type":+ core.text(text: argument)+ key("Enter")+ acceptAnswer(n, "typed")+ case "expect":+ // The rows as they are now, not as last published.+ let rows = ViewJSON.decode(ScreenText.self, core.screenText())?.text ?? ""+ acceptAnswer(n, rows.contains(argument) ? "found" : "missing")+ case "measure":+ // From now until "measured", asked for once what is measured+ // has been set going: a stall it starts with is in it.+ longestTickGap = 0+ lastTickAt = 0+ measuringTicks = true+ acceptAnswer(n, "measuring")+ case "measured":+ // The longest the main thread went without a frame callback.+ measuringTicks = false+ acceptAnswer(n, String(format: "longest_gap_ms=%.0f", longestTickGap * 1000))+ default:+ acceptAnswer(n, "unknown")+ }+ }++ /// One line the driver parses: the connection, and the tabs and bars+ /// the phone shows.+ private func acceptState() -> String {+ refreshViews()+ let current = tabs?.tabs.first(where: { $0.current })+ let pane = connection.hasPrefix("pane ") ? connection.dropFirst(5).prefix(while: { $0.isNumber }) : "-"+ // The status line stays on the pane through the App's own redials;+ // its sticky remark is what says the link is down.+ let connected = connection.hasPrefix("pane ") && !reconnecting ? "yes" : "no"+ return "connected=\(connected) pane=\(pane) tab=\(current.map { String($0.tab) } ?? "-")"+ + " tabs=\(tabs?.tabs.count ?? 0) panes=\(current?.panes.count ?? 0) bars=\(navs.count)"+ }++ private func acceptAnswer(_ n: Int, _ detail: String) {+ let line = "ACCEPT ack \(n) \(detail)"+ print(line)+ log(line)+ }+/// 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() {@@ -747,7 +1047,8 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {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")+ // A lone pane has no bar on the phone (Platform::bare_lone_pane).+ self.check("lone pane, no bar", self.navs.isEmpty, "\(self.navs.count) bars")self.chromeClick("split-right")}q.asyncAfter(deadline: .now() + 7.0) {@@ -774,9 +1075,17 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {}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")+ self.check("closed pane, bars gone", self.navs.isEmpty, "\(self.navs.count) bars")+ // The size from Settings reaches the open terminal, not only the next one.+ let size = self.settings.fontSize+ self.settings.fontSize = size + 2+ q.asyncAfter(deadline: .now() + 1.5) {+ self.refreshViews()+ self.check("text size is live", abs(self.fontPt - (size + 2)) < 0.01, "\(size) -> \(self.fontPt) pt")+ self.settings.fontSize = size+ self.report("ui done")+ print("UITEST DONE")+ }}}@@ -848,6 +1157,23 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {self.check("selection rects", rects.count == 1 && rects[0].rect.width > 0, "\(rects.count) rects, first \(rects.first?.rect ?? .zero)")let under = input.closestPosition(to: CGPoint(x: rects.first?.rect.midX ?? 0, y: rects.first?.rect.midY ?? 0)) as? TerminalInputView.Posself.check("point to cell", under.map { $0.i >= a && $0.i < a + 16 } ?? false, "\(under?.i ?? -1)")+ // Wide characters and one outside the BMP: the rows carry+ // stand-ins for both, the copy must not.+ self.core.text(text: "echo 复制中文😀OK\n")+ }+ q.asyncAfter(deadline: .now() + 2.5) {+ let wide = "复制中文😀OK"+ guard let screen = ViewJSON.decode(ScreenText.self, self.core.screenText()) else {+ return self.check("wide line on screen", false, "no rows")+ }+ let rows = screen.text.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)+ guard let row = rows.lastIndex(where: { $0.contains("OK") && $0.contains("文") && !$0.contains("echo") }) else {+ return self.check("wide line on screen", false, "not found")+ }+ let start = row * (screen.cols + 1)+ input.selectedTextRange = TerminalInputView.Range(start, start + screen.cols)+ let copied = input.selectedText() ?? ""+ self.check("copy keeps wide text", copied == wide, copied)self.report("selection done")print("SELTEST DONE")}@@ -861,11 +1187,23 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {q.asyncAfter(deadline: .now() + 1.5) { self.connectProbe() }q.asyncAfter(deadline: .now() + 5.0) {sizeBefore = self.sizeString()+ let asked = Date()self.focusKeyboard()- }- q.asyncAfter(deadline: .now() + 6.5) {- let after = self.sizeString()- self.check("keyboard resize", after != sizeBefore, "\(sizeBefore) -> \(after)")+ // The first keyboard in a while is slow to come up: wait for the+ // resize, up to 5 s, rather than a fixed time.+ func look() {+ let after = self.sizeString()+ let waited = Date().timeIntervalSince(asked)+ if after != sizeBefore || waited > 5 {+ self.check(+ "keyboard resize", after != sizeBefore,+ "\(sizeBefore) -> \(after) after \(String(format: "%.1f", waited)) s"+ )+ } else {+ q.asyncAfter(deadline: .now() + 0.1, execute: look)+ }+ }+ look()}q.asyncAfter(deadline: .now() + 7.0) {guard let v = self.inputView else { self.check("input view", false, "missing"); return }@@ -943,11 +1281,13 @@ func probeUserName() -> String {/// model without touching anything that needs the main thread.private final class NotifySink: Notify, @unchecked Sendable {weak var model: TerminalModel?+ private let screenReader = DispatchQueue(label: "thinkterm.screens", qos: .userInitiated)func onFrameNeeded() { model?.coreWantsFrame() }func onStatus(status: String) { model?.coreStatus(status) }func onLog(line: String) { model?.coreLogged(line) }func onTitle(title: String) { model?.coreTitle(title) }- func onChange() { model?.coreChanged() }+ /// The display link reads the views' count each frame instead.+ func onChange() {}func onClipboard(text: String) {DispatchQueue.main.async {UIPasteboard.general.string = text@@ -969,8 +1309,12 @@ private final class NotifySink: Notify, @unchecked Sendable {func onPublished(key: String, value: String) { model?.corePublished(key, value) }func onBell() { model?.coreBell() }func onPreview(pane: UInt32, rows: String) {- let decoded = ViewJSON.decode([PreviewRow].self, rows) ?? []- DispatchQueue.main.async { self.model?.previews[Int(pane)] = decoded }+ // Only whole screens are asked for here (`requestScreen`), read off+ // the core's thread, in the order they come.+ screenReader.async {+ guard let screen = ViewJSON.decode(TabPreview.self, rows) else { return }+ DispatchQueue.main.async { self.model?.coreScreen(Int(pane), screen) }+ }}}diff --git a/ios/Sources/TerminalScreen.swift b/ios/Sources/TerminalScreen.swiftindex a83a5536..0fa50354 100644--- a/ios/Sources/TerminalScreen.swift+++ b/ios/Sources/TerminalScreen.swift@@ -9,109 +9,325 @@ struct TerminalScreen: View {@ObservedObject private var settings = AppSettings.shared@ObservedObject private var lang = AppLanguage.shared@Environment(\.dismiss) private var dismiss+ @Environment(\.displayScale) private var displayScale+ /// The drawer is out (a narrow screen).@State private var showTree = false+ /// The screen is wide enough to keep the sidebar beside the terminal,+ /// and whether it is kept there.+ @State private var wide = false+ @AppStorage("sidebar.pinned") private var sidebarPinned = true@State private var showLog = false@State private var showSettings = false@State private var menu: MenuSheet?@State private var editingHost: Host?/// A bar being dragged moves the divider it hangs from.@State private var barDrag: CGPoint?- /// The bar's width, for the strip in its middle: a principal item is- /// centred and clipped when wider than its slot, so it is sized.- @State private var barWidth: CGFloat = 402- /// The software keyboard is up: the key bar shows with it.+ /// The software keyboard is up for the terminal: the key bar shows+ /// with it.@State private var keyboardUp = false- /// The overview: the terminal shrinks into its thread's card and the- /// cards fade in around it, as the desktop's Live Overview zooms out.+ /// The drawer's rows are made while it is open and while it slides+ /// shut, not while it lies hidden under the screen.+ @State private var drawerShown = false+ /// How far a swipe from the left edge has pulled the screen off the+ /// drawer, as the Claude app's does; it springs back if let go short.+ @GestureState(resetTransaction: Transaction(animation: TerminalScreen.slide))+ private var edgePull: CGFloat = 0+ @State private var edgeDrag = EdgeDrag()+ /// Where the system puts a bar along the top (`barRoom`): on an+ /// unfolded Duo, below the rounded corners, not at the screen's top.+ @State private var topRoom = EdgeInsets()+ /// A name the sidebar asked for (`SidebarView.editing`), kept here so+ /// the question stands wherever the sidebar is.+ @State private var renaming: (kind: String, id: String)?+ @State private var renameText = ""+ /// The overview (`OverviewScreen`): the terminal shrinks into its+ /// thread's card and the cards fade in around it, as the desktop's Live+ /// Overview zooms out; a card tapped grows back into the terminal.+ /// `overviewOpen` while it is the screen's, `overviewVisible` while its+ /// cards are up (a close included).@State private var overviewOpen = false- @State private var overviewShown = false- /// The cards stay while the terminal comes back out of its card.@State private var overviewVisible = false+ @State private var cardsAlpha: Double = 0+ /// Where the live card's picture is while the terminal is on its way+ /// into it; every card's is in `moves`.+ @State private var landingThumb: CGRect?@State private var terminalFrame: CGRect = .zero- @State private var cardFrame: CardFrames?- /// The card's header, carried along with the terminal by the zoom.- @State private var heroFrames: CardFrames?- @State private var heroScale: CGFloat = 1- @State private var heroOffset: CGSize = .zero- @State private var heroAlpha: Double = 0- /// The moving card's border: its natural height follows the zoom.- @State private var heroFrameHeight: CGFloat = 0- /// The thread whose card the terminal is moving into or out of, and- /// the card a tap picked on the way back.- @State private var heroThread: ThreadView?- @State private var picked: (thread: ThreadView, frames: CardFrames)?- @State private var zoomScale: CGFloat = 1- @State private var zoomOffset: CGSize = .zero- @State private var zoomClip: CGFloat?- /// Once in the card the terminal fades into the card's own preview.- @State private var zoomFade: Double = 1- /// Once the terminal has faded, the live card shows its preview rows.- @State private var livePreview = false- @State private var deletingThread: ThreadView?-- /// The tabs live in the navigation bar, between the system's own back- /// button and the menu; the keys sit below the terminal, and nothing- /// else. Every piece of chrome takes the terminal's own background.+ /// The terminal's top and bottom on the screen: the bar's buttons are+ /// above it and the keys below it scroll sideways, so a swipe from the+ /// edge there is theirs.+ @State private var terminalSpan: ClosedRange<CGFloat> = 0...CGFloat.infinity+ /// The terminal is hidden while a picture of it flies in its place.+ @State private var terminalAlpha: Double = 1+ @State private var flight = Flight()+ /// The thread the terminal went into the card of, and whether the+ /// card's picture shows in its place.+ @State private var liveThread: String?+ @State private var liveShown = false+ @State private var moves = OverviewMoves()+ /// Whether tabs lie past the start of the strip and past its end.+ @State private var stripEnds = StripEnds()++ /// On a phone held upright the sidebar is a drawer the whole screen+ /// slides off, rounding its corner -- by the button or a swipe from the+ /// left edge -- and a tap on what shows of it comes back; on a wide screen (an iPad, an unfolded Duo, landscape) it stays+ /// at the left at full height, and the bar runs over the terminal only,+ /// as on the desktop.var body: some View {+ GeometryReader { geo in+ // Decided in the pass that lays it out, so the terminal is sized+ // once; the state follows a pass later, for the buttons.+ let wide = geo.size.width >= Self.wideWidth+ let drawerOpen = showTree && !wide+ let drawerWidth = min(Self.columnWidth + 40, geo.size.width * 0.84)+ let pulled = drawerOpen || edgePull > 0+ ZStack(alignment: .topLeading) {+ if !wide {+ // The drawer lies under the screen, which slides off it.+ sidebar(live: pulled || drawerShown)+ .frame(width: drawerWidth)+ .opacity(pulled ? 1 : 0)+ .allowsHitTesting(drawerOpen)+ .accessibilityHidden(!drawerOpen)+ }+ HStack(spacing: 0) {+ if wide && sidebarPinned {+ sidebar(live: true).frame(width: Self.columnWidth)+ Rectangle().fill(Color.white.opacity(0.08)).frame(width: 1).ignoresSafeArea()+ }+ screen+ .clipShape(RoundedRectangle(cornerRadius: pulled ? 28 : 0, style: .continuous))+ .overlay {+ if drawerOpen {+ // What shows of the screen takes it back.+ RoundedRectangle(cornerRadius: 28, style: .continuous)+ .fill(Color.black.opacity(0.35))+ .ignoresSafeArea()+ .onTapGesture { showTree = false }+ }+ }+ .shadow(color: .black.opacity(pulled ? 0.55 : 0), radius: 20)+ }+ .offset(x: drawerOpen ? drawerWidth : min(edgePull, drawerWidth))+ }+ .simultaneousGesture(+ // A swipe right from the left edge opens the drawer, the+ // screen following the finger; one from further in is the+ // terminal's (a selection, a scroll).+ DragGesture(minimumDistance: 10, coordinateSpace: .global)+ .updating($edgePull) { drag, pull, transaction in+ // Back once it is none: brought back past where it began.+ let next = pullsDrawer(drag) ? max(0, drag.translation.width) : 0+ if next == 0 && pull > 0 {+ transaction.animation = Self.slide+ }+ pull = next+ }+ .onEnded { drag in+ // Far enough, or flung far enough, and not flung back.+ let far = drag.translation.width > drawerWidth / 3 || drag.predictedEndTranslation.width > drawerWidth / 2+ if far && drag.velocity.width > -200 && pullsDrawer(drag) { showSidebar() }+ edgeDrag.start = nil+ },+ including: wide || drawerOpen ? .subviews : .all+ )+ .simultaneousGesture(+ DragGesture(minimumDistance: 24).onEnded { drag in+ // A swipe to the left, not a scroll of the list that+ // drifts.+ let move = drag.translation+ if move.width < -60 && abs(move.width) > abs(move.height) { showTree = false }+ },+ including: drawerOpen ? .all : .subviews+ )+ .animation(Self.slide, value: showTree)+ .animation(Self.slide, value: sidebarPinned)+ .onAppear {+ self.wide = wide+ model.edgePullsDrawer = !wide && !showTree+ }+ .onChange(of: wide) { _, wide in+ self.wide = wide+ if wide { showTree = false }+ model.edgePullsDrawer = !wide && !showTree+ }+ }+ // Under the status bar: the terminal's colour, or the sidebar's+ // beside an open drawer (the screen is clipped to its frame).+ .background((drawerOpen ? Color(white: 0.07) : cardsAlpha > 0 ? OverviewScreen.backdrop : model.background).ignoresSafeArea())+ .onChange(of: drawerOpen) { _, open in+ model.edgePullsDrawer = !wide && !open+ if open {+ drawerShown = true+ } else {+ // The only field it can leave focused is its search.+ UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {+ if !drawerOpen { drawerShown = false }+ }+ }+ }+ .toolbar(.hidden, for: .navigationBar)+ .toolbar(.hidden, for: .tabBar)+ }++ /// Wide enough for the sidebar to stay beside the terminal.+ private static let wideWidth: CGFloat = 700+ /// How near the left edge a swipe must start to open the drawer.+ static let edgeWidth: CGFloat = 24+ /// The screen sliding off the drawer and back, and the column coming+ /// and going.+ private static let slide = Animation.spring(response: 0.34, dampingFraction: 0.88)+ private static let columnWidth: CGFloat = 280+ private static let barHeight: CGFloat = 54+ /// How far in from an end of the tab strip its tabs fade.+ private static let stripFade: CGFloat = 28+ private var drawerOpen: Bool { showTree && !wide }++ /// A drag that pulls the drawer out: from the screen's left edge and+ /// sideways, over the terminal (the bar's buttons are above it, the+ /// keys under it scroll sideways), and not a selection's handle being+ /// moved. Decided as it sets off and kept, so a thumb's arc turning up+ /// or down on the way does not let go of the screen.+ private func pullsDrawer(_ drag: DragGesture.Value) -> Bool {+ if edgeDrag.start != drag.startLocation {+ let move = drag.translation+ edgeDrag.start = drag.startLocation+ edgeDrag.pulls = drag.startLocation.x < Self.edgeWidth && move.width > abs(move.height)+ && terminalSpan.contains(drag.startLocation.y) && model.inputView?.holdsSelection != true+ }+ return edgeDrag.pulls+ }++ /// The sidebar, opened (a drawer) or brought back (a column).+ private func showSidebar() {+ moves.waiting = false+ if wide { sidebarPinned = true } else { model.dismissKeyboard(); showTree = true }+ }++ /// A drawer covers the terminal and takes its keyboard down; a column+ /// leaves both be.+ private func toggleSidebar() {+ moves.waiting = false+ if wide { sidebarPinned.toggle() } else { model.dismissKeyboard(); showTree.toggle() }+ }++ /// Back to the hosts, an overview waiting to open left shut: the+ /// screen is gone only once it has slid away.+ private func leave() {+ moves.waiting = false+ dismiss()+ }++ private func threadName(_ id: String) -> String {+ for space in model.tree?.spaces ?? [] {+ for project in space.projects {+ if let thread = project.threads.first(where: { $0.id == id }) { return thread.name }+ }+ }+ return ""+ }++ private func sidebar(live: Bool) -> some View {+ SidebarPanel(+ model: model,+ hostName: hostName,+ connected: connected,+ done: { if !wide { showTree = false } },+ onEditHost: { showTree = false; editingHost = model.host },+ onSettings: { showSettings = true },+ onOverview: { openOverview() },+ overviewOn: overviewOpen,+ live: live+ )+ }++ /// The terminal's page: the bar, then the strip, the terminal, the+ /// status line and the keys. Every piece of chrome takes the+ /// terminal's own background.+ private var screen: some View {+ VStack(spacing: 0) {+ topBar+ content+ }+ .barRoom(.top, height: Self.barHeight, $topRoom)+ .background((cardsAlpha > 0 ? OverviewScreen.backdrop : model.background).ignoresSafeArea())+ .ignoresSafeArea(.container, edges: .bottom)+ // Another keyboard (the sidebar's search, a name being asked for)+ // is not the terminal's: it does not resize it.+ .ignoresSafeArea(keyboardUp ? [] : .keyboard, edges: .bottom)+ }++ /// The sidebar, back to the hosts, and the strip in the rest of the+ /// bar; the round buttons in the system's glass.+ private var topBar: some View {+ HStack(spacing: 8) {+ Button { toggleSidebar() } label: { barIcon("sidebar.left") }+ .buttonStyle(.plain)+ .glassCircle()+ .accessibilityLabel(tr("sidebar"))+ Button { leave() } label: { barIcon("chevron.left") }+ .buttonStyle(.plain)+ .glassCircle()+ .accessibilityLabel(tr("hosts"))+ if overviewOpen {+ // The overview's own bar: its name, and the way back.+ Text(tr("overview"))+ .font(.headline)+ .foregroundColor(.white)+ .lineLimit(1)+ .padding(.leading, 4)+ .frame(maxWidth: .infinity, alignment: .leading)+ Button { closeOverview() } label: { barIcon("xmark") }+ .buttonStyle(.plain)+ .glassCircle()+ .accessibilityLabel(tr("done"))+ } else {+ tabStrip.frame(maxWidth: .infinity, alignment: .leading)+ }+ }+ // The screen's left side is the sidebar's while it stays there.+ .padding(.leading, max(10, wide && sidebarPinned ? 0 : topRoom.leading))+ .padding(.trailing, max(10, topRoom.trailing))+ .frame(height: Self.barHeight)+ .padding(.top, max(0, topRoom.top))+ .contentShape(Rectangle())+ // Pinching the bar zooms out to the overview.+ .gesture(MagnifyGesture().onEnded { value in+ if value.magnification < 0.8 { openOverview() }+ })+ // The text follows the system's size, as far as the bar holds it.+ .dynamicTypeSize(...DynamicTypeSize.xxLarge)+ }++ private func barIcon(_ name: String) -> some View {+ Image(systemName: name)+ .font(.body.weight(.semibold))+ .foregroundColor(cardsAlpha > 0 ? .white : model.ink)+ .frame(width: 42, height: 42)+ .contentShape(Circle())+ }++ private var content: some View {ZStack(alignment: .topLeading) {if overviewVisible {OverviewScreen(- model: model, isPresented: $overviewShown, cardFrame: $cardFrame,- liveThread: currentThreadId, livePreview: livePreview,- onPick: { thread, frames in if let frames { picked = (thread, frames) } }+ model: model, stage: terminalFrame.size, liveThread: liveThread, liveShown: liveShown,+ onThumb: { noteThumb($0, $1) }, onPick: { pick($0) }, onClose: { closeOverview() })- .opacity(gridOpacity)- .onChange(of: overviewShown) { _, shown in if !shown { closeOverview() } }+ .opacity(cardsAlpha)+ .allowsHitTesting(overviewOpen)}- // The card's own header rides along with the terminal: laid out at- // the card's size, blown up to the terminal's width, and shrunk- // with the same zoom, so the whole card closes in.- if let hero = heroFrames, let thread = heroThread {- let sEnd = hero.thumb.width / max(terminalFrame.width, 1)- ThreadCardHeader(thread: thread)- .frame(width: hero.card.width, height: hero.thumb.minY - hero.card.minY, alignment: .top)- .background(Color(red: 0.10, green: 0.11, blue: 0.13))- .clipShape(UnevenRoundedRectangle(topLeadingRadius: 13, topTrailingRadius: 13))- .scaleEffect(1 / sEnd, anchor: .topLeading)- .scaleEffect(heroScale, anchor: .topLeading)- .offset(heroOffset)- .opacity(heroAlpha * zoomFade)- .zIndex(3)- .allowsHitTesting(false)- // The moving card's border, around header and terminal slice- // together; the card's own border waits until it has landed.- RoundedRectangle(cornerRadius: 13)- .stroke(Color.accentColor, lineWidth: 2)- .frame(width: hero.card.width, height: heroFrameHeight)- .scaleEffect(1 / sEnd, anchor: .topLeading)- .scaleEffect(heroScale, anchor: .topLeading)- .offset(heroOffset)- .opacity(heroAlpha * zoomFade)- .zIndex(3)- .allowsHitTesting(false)- }- // Above the cards, so the shrunken terminal shows in its card;- // untouchable meanwhile, so the cards get the taps.+ // Above the cards, so the terminal shows on its way into its+ // card; untouchable meanwhile, so the cards get the taps.VStack(spacing: 0) {- if twoLevel {- tabSubstrip.opacity(overviewOpen ? 0 : 1)- }terminal- .background(GeometryReader { geo in- Color.clear- .onAppear { terminalFrame = geo.frame(in: .named("screen")) }- .onChange(of: geo.frame(in: .named("screen"))) { _, f in terminalFrame = f }- })- .mask(alignment: .bottom) {- // The card's own corners, once the terminal is in it.- UnevenRoundedRectangle(bottomLeadingRadius: 13 / zoomScale, bottomTrailingRadius: 13 / zoomScale)- .frame(height: zoomClip)- }- .scaleEffect(zoomScale, anchor: .topLeading)- .offset(zoomOffset)- .opacity(zoomFade)+ .opacity(terminalAlpha)+ .onGeometryChange(for: CGRect.self) { $0.frame(in: .named("screen")) } action: { terminalFrame = $0 }+ .onGeometryChange(for: ClosedRange<CGFloat>.self) { geo in+ let frame = geo.frame(in: .global)+ return frame.minY...max(frame.minY, frame.maxY)+ } action: { terminalSpan = $0 }.zIndex(2)- .allowsHitTesting(!overviewOpen)statusLine.opacity(overviewOpen ? 0 : 1)if (keyboardUp || model.panelOpen) && !overviewOpen {// With the keyboard down the bar sits on the home@@ -124,57 +340,52 @@ struct TerminalScreen: View {.animation(.easeOut(duration: 0.2), value: keyboardUp).animation(.easeOut(duration: 0.2), value: model.panelOpen).zIndex(1)- .allowsHitTesting(!overviewOpen)- }- .overlay {- SidebarPanel(- model: model,- isPresented: $showTree,- hostName: hostName,- connected: connected,- onEditHost: { showTree = false; editingHost = model.host },- onSettings: { showTree = false; showSettings = true },- onOverview: { showTree = false; openOverview() }- )+ .allowsHitTesting(!overviewVisible)+ // A picture of the terminal on its way into a card or out of one.+ Flyway(flight: flight)+ .allowsHitTesting(false)+ .zIndex(3)}.coordinateSpace(name: "screen")- .background(overviewOpen ? Color(white: 0.06) : model.background)- .background(GeometryReader { geo in- Color.clear.onAppear { barWidth = geo.size.width }- .onChange(of: geo.size.width) { _, w in barWidth = w }- })+ .background(cardsAlpha > 0 ? OverviewScreen.backdrop : model.background).onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)) { note inlet frame = (note.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect) ?? .zero- keyboardUp = frame.height > 0+ // The sidebar's search has a keyboard too, and no key bar.+ keyboardUp = frame.height > 0 && model.inputView?.isFirstResponder == true+ // The terminal's back before the overview it was put away for.+ if keyboardUp { moves.waiting = false }}.onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)) { _ inkeyboardUp = false}- .onChange(of: cardFrame) { _, frames in- // The card's thumbnail is laid out: the terminal goes there --- // even when it came late and the overview opened without it.- if overviewShown, let frames, heroFrames == nil { zoom(into: frames) }+ .onChange(of: landingThumb) { _, thumb in+ // The cards are laid out (or the card moved, scrolled into+ // sight), even after the picture got where they were thought to+ // be: it goes on to the card, and the cards come out from under+ // the cover.+ guard let thumb, overviewOpen, !liveShown, !moves.closing else { return }+ flyIn(to: thumb)+ flight.fadeCover(to: 0, duration: 0.3)}- .navigationBarTitleDisplayMode(.inline)- .toolbar(.hidden, for: .tabBar)- .toolbarBackground(model.background, for: .navigationBar)- .toolbarBackground(.visible, for: .navigationBar)- .toolbar {- // The strip takes the bar from the two leading buttons to the- // trailing margin: nothing sits at the right any more.- ToolbarItem(placement: .principal) { tabStrip.frame(width: max(barWidth - 140, 120)) }- ToolbarItem(placement: .topBarLeading) {- // The desktop's sidebar: the projects and threads, as a- // panel; the keyboard goes first, or the panel sits on it.- Button { model.dismissKeyboard(); showTree = true } label: { Image(systemName: "sidebar.left") }+ .onChange(of: livePicture) { _, _ in fadeIntoCard() }+ .onChange(of: currentThreadId) { _, now in+ if overviewOpen, !moves.closing, let now, now != liveThread,+ let thread = model.threads?.threads.first(where: { $0.id == now }) {+ // Another thread picked elsewhere (the sidebar): it is the+ // one the overview closes into.+ pick(thread)+ } else if moves.picked != nil {+ // The picked thread is the terminal's now; its first frame+ // follows.+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) { revealPicked(force: false) }}}- .ignoresSafeArea(.container, edges: .bottom).sheet(item: $model.pendingHostKey) { challenge inScrollView {VStack(alignment: .leading, spacing: 20) {Text(tr("hostkey.approve.title")).font(.headline)- Text("\(challenge.hostname):\(challenge.port)")+ // Verbatim: an interpolated number is localised, "2,299".+ Text(verbatim: "\(challenge.hostname):\(challenge.port)")Text(challenge.fingerprint).font(.system(.body, design: .monospaced)).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)Text(tr("hostkey.approve.body"))@@ -188,29 +399,72 @@ struct TerminalScreen: View {}.sheet(isPresented: $showSettings) {NavigationStack {- SettingsView(model: model, showLog: $showLog)+ SettingsView(showLog: $showLog).toolbar {ToolbarItem(placement: .confirmationAction) { Button(tr("done")) { showSettings = false } }}}}- .onChange(of: showLog) { _, on in model.wantsStats = on }- .sheet(item: $menu) { sheet in- MenuList(model: model, sheet: sheet) { menu = nil }- .presentationDetents([.medium, .large])+ .onChange(of: showLog) { _, on in model.logShown = on }+ .onChange(of: model.sidebar?.editing) { _, editing in+ // A new project has no id yet: the same field, asking for the+ // name of what is about to exist.+ guard let editing, editing.kind != "none" else { return }+ if renaming == nil {+ renameText = ""+ renaming = (editing.kind, editing.id ?? "")+ }+ }+ .onChange(of: model.nameAsks) { _, _ in+ // "+" asks at once, even while the core still asks from before.+ renameText = ""+ renaming = ("new-project", "")+ }+ .onChange(of: model.sidebar?.new_project_error) { _, error in+ // A folder the core refused: asked again, with why.+ if error != nil, model.sidebar?.editing.kind == "new-project", renaming == nil {+ renaming = ("new-project", "")+ }+ }+ .alert(+ renaming?.kind == "new-project" ? tr("project.new") : tr("rename"),+ isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })+ ) {+ // A new project is a folder on the host, ~/dir or /dir.+ TextField(renaming?.kind == "new-project" ? "~/" : tr("f.name"), text: $renameText)+ .textInputAutocapitalization(.never)+ .autocorrectionDisabled()+ Button(tr("save")) {+ model.sideKey("Enter", value: renameText)+ renaming = nil+ }+ Button(tr("cancel"), role: .cancel) {+ model.sideKey("Escape", value: "")+ renaming = nil+ }+ } message: {+ if renaming?.kind == "new-project", let error = model.sidebar?.new_project_error {+ Text(error)+ }}.confirmationDialog(- tr("thread.delete.title", deletingThread?.name ?? ""),- isPresented: Binding(get: { deletingThread != nil }, set: { if !$0 { deletingThread = nil } }),- titleVisibility: .visible,- presenting: deletingThread- ) { thread in+ tr("thread.delete.title", threadName(model.confirming?.split(separator: ":", maxSplits: 1).last.map(String.init) ?? "")),+ isPresented: Binding(get: { model.confirming != nil }, set: { if !$0 { model.confirming = nil } }),+ titleVisibility: .visible+ ) {// Deleting ends every program in the thread: it is asked first.- Button(tr("delete"), role: .destructive) { model.sideClick("delete", id: thread.id) }- Button(tr("cancel"), role: .cancel) {}- } message: { _ in+ Button(tr("delete"), role: .destructive) {+ if let action = model.confirming { model.menuAction(action) }+ model.confirming = nil+ }+ Button(tr("cancel"), role: .cancel) { model.confirming = nil }+ } message: {Text(tr("thread.delete.body"))}+ .sheet(item: $menu) { sheet in+ MenuList(model: model, sheet: sheet) { menu = nil }+ .presentationDetents([.medium, .large])+ }.sheet(item: $editingHost) { host inHostEditView(host: host) { edited, secret, passphrase inif !secret.isEmpty { Keychain.save(secret, account: edited.id.uuidString) }@@ -221,25 +475,51 @@ struct TerminalScreen: View {}}.onAppear {+ moves.onScreen = truemodel.enterScreen()// The automated flows connect on their own schedule; a session// found open is simply shown.- let args = ProcessInfo.processInfo.arguments- if !args.contains(where: { $0.hasSuffix("test") || $0 == "--autoconnect" }), !model.isConnected {+ if !TerminalModel.automated, !model.isConnected {model.connect()}#if DEBUG- // Screenshots of the sheets, which no script can tap open.- if args.contains("--open-tree") {- DispatchQueue.main.asyncAfter(deadline: .now() + 14) { showTree = true }+ let args = ProcessInfo.processInfo.arguments+ // When a flag fires: the seconds after it, if given.+ func when(_ flag: String, _ otherwise: Double) -> Double? {+ guard let at = args.firstIndex(of: flag) else { return nil }+ return at + 1 < args.count ? Double(args[at + 1]) ?? otherwise : otherwise+ }+ // On time: the system lets a long wait run late by up to a+ // tenth of it, which would run two flags a moment apart as one.+ // Not once the screen is gone.+ func after(_ seconds: Double, _ work: @escaping () -> Void) {+ let timer = DispatchSource.makeTimerSource(queue: .main)+ timer.schedule(deadline: .now() + seconds, leeway: .milliseconds(1))+ timer.setEventHandler {+ if moves.onScreen { work() }+ timer.cancel()+ }+ timer.resume()}- if args.contains("--open-overview") {- DispatchQueue.main.asyncAfter(deadline: .now() + 14) { openOverview() }+ // Screenshots of the sheets, which no script can tap open.+ if let t = when("--open-tree", 14) { after(t) { showSidebar() } }+ if let t = when("--open-overview", 14) { after(t) { openOverview() } }+ // The overview's ways back: a running thread's card by its+ // place among them, or the close button.+ if let at = args.firstIndex(of: "--overview-pick"), at + 1 < args.count, let n = Int(args[at + 1]) {+ after(17) {+ let running = (model.threads?.threads ?? []).filter(\.live)+ if running.indices.contains(n) { pick(running[n]) }+ }}+ if let t = when("--overview-close", 17) { after(t) { closeOverview() } }#endif}.onDisappear {- // The picture goes, the connection stays (see Sessions).+ // The picture goes, the connection stays (see Sessions), and an+ // overview left open, or on its way, lets its screens go.+ moves.onScreen = false+ overviewClosed()model.leaveScreen()}}@@ -261,113 +541,98 @@ struct TerminalScreen: View {return .red}- /// The desktop's two layers, as two rows: threads (the sidebar's- /// layer, one per workspace) in the navigation bar, the current- /// thread's tabs in a strip under it. A server without threads (no- /// session state) shows its tabs in the bar instead.- private var twoLevel: Bool { settings.tabBarLevels == "two" && !(model.threads?.threads.isEmpty ?? true) }-+ /// The current thread's tabs, as the desktop's bar has them; the+ /// threads are the sidebar's.private var tabStrip: some View {- HStack(spacing: 2) {- ScrollViewReader { reader in+ let current = model.tabs?.tabs.first(where: { $0.current })?.tab+ return ScrollViewReader { reader inScrollView(.horizontal, showsIndicators: false) {- HStack(spacing: 4) {- if twoLevel {- ForEach(model.threads?.threads ?? []) { thread in- Button {- // The one on show opens the tree; another is shown.- if thread.current { showTree = true } else { model.sideClick("thread", id: thread.id) }- } label: {- HStack(spacing: 5) {- Circle().fill(threadColor(thread)).frame(width: 6, height: 6)- Text(thread.name)- .font(.system(size: 12, weight: thread.current ? .semibold : .regular))- .lineLimit(1)- if thread.current {- closeX { deletingThread = thread }- }- }- .padding(.leading, 10)- .padding(.trailing, thread.current ? 4 : 10)- .frame(minWidth: 64, minHeight: 26)- .background(thread.current ? Color.white.opacity(0.18) : Color.white.opacity(0.06))- .clipShape(Capsule())- }- .buttonStyle(.plain)- .contextMenu {- AppMenuItems(model: model, kind: "thread", id: thread.id)- }- .id("thread:" + thread.id)- }- Button { model.sideClick("new-thread") } label: {- Image(systemName: "plus").font(.system(size: 13, weight: .semibold)).padding(6)- .foregroundColor(Color.white.opacity(0.62))- }- .buttonStyle(.plain)- } else {- tabPills(size: 12, height: 26)- newTabButton- }+ // As tall as the round buttons beside them, in their glass.+ HStack(spacing: 8) {+ tabPills(height: 42)+ newTabButton}+ // A scroll comes to rest with a whole pill at the start.+ .scrollTargetLayout()+ .glassGroup(spacing: 8)}- .onChange(of: model.threads?.threads.first(where: { $0.current })?.id) { _, id in- if let id { reader.scrollTo("thread:" + id, anchor: .center) }+ .scrollTargetBehavior(.viewAligned)+ // The glass swells as it is pressed, above and below the strip;+ // at its ends the tabs scrolled off it are cut, not drawn over+ // the buttons before it, and fade out on their way there.+ .scrollClipDisabled()+ .clipShape(SideClip())+ .onScrollGeometryChange(for: StripEnds.self) { geo in+ StripEnds(before: geo.visibleRect.minX > 1, after: geo.visibleRect.maxX < geo.contentSize.width - 1)+ } action: { _, ends in+ stripEnds = ends}- .onChange(of: model.tabs?.tabs.first(where: { $0.current })?.tab) { _, tab in- if let tab, !twoLevel { reader.scrollTo("tab:\(tab)", anchor: .center) }+ .overlay { stripFades }+ .onAppear {+ // First shown, or back from the overview: the current tab+ // at the start, once the strip is laid out.+ DispatchQueue.main.async {+ if let current { reader.scrollTo("tab:\(current)", anchor: .leading) }+ }}+ .onChange(of: current) { _, tab in+ // A new tab's pill is laid out in this same pass: at the+ // start once it is.+ DispatchQueue.main.async {+ if let tab { reader.scrollTo("tab:\(tab)", anchor: .leading) }+ }}}- .foregroundColor(.white)+ .foregroundColor(model.ink)}- /// The current thread's tabs, under the bar.- private var tabSubstrip: some View {- HStack(spacing: 4) {- ScrollViewReader { reader in- ScrollView(.horizontal, showsIndicators: false) {- HStack(spacing: 4) {- tabPills(size: 11.5, height: 22)- }- }- .onChange(of: model.tabs?.tabs.first(where: { $0.current })?.tab) { _, tab in- if let tab { reader.scrollTo("tab:\(tab)", anchor: .center) }- }- }- newTabButton+ /// The bar's ground over the strip's ends where tabs lie past them, so+ /// they fade out there rather than end in a cut; an end with nothing+ /// past it stays sharp.+ private var stripFades: some View {+ let ground = cardsAlpha > 0 ? OverviewScreen.backdrop : model.background+ return HStack(spacing: 0) {+ LinearGradient(colors: [ground, ground.opacity(0)], startPoint: .leading, endPoint: .trailing)+ .frame(width: Self.stripFade)+ .opacity(stripEnds.before ? 1 : 0)+ Spacer(minLength: 0)+ LinearGradient(colors: [ground.opacity(0), ground], startPoint: .leading, endPoint: .trailing)+ .frame(width: Self.stripFade)+ .opacity(stripEnds.after ? 1 : 0)}- .foregroundColor(.white)- .padding(.horizontal, 8)- .frame(height: 32)- .contentShape(Rectangle())- // Pinching the strip zooms out to the overview.- .gesture(MagnifyGesture().onEnded { value in- if value.magnification < 0.8 { openOverview() }- })- .background(model.background)+ .animation(.easeOut(duration: 0.15), value: stripEnds)+ .allowsHitTesting(false)}- private func tabPills(size: CGFloat, height: CGFloat) -> some View {+ /// The tabs as the desktop's capsules: the card of what each runs at+ /// the left, round within the capsule's round end, then its name.+ private func tabPills(height: CGFloat) -> some View {ForEach(model.tabs?.tabs ?? []) { tab inButton {model.chromeClick("pane", pane: tab.target)} label: {- HStack(spacing: 4) {- Text(tab.label.isEmpty ? tr("tab.num", tab.tab) : tab.label)- .font(.system(size: size, weight: tab.current ? .semibold : .regular))- .lineLimit(1)- if tab.current {- closeX { model.chromeClick("close-tab", tab: tab.tab) }+ // A window tab wears the terminal's card, as on the+ // desktop; what each pane runs is on its capsule.+ let icon = model.tabs?.icon+ AtMost(width: 180) {+ HStack(spacing: 8) {+ TabIconCard(core: model.core, id: icon, size: height - 12, revision: model.iconsRevision)+ Text(tab.label.isEmpty ? tr("tab.num", tab.tab) : tab.label)+ .font(.subheadline.weight(tab.current ? .semibold : .regular))+ .lineLimit(1)+ if tab.current {+ closeX { model.chromeClick("close-tab", tab: tab.tab) }+ }}+ .padding(.leading, icon == nil ? 14 : 6)+ .padding(.trailing, tab.current ? 6 : 14)}- .padding(.leading, 10)- .padding(.trailing, tab.current ? 4 : 10)- .frame(minWidth: 76, maxWidth: 160, minHeight: height)- .foregroundColor(tab.current ? .white : Color.white.opacity(0.62))- .background(tab.current ? Color.white.opacity(0.18) : Color.white.opacity(0.06))- .clipShape(Capsule())+ .frame(minWidth: 76, minHeight: height)+ .foregroundColor(tab.current ? model.ink : model.ink.opacity(0.62))+ .contentShape(Capsule())}.buttonStyle(.plain)+ .glassPill(lit: tab.current, ink: model.ink).contextMenu {AppMenuItems(model: model, kind: "tab", id: String(tab.tab))}@@ -379,9 +644,9 @@ struct TerminalScreen: View {private func closeX(_ action: @escaping () -> Void) -> some View {Button(action: action) {Image(systemName: "xmark")- .font(.system(size: 9, weight: .bold))- .foregroundColor(Color.white.opacity(0.7))- .frame(width: 18, height: 18)+ .font(.system(size: 11, weight: .bold))+ .foregroundColor(model.ink.opacity(0.7))+ .frame(width: 30, height: 30).contentShape(Circle())}.buttonStyle(.plain)@@ -389,173 +654,303 @@ struct TerminalScreen: View {/// "+" opens a tab; held, it offers the splits too.private var newTabButton: some View {- Button { model.chromeClick("new-tab") } label: {- Image(systemName: "plus").font(.system(size: 13, weight: .semibold)).padding(6)- .foregroundColor(Color.white.opacity(0.62))- }- .buttonStyle(.plain)- .contextMenu {- Button(tr("newtab")) { model.chromeClick("new-tab") }- Button(tr("split.right")) { model.chromeClick("split-right") }- Button(tr("split.below")) { model.chromeClick("split-below") }- }- }-- static func threadColor(status: String, live: Bool) -> Color {- switch status {- case "Running": return .green- case "NeedsAttention": return .orange- case "Done": return .blue- default: return live ? .gray : .gray.opacity(0.4)- }+ Button { model.chromeClick("new-tab") } label: { barIcon("plus") }+ .buttonStyle(.plain)+ .glassCircle()+ .accessibilityLabel(tr("newtab"))+ .contextMenu {+ Button(tr("newtab")) { model.chromeClick("new-tab") }+ Button(tr("split.right")) { model.chromeClick("split-right") }+ Button(tr("split.below")) { model.chromeClick("split-below") }+ }}- private func threadColor(_ t: ThreadView) -> Color { Self.threadColor(status: t.status, live: t.live) }-- // MARK: the overview's zoom+ // MARK: the overviewprivate var currentThreadId: String? { model.threads?.threads.first(where: { $0.current })?.id }- /// The cards' opacity follows the zoom itself, so no frame shows the- /// cards before the terminal has begun to shrink (or after it has- /// begun to grow back): one curve for both.- private var gridOpacity: Double {- guard overviewOpen else { return 0 }- guard let hero = heroFrames, terminalFrame.width > 0 else { return 1 }- let end = hero.thumb.width / terminalFrame.width- guard end < 0.999 else { return 1 }- return min(max((1 - zoomScale) / (1 - end), 0), 1)+ /// Where the live card's picture is, its pane, and whether its+ /// picture is drawn.+ private var liveThumb: CGRect? { liveThread.flatMap { moves.thumbs[$0] } }+ private var livePane: Int? {+ liveThread.flatMap { id in model.threads?.threads.first(where: { $0.id == id }) }.flatMap(OverviewScreen.pane(of:))+ }+ private var livePicture: Bool { livePane.flatMap { model.pictures[$0] } != nil }++ /// A card's picture moved (laid out, scrolled): kept for the flights,+ /// and the live one's followed while the terminal is on its way in.+ private func noteThumb(_ id: String, _ rect: CGRect) {+ moves.thumbs[id] = rect+ if id == liveThread, overviewOpen, !liveShown, !moves.closing { landingThumb = rect }}/// The home indicator's inset, for a bar that sits at the bottom/// while the keyboard is down.- private static var bottomInset: CGFloat {+ static var bottomInset: CGFloat {UIApplication.shared.connectedScenes.compactMap { ($0 as? UIWindowScene)?.keyWindow }.first?.safeAreaInsets.bottom ?? 0}+ /// Into the overview. The terminal as it is flies off at once, for+ /// where its card is bound to be, over a cover under which the cards+ /// are made; Core Animation keeps it going while they are, and the+ /// cards come out from under the cover once they are laid out.private func openOverview() {- guard !overviewShown else { return }- model.refreshViews()- overviewShown = true- if overviewVisible, let frames = cardFrame {- // The cards are still up from a close a moment ago and will- // not lay out again: the frames they last reported serve.- zoom(into: frames)+ guard !overviewVisible, !flight.flying, !moves.waiting else {+ // Asked again from the drawer, or while it slides away: only+ // the drawer goes.+ if drawerOpen { showTree = false }+ return+ }+ guard drawerOpen || keyboardUp || model.panelOpen else { return zoomOut() }+ // The terminal back in its place, uncovered and at its full height,+ // first: the cards have its shape, and it flies from where it shows.+ model.dismissKeyboard()+ model.panelOpen = false+ moves.waiting = true+ let turn = moves.turn+ // Once; not if the drawer, the keyboard or the keys came back+ // meanwhile, or the screen went.+ let go = {+ guard turn == moves.turn, moves.waiting else { return }+ moves.waiting = false+ guard moves.onScreen, !drawerOpen, edgePull == 0, model.inputView?.isFirstResponder != true, !model.panelOpen else { return }+ zoomOut()+ }+ if drawerOpen {+ // Once the screen has slid back over the drawer, not while it+ // shows short of where it is laid out (a busy main thread+ // starts the slide late); a slide that never says it is done+ // waits no longer than a second.+ var back = Transaction(animation: Self.slide)+ back.addAnimationCompletion(criteria: .logicallyComplete, go)+ withTransaction(back) { showTree = false }+ DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: go)} else {- cardFrame = nil+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.4, execute: go)}- overviewVisible = true- // Without a card of its own (no threads, or none current) the- // terminal only fades.- if currentThreadId == nil {- withAnimation(.easeOut(duration: 0.25)) { overviewOpen = true }+ }++ /// The terminal, where it shows uncovered, off into its card.+ private func zoomOut() {+ let running = (model.threads?.threads ?? []).filter(\.live)+ let live = running.first(where: \.current)+ moves.turn += 1+ moves.landed = false+ let turn = moves.turn+ if let live, let index = running.firstIndex(of: live), terminalFrame.height > 0,+ let shot = flight.snapshot(terminalFrame) {+ flight.cover(UIColor(OverviewScreen.backdrop), alpha: 1)+ flight.begin(with: shot, frame: terminalFrame, at: terminalFrame, radius: 0)+ flyIn(to: OverviewScreen.estimatedThumb(+ index: index, count: running.count, width: terminalFrame.width, aspect: terminalFrame.width / terminalFrame.height+ ))+ CATransaction.flush()}- // A card the lazy grid never realises reports nothing; the- // overview must not stay invisible for it. After a moment, the- // terminal only fades.- DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {- if overviewShown && !overviewOpen {- withAnimation(.easeOut(duration: 0.25)) { overviewOpen = true }+ // The cards, after the flight is under way.+ DispatchQueue.main.async {+ guard turn == moves.turn else { return }+ model.refreshViews()+ model.keepScreens()+ liveThread = live?.id+ if let pane = live.flatMap(OverviewScreen.pane(of:)) { model.requestScreen(pane: pane) }+ moves.thumbs = [:]+ landingThumb = nil+ liveShown = false+ overviewOpen = true+ overviewVisible = true+ if flight.flying {+ // Under the cover already: gone at once, so the cover+ // fading off the cards shows no trace of it.+ terminalAlpha = 0+ withAnimation(.easeOut(duration: 0.3)) { cardsAlpha = 1 }+ } else {+ // Nothing flies over the live card: its picture shows.+ withAnimation(.easeOut(duration: 0.3)) {+ terminalAlpha = 0+ cardsAlpha = 1+ }+ moves.landed = true+ liveShown = true}}+ // Cards that never say where they are show all the same.+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) {+ guard turn == moves.turn, overviewOpen, !liveShown, landingThumb == nil else { return }+ moves.landed = true+ liveShown = true+ flight.fadeOut(duration: 0.2) {}+ }}- /// Shrink the terminal into the card's thumbnail: scaled to its- /// width, moved into it, and masked to its height from the bottom,- /// so the card keeps the newest rows as the other cards' previews do.- private func zoom(into frames: CardFrames) {- guard terminalFrame.width > 0 else { return }- let frame = frames.thumb- let scale = frame.width / terminalFrame.width- let clip = frame.height / scale- // The header starts above the terminal, at the terminal's width,- // and lands on the card's own header.- let headerH = frame.minY - frames.card.minY- heroFrames = frames- heroThread = model.threads?.threads.first(where: { $0.id == currentThreadId })- heroScale = 1- heroOffset = CGSize(width: terminalFrame.minX, height: terminalFrame.minY - headerH / scale)- heroFrameHeight = headerH + terminalFrame.height * scale- heroAlpha = 0- withAnimation(.spring(response: 0.4, dampingFraction: 0.85)) {- overviewOpen = true- zoomScale = scale- zoomOffset = CGSize(- width: frame.minX - terminalFrame.minX,- height: frame.minY - terminalFrame.minY - (terminalFrame.height - clip) * scale- )- zoomClip = clip- heroScale = scale- heroOffset = CGSize(width: frames.card.minX, height: frames.card.minY)- heroFrameHeight = frames.card.height- heroAlpha = 1- }- DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {- guard overviewOpen else { return }- withAnimation(.easeOut(duration: 0.18)) { zoomFade = 0 }- DispatchQueue.main.asyncAfter(deadline: .now() + 0.18) {- if overviewOpen { withAnimation(.easeOut(duration: 0.15)) { livePreview = true } }+ private func flyIn(to thumb: CGRect) {+ let turn = moves.turn+ flight.move(to: thumb, radius: OverviewScreen.thumbRadius, duration: 0.45) {+ guard turn == moves.turn else { return }+ moves.landed = true+ fadeIntoCard()+ // A picture that never comes (the server could not say) leaves+ // the card's own background there.+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {+ if turn == moves.turn { fadeIntoCard(force: true) }}}}- /// Back to the terminal. A tapped card was kept by onPick: the- /// terminal grows out of that card, not the one it came from.+ /// The card's picture under the terminal's, which fades off it.+ private func fadeIntoCard(force: Bool = false) {+ guard overviewOpen, moves.landed, !moves.closing, !liveShown, livePicture || force else { return }+ liveShown = true+ let turn = moves.turn+ DispatchQueue.main.async {+ if turn == moves.turn { flight.fadeOut(duration: 0.2) {} }+ }+ }++ /// A card's picture as a view to fly out of it, at once; drawn again+ /// at the terminal's size off the main thread and put in when it is,+ /// on the way.+ private func flyingPicture(of pane: Int) -> UIView? {+ guard let card = model.pictures[pane], terminalFrame.width > 0 else { return nil }+ let scale = displayScale+ let view = UIImageView(image: UIImage(cgImage: card, scale: scale, orientation: .up))+ view.contentMode = .scaleToFill+ view.backgroundColor = UIColor(model.screens[pane].flatMap { Color(hex: $0.background) } ?? model.background)+ model.paint(pane: pane, pixels: CGSize(width: terminalFrame.width * scale, height: terminalFrame.height * scale)) {+ [weak view] full in view?.image = UIImage(cgImage: full, scale: scale, orientation: .up)+ }+ return view+ }++ /// Back into the thread on show: its picture lifts off its card and+ /// grows to the screen as the cards go under the cover, and the+ /// terminal takes over (`flyBack`).private func closeOverview() {- if let pick = picked, terminalFrame.width > 0 {- picked = nil- let frame = pick.frames.thumb- let scale = frame.width / terminalFrame.width- let clip = frame.height / scale- // Placed in the new card without animation: nothing shows yet.- var t = Transaction(); t.disablesAnimations = true- withTransaction(t) {- heroFrames = pick.frames- heroThread = pick.thread- zoomScale = scale- zoomOffset = CGSize(- width: frame.minX - terminalFrame.minX,- height: frame.minY - terminalFrame.minY - (terminalFrame.height - clip) * scale- )- zoomClip = clip- heroScale = scale- heroOffset = CGSize(width: pick.frames.card.minX, height: pick.frames.card.minY)- heroFrameHeight = pick.frames.card.height- }+ guard overviewOpen, !moves.closing else { return }+ moves.turn += 1+ moves.closing = true+ let turn = moves.turn+ let backdrop = UIColor(OverviewScreen.backdrop)+ if !moves.landed && flight.flying {+ // Still on its way in: it turns back.+ flight.fadeCover(to: 1, duration: 0.2)+ flight.move(to: terminalFrame, radius: 0, duration: 0.35) { flyBack(turn) }+ } else if let thumb = liveThumb, let pane = livePane, let picture = flyingPicture(of: pane) {+ flight.cover(backdrop, alpha: 0)+ flight.begin(with: picture, frame: terminalFrame, at: thumb, radius: OverviewScreen.thumbRadius)+ flight.fadeCover(to: 1, duration: 0.3)+ flight.move(to: terminalFrame, radius: 0, duration: 0.4) { flyBack(turn) }+ } else {+ fadeBack(turn)+ return}- withAnimation(.easeOut(duration: 0.1)) { livePreview = false }- withAnimation(.easeOut(duration: 0.15)) { zoomFade = 1 }- DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) {- // Opened again already: the zoom in progress is the new one's.- guard !overviewShown else { return }- withAnimation(.spring(response: 0.35, dampingFraction: 0.9)) {- overviewOpen = false- zoomScale = 1- zoomOffset = .zero- zoomClip = nil- heroScale = 1- heroAlpha = 0- if let hero = heroFrames {- let sEnd = hero.thumb.width / max(terminalFrame.width, 1)- let headerH = hero.thumb.minY - hero.card.minY- heroOffset = CGSize(width: terminalFrame.minX, height: terminalFrame.minY - headerH / sEnd)- heroFrameHeight = headerH + terminalFrame.height * sEnd- }+ CATransaction.flush()+ }++ /// Nothing to fly: the terminal fades back over the cards, its bar+ /// back at once.+ private func fadeBack(_ turn: Int) {+ flight.end()+ overviewOpen = false+ withAnimation(.easeOut(duration: 0.25)) {+ terminalAlpha = 1+ cardsAlpha = 0+ } completion: {+ if turn == moves.turn { overviewClosed() }+ }+ }++ /// A card tapped. The thread on show comes back as `closeOverview`+ /// has it; another's picture leaves its card and grows to the screen,+ /// and the terminal takes over from it once it shows that thread+ /// (`revealPicked`).+ private func pick(_ thread: ThreadView) {+ guard overviewOpen, !moves.closing else { return }+ if thread.id == liveThread {+ closeOverview()+ return+ }+ if currentThreadId != thread.id { model.sideClick("thread", id: thread.id) }+ moves.turn += 1+ moves.closing = true+ moves.grown = false+ moves.picked = thread.id+ let turn = moves.turn+ guard let thumb = moves.thumbs[thread.id], let pane = OverviewScreen.pane(of: thread),+ let picture = flyingPicture(of: pane) else {+ // Its picture not drawn yet: none flies, not even the thread+ // on show's, and the terminal fades back once it shows this one.+ flight.end()+ moves.grown = true+ if currentThreadId == thread.id {+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) { revealPicked(force: false) }+ }+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {+ if turn == moves.turn { revealPicked(force: true) }}+ return+ }+ flight.cover(UIColor(OverviewScreen.backdrop), alpha: 0)+ flight.begin(with: picture, frame: terminalFrame, at: thumb, radius: OverviewScreen.thumbRadius)+ flight.fadeCover(to: 1, duration: 0.3)+ flight.move(to: terminalFrame, radius: 0, duration: 0.42) {+ guard turn == moves.turn else { return }+ moves.grown = true+ revealPicked(force: false)}- DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {- if !overviewShown {- overviewVisible = false- heroFrames = nil- // The cards go with the grid; the next open lays them out- // again and hears their frames afresh.- cardFrame = nil+ CATransaction.flush()+ // A switch that never shows ends the wait all the same.+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {+ if turn == moves.turn { revealPicked(force: true) }+ }+ }++ private func revealPicked(force: Bool) {+ guard let picked = moves.picked else { return }+ guard force || (moves.grown && currentThreadId == picked) else { return }+ moves.picked = nil+ flyBack(moves.turn)+ }++ /// The picture fills the screen: the terminal and its bar come back+ /// under it, the picture fades off it, and the cards are taken down+ /// after, out of sight under the terminal.+ private func flyBack(_ turn: Int) {+ guard turn == moves.turn else { return }+ guard flight.flying else { return fadeBack(turn) }+ terminalAlpha = 1+ cardsAlpha = 0+ overviewOpen = false+ DispatchQueue.main.async {+ guard turn == moves.turn else { return }+ flight.fadeOut(duration: 0.15) {+ if turn == moves.turn { overviewClosed() }}}}+ /// The cards are gone: the overview lets go of what it held, and what+ /// was set to run on its way in or out finds itself overtaken.+ private func overviewClosed() {+ moves.turn += 1+ moves.waiting = false+ flight.end()+ overviewOpen = false+ overviewVisible = false+ liveThread = nil+ liveShown = false+ moves.thumbs = [:]+ landingThumb = nil+ terminalAlpha = 1+ cardsAlpha = 0+ moves.landed = false+ moves.closing = false+ moves.grown = false+ moves.picked = nil+ model.releaseScreens()+ }+// MARK: the terminal with its overlaysprivate var terminal: some View {@@ -595,7 +990,7 @@ struct TerminalScreen: View {// Asked not to redial: the card offers it instead.ConnectionCard(phase: .disconnected, hostName: hostName, canEdit: model.host != nil) { action inswitch action {- case .back: dismiss()+ case .back: leave()default: model.connect()}}@@ -611,7 +1006,7 @@ struct TerminalScreen: View {}model.connect()case .edit: editingHost = model.host- case .back: dismiss()+ case .back: leave()}}}@@ -661,16 +1056,21 @@ struct TerminalScreen: View {model.chromeClick("pane", pane: member.pane)} label: {HStack(spacing: 4) {- if member.busy {+ if member.icon != nil {+ TabIconCard(+ core: model.core, id: member.icon, size: 15, busy: member.busy,+ revision: model.iconsRevision+ )+ } else if member.busy {ProgressView().controlSize(.mini)}Text(member.title.isEmpty ? "shell" : member.title).lineLimit(1)- .font(.system(size: 11, weight: member.current ? .semibold : .regular))+ .font(.caption2.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)+ .background(member.current ? model.ink.opacity(nav.focused ? 0.22 : 0.12) : Color.clear).clipShape(Capsule())}.buttonStyle(.plain)@@ -685,11 +1085,13 @@ struct TerminalScreen: View {}.buttonStyle(.plain)}- .foregroundColor(nav.focused ? .white : .gray)+ .foregroundColor(nav.focused ? model.ink : .gray).padding(.horizontal, 6).frame(width: min(nav.rect.width, maxWidth), height: nav.rect.height, alignment: .leading)+ // The bar's height is the core's: its text grows only so far.+ .dynamicTypeSize(...DynamicTypeSize.large).background(model.background)- .background(Color.white.opacity(nav.focused ? 0.1 : 0.04))+ .background(model.ink.opacity(nav.focused ? 0.1 : 0.04)).contentShape(Rectangle()).contextMenu {AppMenuItems(model: model, kind: "pane", id: String(nav.rect.pane))@@ -781,6 +1183,71 @@ struct MenuSheet: Identifiable {var key: String { kind + ":" + id }}+/// A thread's status as the desktop's sidebar shows it: a spinner while+/// it works, an alert while it waits on someone, a check when it finished+/// unseen; otherwise the core's dot -- the one on show, open, pinned,+/// unread or quiet. Every state takes the same square, `size` × 2, so a+/// row or a chip keeps its width as the status changes.+struct ThreadMark: View {+ var status: String+ var dot: String+ var size: CGFloat++ // The web page's tokens (tokens.css), which follow the desktop's.+ static let open = Color(hex: "#61B8FF") ?? .blue+ static let done = Color(hex: "#7CE5A2") ?? .green+ static let warn = Color(hex: "#DB7320") ?? .orange++ var body: some View {+ Group {+ switch status {+ case "Running":+ Spinner(color: Self.open).padding(size * 0.15)+ case "NeedsAttention":+ Image(systemName: "exclamationmark.circle.fill")+ .resizable().scaledToFit().foregroundColor(Self.warn)+ case "Done":+ Image(systemName: "checkmark.circle.fill")+ .resizable().scaledToFit().foregroundColor(Self.done)+ default:+ Circle().fill(Self.dotColor(dot)).frame(width: size, height: size)+ }+ }+ .frame(width: size * 2, height: size * 2)+ }++ static func dotColor(_ dot: String) -> Color {+ switch dot {+ case "Active": return done+ case "Open": return open+ case "Pinned": return Color(hex: "#C7C7CC") ?? .gray+ case "Unread": return Color(hex: "#8E8E93") ?? .gray+ default: return Color.white.opacity(0.16)+ }+ }+}++/// The desktop's and the page's busy mark: an open ring turning once in+/// 0.96 s, drawn to the size it is given.+struct Spinner: View {+ var color: Color+ @State private var turning = false++ var body: some View {+ Circle()+ .trim(from: 0, to: 0.75)+ .stroke(color, style: StrokeStyle(lineWidth: 1.6, lineCap: .round))+ .rotationEffect(.degrees(turning ? 360 : 0))+ // Started again each time it shows: a lazy list's row comes+ // back with its state, and an animation that ran out.+ .onAppear {+ turning = false+ withAnimation(.linear(duration: 0.96).repeatForever(autoreverses: false)) { turning = true }+ }+ .onDisappear { turning = false }+ }+}+/// The App's context menu for something, as the system menu that a long/// press opens: its items, checks, separators and submenus, built when/// the menu shows.@@ -809,9 +1276,11 @@ struct AppMenuItems: View {ForEach(subs, id: \.rowId) { sub in row(sub, model: model) }})}+ // Deleting a thread ends its programs: it is asked first.+ let deletes = item.id.hasPrefix("delete-thread:")return AnyView(- Button {- model.menuAction(item.id)+ Button(role: deletes ? .destructive : nil) {+ if deletes { model.confirming = item.id } else { model.menuAction(item.id) }} label: {if item.checked {Label(item.label, systemImage: "checkmark")@@ -1023,3 +1492,59 @@ struct ConnectionCard: View {return nil}}++/// The tab strip's clip: its own width, with room above and below for the+/// glass to swell into as it is pressed.+private struct SideClip: Shape {+ func path(in rect: CGRect) -> Path { Path(rect.insetBy(dx: 0, dy: -16)) }+}++/// Its content at most `width` across, however much is offered: in a+/// scroll view, which offers none, a frame's limit alone sizes the frame+/// but leaves a long name whole and spilling out of it.+private struct AtMost: Layout {+ var width: CGFloat++ func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {+ guard let content = subviews.first else { return .zero }+ let ideal = content.sizeThatFits(.unspecified).width+ return content.sizeThatFits(ProposedViewSize(width: min(proposal.width ?? ideal, ideal, width), height: proposal.height))+ }++ func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {+ subviews.first?.place(at: bounds.origin, proposal: ProposedViewSize(bounds.size))+ }+}++/// What the overview's moves keep to themselves, out of SwiftUI's state so+/// that keeping it redraws nothing: which move is the latest (a late end+/// belongs to an older one), whether the terminal's picture is in its+/// card, and the thread a tapped card is bringing back.+final class OverviewMoves {+ var turn = 0+ /// Each card's picture, by thread, in the screen's space: read as a+ /// flight sets off, not drawn from.+ var thumbs: [String: CGRect] = [:]+ var landed = false+ /// On the way back (`closeOverview`, `pick`): taps wait.+ var closing = false+ var grown = false+ var picked: String?+ /// An open waits for the drawer or the keyboard to go first.+ var waiting = false+ /// The screen is up: what was set to run on it runs only then.+ var onScreen = false+}++/// Whether tabs are scrolled off the strip's start, and lie past its end.+private struct StripEnds: Equatable {+ var before = false+ var after = false+}++/// Where the drag from the left edge under way set off, and whether it+/// pulls the drawer: decided once, as it sets off.+final class EdgeDrag {+ var start: CGPoint?+ var pulls = false+}diff --git a/ios/Sources/ThinkTermApp.swift b/ios/Sources/ThinkTermApp.swiftindex aaf03495..b73e8b9a 100644--- a/ios/Sources/ThinkTermApp.swift+++ b/ios/Sources/ThinkTermApp.swift@@ -4,25 +4,31 @@ import SwiftUIstruct ThinkTermApp: App {@StateObject private var store = HostStore()@StateObject private var sessions = Sessions()+ @Environment(\.scenePhase) private var scenePhasevar body: some Scene {WindowGroup {Group {- #if DEBUG- if ProcessInfo.processInfo.arguments.contains(where: { $0.hasPrefix("--auto") || $0.hasSuffix("test") }) {+ if TerminalModel.automated {// The automated flows go straight to the probe's host.NavigationStack { TerminalScreen(model: sessions.model(for: nil, store: store)) }} else {RootTabs(store: store)}- #else- RootTabs(store: store)- #endif}.environmentObject(store).environmentObject(sessions).preferredColorScheme(.dark)}+ // Every open connection hears about the background, on screen or+ // not, whichever way the app was opened.+ .onChange(of: scenePhase) { _, phase in+ switch phase {+ case .background: sessions.detachForBackground()+ case .active: sessions.reattachAfterBackground()+ default: break+ }+ }}/// `--seed-probe-host`: save the probe as an ordinary host whose key@@ -53,8 +59,6 @@ struct ThinkTermApp: App {/// with the rest of the app.private struct RootTabs: View {let store: HostStore- @EnvironmentObject private var sessions: Sessions- @Environment(\.scenePhase) private var scenePhase@State private var path = NavigationPath()@ObservedObject private var lang = AppLanguage.shared@@ -73,17 +77,9 @@ private struct RootTabs: View {}.tabItem { Label(tr("hosts"), systemImage: "server.rack") }NavigationStack {- SettingsView(model: nil, showLog: nil)+ SettingsView(showLog: nil)}.tabItem { Label(tr("settings"), systemImage: "gearshape") }}- // Every open connection hears about the background, on screen or not.- .onChange(of: scenePhase) { _, phase in- switch phase {- case .background: sessions.detachForBackground()- case .active: sessions.reattachAfterBackground()- default: break- }- }}}diff --git a/ios/Sources/TreeSheet.swift b/ios/Sources/TreeSheet.swiftdeleted file mode 100644index 3f6d2e53..00000000--- a/ios/Sources/TreeSheet.swift+++ /dev/null@@ -1,224 +0,0 @@-import SwiftUI--/// The desktop's Live Overview as an overlay under the terminal: a card-/// per thread, grouped by project, two to a row. Each card is the-/// thread's name and state with its current tab's title,-/// an offline badge, and a thumbnail of its terminal in its colours: the-/// last rows of its current tab's pane, fetched from the server and-/// refreshed while the overview is up. The thread on show leaves its-/// thumbnail empty and reports the box's frame: the live terminal is-/// zoomed into it by the screen above.-struct OverviewScreen: View {- @ObservedObject var model: TerminalModel- @ObservedObject private var lang = AppLanguage.shared- @Binding var isPresented: Bool- /// The thread on show's card and its thumbnail box, in the screen's space.- @Binding var cardFrame: CardFrames?- var liveThread: String?- /// The live card's rows wait until the terminal has faded out of it.- var livePreview: Bool = true- /// A tapped card, with its frames: the terminal grows back out of it.- var onPick: (ThreadView, CardFrames?) -> Void = { _, _ in }- private let rows = 9- private let columns = [GridItem(.flexible(), spacing: 10), GridItem(.flexible(), spacing: 10)]-- /// Every card's two frames, by thread; the live card's are reported.- @State private var cardFrames: [String: CGRect] = [:]- @State private var thumbFrames: [String: CGRect] = [:]-- private func frames(of id: String) -> CardFrames? {- guard let card = cardFrames[id], let thumb = thumbFrames[id] else { return nil }- return CardFrames(card: card, thumb: thumb)- }-- private func report() {- guard let live = liveThread, let frames = frames(of: live) else { return }- if cardFrame != frames { cardFrame = frames }- }-- private var threads: [ThreadView] { model.threads?.threads ?? [] }-- private var groups: [(project: String, threads: [ThreadView])] {- var order: [String] = []- var byProject: [String: [ThreadView]] = [:]- for t in threads {- if byProject[t.project] == nil { order.append(t.project) }- byProject[t.project, default: []].append(t)- }- return order.map { ($0, byProject[$0] ?? []) }- }-- var body: some View {- VStack(spacing: 0) {- ScrollView {- if threads.isEmpty {- Text(tr("overview.none"))- .foregroundColor(.secondary)- .padding(.top, 60)- } else {- LazyVStack(alignment: .leading, spacing: 8) {- ForEach(groups, id: \.project) { group in- HStack(spacing: 6) {- Text(model.threads?.space ?? "")- Text("·").foregroundColor(.secondary)- Text(group.project)- Rectangle().fill(Color.white.opacity(0.08)).frame(height: 1)- Text("\(group.threads.count)").foregroundColor(.secondary)- }- .font(.caption)- .padding(.top, 10)- LazyVGrid(columns: columns, spacing: 10) {- ForEach(group.threads) { thread in- card(thread)- }- }- }- }- .padding(.horizontal, 12)- .padding(.vertical, 8)- }- }- // Pinching back in returns to the terminal.- .gesture(MagnifyGesture().onEnded { value in- if value.magnification > 1.25 { isPresented = false }- })- }- .foregroundColor(.white)- .background(Color(white: 0.06))- .onAppear {- model.refreshViews()- refreshPreviews()- }- .task {- // One ticker for the grid's life: a publisher made in `body`- // would be made again on every render, and its subscription- // with it.- while !Task.isCancelled {- try? await Task.sleep(nanoseconds: 2_000_000_000)- if !Task.isCancelled { refreshPreviews() }- }- }- }-- /// Every live thread's current tab, asked for its last rows.- private func refreshPreviews() {- for thread in threads where thread.live {- if let pane = previewPane(thread) {- model.requestPreview(pane: pane, rows: rows)- }- }- }-- private func previewPane(_ thread: ThreadView) -> Int? {- (thread.tabs.first(where: { $0.current }) ?? thread.tabs.first)?.target- }-- private func card(_ thread: ThreadView) -> some View {- let live = thread.id == liveThread- return Button {- if !live { model.sideClick("thread", id: thread.id) }- onPick(thread, frames(of: thread.id))- isPresented = false- } label: {- VStack(alignment: .leading, spacing: 0) {- ThreadCardHeader(thread: thread)- ZStack(alignment: .topLeading) {- Text(preview(thread))- .font(.system(size: 7, design: .monospaced))- .lineSpacing(1)- .frame(maxWidth: .infinity, alignment: .topLeading)- .padding(.horizontal, 8)- .padding(.vertical, 7)- .opacity(!live || livePreview ? 1 : 0)- // The terminal itself lands over this, then fades into the- // same preview as every other card; the frame is kept so- // the screen above knows where.- Color.clear- .background(GeometryReader { geo in- Color.clear- .onAppear { thumbFrames[thread.id] = geo.frame(in: .named("screen")); report() }- .onChange(of: geo.frame(in: .named("screen"))) { _, f in thumbFrames[thread.id] = f; report() }- })- }- .frame(height: 92, alignment: .topLeading)- .background(thread.live ? model.background : Color.black.opacity(0.4))- .clipped()- }- .background(GeometryReader { geo in- Color.clear- .onAppear { cardFrames[thread.id] = geo.frame(in: .named("screen")); report() }- .onChange(of: geo.frame(in: .named("screen"))) { _, f in cardFrames[thread.id] = f; report() }- })- .background(Color(red: 0.10, green: 0.11, blue: 0.13))- .clipShape(RoundedRectangle(cornerRadius: 13))- // The moving card draws its own border until it has landed.- .overlay(RoundedRectangle(cornerRadius: 13).stroke(- live ? (livePreview ? Color.accentColor : Color.clear) : Color.white.opacity(0.07),- lineWidth: live ? 2 : 1- ))- }- .buttonStyle(.plain)- }-- /// The rows fetched for the thread's pane in their colours, trailing- /// blank rows dropped, each cut at about a half-width card's worth.- private func preview(_ thread: ThreadView) -> AttributedString {- guard let pane = previewPane(thread), let fetched = model.previews[pane] else { return AttributedString("") }- let kept = Array(fetched.reversed().drop(while: { $0.runs.isEmpty }).reversed().suffix(rows))- var out = AttributedString()- for (i, row) in kept.enumerated() {- var used = 0- for run in row.runs {- let room = 38 - used- if room <= 0 { break }- var piece = AttributedString(String(run.text.prefix(room)))- piece.foregroundColor = Color(hex: run.fg) ?? .white- out += piece- used += min(run.text.count, room)- }- if i < kept.count - 1 { out += AttributedString("\n") }- }- return out- }-}--/// Where the live card is and where its thumbnail is, in the screen's space.-struct CardFrames: Equatable {- var card: CGRect- var thumb: CGRect-}--/// A card's top: the thread's dot and name, its tabs as dots, the current-/// tab's title, and an offline badge. Shared with the screen's zoom, which-/// carries the same header while the terminal shrinks.-struct ThreadCardHeader: View {- let thread: ThreadView- @ObservedObject private var lang = AppLanguage.shared-- /// One line: the dot and name, the current tab's title after them, and- /// an offline badge at the end; the tabs as dots took a row of their own.- var body: some View {- let currentTab = thread.tabs.first(where: { $0.current }) ?? thread.tabs.first- HStack(spacing: 7) {- Circle().fill(TerminalScreen.threadColor(status: thread.status, live: thread.live)).frame(width: 7, height: 7)- Text(thread.name).font(.system(size: 13.5, weight: .semibold)).lineLimit(1)- Text(currentTab?.title ?? "")- .font(.system(size: 10, design: .monospaced))- .foregroundColor(.secondary)- .lineLimit(1)- Spacer(minLength: 0)- if !thread.live {- Text(tr("offline"))- .font(.system(size: 9, weight: .semibold))- .foregroundColor(.secondary)- .padding(.horizontal, 6).padding(.vertical, 2)- .background(Color.gray.opacity(0.22))- .clipShape(Capsule())- }- }- .padding(.horizontal, 10)- .padding(.top, 9)- .padding(.bottom, 8)- .foregroundColor(.white)- }-}diff --git a/ios/Sources/Views.swift b/ios/Sources/Views.swiftindex 9c044247..146991d6 100644--- a/ios/Sources/Views.swift+++ b/ios/Sources/Views.swift@@ -30,6 +30,8 @@ struct Controls: Decodable, Hashable {struct TabsView: Decodable, Hashable {var tabs: [TabEntry]var controls: Controls+ /// The terminal's card, which every window tab wears, as on the desktop.+ var icon: String?}struct NavRect: Decodable, Hashable {@@ -45,6 +47,7 @@ struct CapsuleView: Decodable, Hashable, Identifiable {var title: Stringvar busy: Boolvar current: Bool+ var icon: String?var id: Int { pane }}@@ -112,14 +115,39 @@ struct TreeProject: Decodable, Hashable, Identifiable {var threads: [ThreadRow]}-/// A thumbnail row: `App::PreviewRow`.-struct PreviewRow: Decodable, Hashable {- var runs: [PreviewRun]+/// A tab as it is split, for a picture of it: each pane's screen where it+/// lies, in the tab's cells (`App::TabPreview`).+struct TabPreview: Decodable, Hashable {+ var cols: Int+ var rows: Int+ var foreground: String+ var background: String+ var panes: [PanePreview]+}++struct PanePreview: Decodable, Hashable {+ var left: Int+ var top: Int+ var screen: ScreenPreview+}++/// A pane's whole screen: `App::ScreenPreview`.+struct ScreenPreview: Decodable, Hashable {+ var cols: Int+ var rows: Int+ var foreground: String+ var background: String+ var lines: [[ScreenRun]]}-struct PreviewRun: Decodable, Hashable {+/// Text from column `col` across `width` columns, of one foreground and+/// background (`bg` is "" on the screen's own).+struct ScreenRun: Decodable, Hashable {var text: Stringvar fg: String+ var bg: String+ var col: Int+ var width: Int}struct Toast: Decodable, Hashable {diff --git a/ios/tools/gen-strings.py b/ios/tools/gen-strings.pyindex c2441ed9..94a76fe9 100644--- a/ios/tools/gen-strings.py+++ b/ios/tools/gen-strings.py@@ -30,6 +30,9 @@ EXTRA = {"p.layout": ["Layout", "布局", "レイアウト", "Disposition", "Layout"],"project.new": ["New project", "新建项目", "新規プロジェクト", "Nouveau projet", "Neues Projekt"],"sidebar": ["Sidebar", "侧栏", "サイドバー", "Barre latérale", "Seitenleiste"],+ # The desktop's tooltip-sidebar-thread-search, with this app's word for a thread.+ "thread.find": ["Find Thread", "查找会话", "セッションを検索", "Rechercher une session", "Thread finden"],+ "thread.find.none": ["No thread matches", "没有匹配的会话", "一致するセッションはありません", "Aucune session ne correspond", "Kein Thread passt"],"keyboard.incognito": ["Incognito keyboard", "无痕键盘", "シークレット キーボード", "Clavier incognito", "Inkognito-Tastatur"],"thread.delete.title": ["Delete “%@”?", "删除“%@”?", "「%@」を削除しますか?", "Supprimer « %@ » ?", "„%@“ löschen?"],"thread.delete.body": [