SPB Git

Repository Public

TerminalSession.swift 17.4 KB 393 lines swift

1import AppKit2import DesignSystem3import Foundation4import Observation5import PTYProcess6import SettingsModel7import SwiftTerm89/// Lifecycle of the process behind a session.10public enum SessionStatus: Sendable, Equatable {11    case notStarted12    case running(pid: pid_t)13    case exited(PTYExitStatus)14    case failed(String)1516    public var isRunning: Bool { if case .running = self { return true } else { return false } }1718    public var label: String {19        switch self {20        case .notStarted: return "Not started"21        case .running: return "Running"22        case .exited(.exited(let code)): return code == 0 ? "Exited" : "Exited (\(code))"23        case .exited(.signaled(let signal)): return "Terminated (signal \(signal))"24        case .failed(let reason): return "Failed: \(reason)"25        }26    }27}2829/// Thread-safe activity counters updated from the PTY queue and sampled on the main actor,30/// so heavy output never floods the main thread with observation updates.31final class ActivityCounter: @unchecked Sendable {32    private let lock = NSLock()33    private var bytes: UInt64 = 034    private var last: Date?3536    func record(_ count: Int) { lock.withLock { bytes &+= UInt64(count); last = Date() } }37    func snapshot() -> (bytes: UInt64, last: Date?) { lock.withLock { (bytes, last) } }38}3940/// One terminal session: a PTY-backed process and the view rendering it.41///42/// A session is independent of any window: moving a pane to another tab, window or display only43/// re-parents `view`; the process, scrollback and PTY are untouched.44@MainActor45@Observable46public final class TerminalSession: Identifiable, TerminalViewDelegate {47    public nonisolated let id: UUID48    public private(set) var request: LaunchRequest49    public private(set) var status: SessionStatus = .notStarted50    /// Title set by the running program (OSC 0/2).51    public private(set) var reportedTitle: String = ""52    /// Working directory: reported by the shell (OSC 7) when available, otherwise probed.53    public private(set) var workingDirectory: String?54    /// Remote host named in the last OSC 7 report, if any.55    public private(set) var reportedRemoteHost: String?56    public private(set) var columns = 8057    public private(set) var rows = 2458    public private(set) var startedAt: Date?59    public private(set) var endedAt: Date?60    /// A command (not the shell itself) owns the terminal.61    public private(set) var hasForegroundJob = false62    public private(set) var foregroundProcessName: String?63    public private(set) var foregroundSince: Date?64    public private(set) var lastOutputAt: Date?65    public private(set) var totalOutputBytes: UInt64 = 066    public private(set) var bellCount = 067    public private(set) var isFocused = false68    /// Resource usage of the foreground process group (sampled by `refreshProcessState`).69    public private(set) var resources: ProcessSnapshot?70    /// CPU share of the foreground group between the last two samples (1.0 = one full core).71    public private(set) var cpuLoad: Double = 07273    @ObservationIgnored public let view: SPTerminalView74    @ObservationIgnored private var process: PTYProcess?75    @ObservationIgnored private let activity = ActivityCounter()76    @ObservationIgnored private var initialDirectory: String?77    @ObservationIgnored private var extraEnvironment: [String: String]78    @ObservationIgnored private var directoryWasReported = false79    @ObservationIgnored private var lastCPUSample: (seconds: Double, at: Date, pid: pid_t)?80    @ObservationIgnored private let appVersion: String8182    // Hooks installed by the workspace controller.83    /// Bytes typed by the user in this session (used to mirror input to a broadcast group).84    @ObservationIgnored public var userInputTap: ((ArraySlice<UInt8>) -> Void)?85    @ObservationIgnored public var onExit: ((PTYExitStatus) -> Void)?86    @ObservationIgnored public var onBell: (() -> Void)?87    /// A program asked to open a link (OSC 8 or detected URL). The host validates and opens.88    @ObservationIgnored public var onOpenLink: ((String) -> Void)?89    /// A program wants to write the clipboard (OSC 52). The host applies the user's policy.90    @ObservationIgnored public var onClipboardWrite: ((String) -> Void)?91    /// Returns clipboard text for an OSC 52 read, or `nil` to refuse (the default).92    @ObservationIgnored public var clipboardReadProvider: (() -> String?)?93    @ObservationIgnored public var onFocus: (() -> Void)?94    @ObservationIgnored public var onTitleChange: (() -> Void)?95    /// Foreground command finished (name, duration) — drives "long command finished" notifications.96    @ObservationIgnored public var onForegroundJobEnded: ((String, TimeInterval) -> Void)?9798    public init(id: UUID = UUID(), request: LaunchRequest, workingDirectory: String? = nil,99                extraEnvironment: [String: String] = [:], scrollback: Int = 20_000, appVersion: String = "1.0") {100        self.id = id101        self.request = request102        self.initialDirectory = workingDirectory103        self.workingDirectory = workingDirectory104        self.extraEnvironment = extraEnvironment105        self.appVersion = appVersion106        var options = TerminalOptions.default107        options.scrollback = scrollback108        view = SPTerminalView(frame: CGRect(x: 0, y: 0, width: 800, height: 480), font: nil, options: options)109        view.terminalDelegate = self110        view.onFileDrop = { [weak self] urls in111            self?.view.typeText(ShellEscaping.escapePaths(urls.map(\.path)))112        }113    }114115    // MARK: Lifecycle116117    /// Starts the process. Safe to call once; use `restart()` afterwards.118    public func start() {119        guard process == nil, !status.isRunning else { return }120        let dims = view.terminalDimensions121        columns = dims.cols122        rows = dims.rows123        let configuration = LaunchPlanner.plan(request, workingDirectory: initialDirectory, columns: columns, rows: rows,124                                               appVersion: appVersion, extraEnvironment: extraEnvironment)125        let feeder = view.feedSender126        let activity = activity127        do {128            let id = self.id129            process = try PTYProcess(configuration, onOutput: { bytes in130                feeder.feed(byteArray: bytes)131                activity.record(bytes.count)132            }, onExit: { [weak self] exit in133                Task { @MainActor in134                    guard let self, self.id == id else { return }135                    self.processDidExit(exit)136                }137            })138            status = .running(pid: process!.pid)139            startedAt = Date()140            endedAt = nil141        } catch {142            status = .failed(String(describing: error))143            view.feed(text: "\r\n\u{1b}[31mSP Term could not start the session: \(error)\u{1b}[0m\r\n")144        }145    }146147    private func processDidExit(_ exit: PTYExitStatus) {148        guard status.isRunning else { return }149        status = .exited(exit)150        endedAt = Date()151        hasForegroundJob = false152        foregroundProcessName = nil153        resources = nil154        cpuLoad = 0155        process = nil156        let note: String157        switch exit {158        case .exited(let code): note = "process exited with code \(code)"159        case .signaled(let signal): note = "process terminated by signal \(signal)"160        }161        view.feed(text: "\r\n\u{1b}[0m\u{1b}[2m[\(note)]\u{1b}[0m\r\n")162        onExit?(exit)163    }164165    /// Starts a new process in the same view (scrollback kept), in the last known directory.166    public func restart() {167        if let process, process.isRunning {168            process.terminate(grace: 0.3)169        }170        process = nil171        if status.isRunning { status = .exited(.signaled(signal: SIGHUP)) }172        initialDirectory = workingDirectory ?? initialDirectory173        directoryWasReported = false174        view.feed(text: "\r\n\u{1b}[0m\u{1b}[2m[new process started — earlier output above belongs to the previous one]\u{1b}[0m\r\n")175        start()176    }177178    /// Ends the session's process (SIGHUP to the session, then SIGKILL after a grace period).179    public func terminate() {180        process?.terminate()181    }182183    public var pid: pid_t? { if case .running(let pid) = status { return pid } else { return nil } }184    public var ttyName: String? { process?.ttyName }185186    /// `true` when closing would interrupt something: a command is running in the shell, or the187    /// session is a directly launched program (ssh, an agent) that is still alive.188    public var isBusy: Bool {189        guard status.isRunning, let process else { return false }190        if case .shell = request { return process.hasForegroundJob }191        return true192    }193194    /// Called by the window when the view gains or loses first-responder status.195    public func setFocused(_ focused: Bool) {196        guard focused != isFocused else { return }197        isFocused = focused198        if focused { onFocus?() }199    }200201    // MARK: Input202203    /// Sends text to the process as typed input (no newline is added).204    public func send(text: String) { process?.write(text) }205    public func send(bytes: some Sequence<UInt8>) { process?.write(bytes) }206207    /// Inserts a command at the prompt; runs it only when `execute` is true.208    public func insertCommand(_ command: String, execute: Bool) {209        process?.write(command + (execute ? "\r" : ""))210    }211212    // MARK: Periodic sampling (called about once per second by the app)213214    public func refreshProcessState() {215        let sample = activity.snapshot()216        if sample.bytes != totalOutputBytes { totalOutputBytes = sample.bytes }217        if sample.last != lastOutputAt { lastOutputAt = sample.last }218        guard let process, status.isRunning else { return }219        let group = process.foregroundProcessGroup()220        let busy = group != nil && group != process.pid221        if busy != hasForegroundJob {222            if !busy, let name = foregroundProcessName, let since = foregroundSince {223                onForegroundJobEnded?(name, Date().timeIntervalSince(since))224            }225            hasForegroundJob = busy226            foregroundSince = busy ? Date() : nil227        }228        let leader = busy ? group! : process.pid229        let name = ProcessProbe.name(of: leader)230        if name != foregroundProcessName { foregroundProcessName = name }231        if !directoryWasReported, let cwd = ProcessProbe.workingDirectory(of: process.pid), cwd != workingDirectory {232            workingDirectory = cwd233        }234        // Resources: sum over the foreground process group.235        let members = busy ? ProcessProbe.members(ofProcessGroup: leader) : [leader]236        var total = ProcessSnapshot(pid: leader, name: name ?? "?", residentBytes: 0, cpuSeconds: 0, startDate: nil)237        for pid in members.isEmpty ? [leader] : members {238            guard let snapshot = ProcessProbe.snapshot(of: pid) else { continue }239            total.residentBytes += snapshot.residentBytes240            total.cpuSeconds += snapshot.cpuSeconds241            if pid == leader { total.startDate = snapshot.startDate }242        }243        let now = Date()244        if let previous = lastCPUSample, previous.pid == leader, now.timeIntervalSince(previous.at) > 0.2 {245            cpuLoad = max(0, (total.cpuSeconds - previous.seconds) / now.timeIntervalSince(previous.at))246        } else {247            cpuLoad = 0248        }249        lastCPUSample = (total.cpuSeconds, now, leader)250        if total != resources { resources = total }251    }252253    // MARK: Appearance254255    /// Applies colours, font and behaviour preferences to the view.256    public func apply(settings: AppSettings, theme: TerminalTheme) {257        let size = CGFloat(settings.fontSize)258        let font = TerminalSession.font(named: settings.fontName, size: size)259        if view.font != font { view.font = font }260        view.installColors(theme.ansi.map(\.terminalColor))261        view.nativeBackgroundColor = theme.background.nsColor262        view.nativeForegroundColor = theme.foreground.nsColor263        view.caretColor = theme.cursor.nsColor264        view.selectedTextBackgroundColor = theme.selection.nsColor265        view.backgroundOpacity = CGFloat(settings.backgroundOpacity)266        view.minimumContrastRatio = theme.isHighContrast ? 4.5 : 1267        let style: CursorStyle268        switch (settings.cursorShape, settings.cursorBlink) {269        case (.block, true): style = .blinkBlock270        case (.block, false): style = .steadyBlock271        case (.underline, true): style = .blinkUnderline272        case (.underline, false): style = .steadyUnderline273        case (.bar, true): style = .blinkBar274        case (.bar, false): style = .steadyBar275        }276        view.setCursorStyle(style)277        view.optionAsMetaKey = settings.optionAsMeta278        view.allowMouseReporting = settings.mouseReporting279        switch settings.bell {280        case .off: view.bellStyle = .none281        case .sound: view.bellStyle = .sound282        case .visual: view.bellStyle = .visual283        case .both: view.bellStyle = .soundAndVisual284        }285        view.changeScrollback(settings.scrollbackLines)286        if view.isUsingMetalRenderer != settings.useMetalRenderer {287            try? view.setUseMetal(settings.useMetalRenderer)288        }289    }290291    /// Resolves a font family/name to a fixed-pitch font, falling back to the system monospaced font.292    public static func font(named name: String, size: CGFloat) -> NSFont {293        if name == "SF Mono" || name.isEmpty { return NSFont.monospacedSystemFont(ofSize: size, weight: .regular) }294        if let exact = NSFont(name: name, size: size) { return exact }295        if let family = NSFontManager.shared.font(withFamily: name, traits: [], weight: 5, size: size) { return family }296        return NSFont.monospacedSystemFont(ofSize: size, weight: .regular)297    }298299    /// Installed fixed-pitch font families, "SF Mono" (the system monospaced font) first.300    public static func monospacedFontFamilies() -> [String] {301        let manager = NSFontManager.shared302        let families = manager.availableFontFamilies.filter { family in303            guard let font = manager.font(withFamily: family, traits: [], weight: 5, size: 12) else { return false }304            return font.isFixedPitch && !family.hasPrefix(".")305        }306        return ["SF Mono"] + families.filter { $0 != "SF Mono" }.sorted()307    }308309    // MARK: Content310311    /// The whole buffer (scrollback + screen) as text.312    public func bufferText() -> String {313        String(decoding: view.getBufferAsData(), as: UTF8.self)314    }315316    public var selectedText: String? {317        guard view.selectionActive, let text = view.getSelection(), !text.isEmpty else { return nil }318        return text319    }320321    // MARK: TerminalViewDelegate322323    public func sizeChanged(source: TerminalView, newCols: Int, newRows: Int) {324        columns = newCols325        rows = newRows326        process?.resize(columns: UInt16(clamping: newCols), rows: UInt16(clamping: newRows),327                        pixelWidth: UInt16(clamping: Int(source.frame.width)), pixelHeight: UInt16(clamping: Int(source.frame.height)))328    }329330    public func setTerminalTitle(source: TerminalView, title: String) {331        // Titles come from untrusted program output: keep them short and printable.332        let cleaned = String(title.unicodeScalars.filter { $0.value >= 0x20 && $0.value != 0x7f }.prefix(200).map(Character.init))333        if cleaned != reportedTitle {334            reportedTitle = cleaned335            onTitleChange?()336        }337    }338339    public func hostCurrentDirectoryUpdate(source: TerminalView, directory: String?) {340        guard let directory, let path = WorkingDirectoryReport.path(from: directory) else { return }341        directoryWasReported = true342        workingDirectory = path343        reportedRemoteHost = WorkingDirectoryReport.remoteHost(from: directory, localHostNames: TerminalSession.localHostNames)344    }345346    public func send(source: TerminalView, data: ArraySlice<UInt8>) {347        process?.write(data)348        if UserInputScope.isActive { userInputTap?(data) }349    }350351    public func scrolled(source: TerminalView, position: Double) {}352    public func rangeChanged(source: TerminalView, startY: Int, endY: Int) {}353354    public func bell(source: TerminalView) {355        bellCount += 1356        onBell?()357    }358359    public func requestOpenLink(source: TerminalView, link: String, params: [String: String]) {360        onOpenLink?(link)361    }362363    public func clipboardCopy(source: TerminalView, content: Data) {364        guard let text = String(data: content, encoding: .utf8), !text.isEmpty else { return }365        onClipboardWrite?(text)366    }367368    public func clipboardRead(source: TerminalView) -> Data? {369        clipboardReadProvider?().flatMap { $0.data(using: .utf8) }370    }371372    public func iTermContent(source: TerminalView, content: ArraySlice<UInt8>) {}373374    /// Names this machine answers to, computed without reverse DNS (which can block for seconds).375    static let localHostNames: Set<String> = {376        var buffer = [UInt8](repeating: 0, count: 256)377        _ = buffer.withUnsafeMutableBytes { gethostname($0.baseAddress, $0.count - 1) }378        let name = String(decoding: buffer.prefix { $0 != 0 }, as: UTF8.self).lowercased()379        var names: Set<String> = ["localhost", name]380        if let short = name.split(separator: ".").first { names.insert(String(short)) }381        return names382    }()383}384385extension DesignSystem.RGBColor {386    public var nsColor: NSColor {387        NSColor(srgbRed: CGFloat(red) / 255, green: CGFloat(green) / 255, blue: CGFloat(blue) / 255, alpha: 1)388    }389    var terminalColor: SwiftTerm.Color {390        SwiftTerm.Color(red: UInt16(red) * 257, green: UInt16(green) * 257, blue: UInt16(blue) * 257)391    }392}393
Files main
Menu

Theme