import AppKit import HelderCore import SwiftTerm /// One pane's terminal: a SwiftTerm view bound to a PTY child, reporting to the `TerminalStore`. final class HelderTerminalView: LocalProcessTerminalView, TerminalSessionHandle { let kind: TerminalKind private weak var store: TerminalStore? private(set) var hasStarted = false var appliedSettings: HelderConfig.Terminal? var appliedScale = 1.0 private var closeObserver: NSObjectProtocol? private let events = ProcessEvents() init(kind: TerminalKind, store: TerminalStore) { self.kind = kind self.store = store super.init(frame: NSRect(x: 0, y: 0, width: 480, height: 320), font: TerminalAppearance.font(store.config.terminal), options: TerminalAppearance.options(store.config.terminal)) events.owner = self processDelegate = events appliedSettings = store.config.terminal TerminalAppearance.apply(store.config.terminal, to: self) } required init?(coder: NSCoder) { fatalError("HelderTerminalView is built in code") } // MARK: TerminalSessionHandle func start(_ launch: TerminalLaunch, argv0: String) { hasStarted = true let environment = launch.environment.map { "\($0.key)=\($0.value)" } startProcess(executable: launch.executable, args: launch.arguments, environment: environment, execName: argv0, currentDirectory: launch.workingDirectory) } /// Programmatic input (the agent paste) goes straight to the PTY, so it never counts as typing. func send(_ text: String) { guard process.running else { return } process.send(data: Array(text.utf8)[...]) window?.makeFirstResponder(self) } // MARK: Input, selection, menu /// After the child exited, the next keystroke starts a fresh one instead of reaching the dead PTY. override func send(source: TerminalView, data: ArraySlice) { if let store, store.hasExited(kind) { store.start(kind, on: self) return } if kind == .agent { store?.agentReceivedInput(String(decoding: data, as: UTF8.self)) } super.send(source: source, data: data) } /// Selecting text copies it, in both panes. override func selectionChanged(source: Terminal) { super.selectionChanged(source: source) guard selection.active, let text = getSelection(), !text.isEmpty else { return } NSPasteboard.general.clearContents() NSPasteboard.general.setString(text, forType: .string) } var selectedText: String? { selection.active ? getSelection() : nil } /// Bracketed only when the program asked for it, as a clipboard paste would be. func paste(_ text: String) { if terminal.bracketedPasteMode { send(BracketedPaste.wrap(text, composerHasText: false)) } else { send(text.replacingOccurrences(of: "\r\n", with: "\r").replacingOccurrences(of: "\n", with: "\r")) } } /// The app's own menu, drawn by the workspace, replaces the native one. override func menu(for event: NSEvent) -> NSMenu? { guard let store, let content = window?.contentView else { return nil } let p = content.convert(event.locationInWindow, from: nil) store.contextMenuRequested?(kind, selection.active, CGPoint(x: p.x, y: content.isFlipped ? p.y : content.bounds.height - p.y)) return nil } // MARK: Lifetime /// Closing the window kills the child; moving the view between containers does not. override func viewDidMoveToWindow() { super.viewDidMoveToWindow() if let closeObserver { NotificationCenter.default.removeObserver(closeObserver) } closeObserver = nil guard let window else { return } closeObserver = NotificationCenter.default.addObserver( forName: NSWindow.willCloseNotification, object: window, queue: .main ) { [weak self] _ in MainActor.assumeIsolated { guard let self else { return } self.store?.release(self) } } } /// The child ended on its own: say so in the pane and tell the store. fileprivate func childExited(exitCode: Int32?) { feed(text: "\r\n\u{1b}[90m[process exited] ยท press any key to restart\u{1b}[0m\r\n") store?.processExited(kind, exitCode: exitCode) } } /// A separate delegate object: the view itself cannot be one, because the base class forwards /// `hostCurrentDirectoryUpdate` to its `processDelegate`, which would then call itself. private final class ProcessEvents: LocalProcessTerminalViewDelegate { weak var owner: HelderTerminalView? func sizeChanged(source: LocalProcessTerminalView, newCols: Int, newRows: Int) {} func setTerminalTitle(source: LocalProcessTerminalView, title: String) {} func hostCurrentDirectoryUpdate(source: TerminalView, directory: String?) {} func processTerminated(source: TerminalView, exitCode: Int32?) { DispatchQueue.main.async { [weak self] in MainActor.assumeIsolated { self?.owner?.childExited(exitCode: exitCode) } } } }