Files
helder/Sources/HelderUI/Terminal/HelderTerminalView.swift
T
2026-10-10 14:54:39 +02:00

219 lines
9.2 KiB
Swift

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, PointerTextTarget {
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 lazy var pointerTracker = PointerTracker(view: self)
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))
Self.policyCursorUpdate
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<UInt8>) {
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)
}
/// ⌥← and ⌥→ jump by word (ESC b / ESC f, as Terminal.app does) while Option is not the Meta key.
override func interpretKeyEvents(_ events: [NSEvent]) {
if !optionAsMetaKey, events.count == 1, let event = events.first, event.type == .keyDown,
event.modifierFlags.intersection([.shift, .control, .option, .command]) == .option,
let key = event.charactersIgnoringModifiers?.unicodeScalars.first.map({ Int($0.value) }) {
switch key {
case NSLeftArrowFunctionKey: return send(EscapeSequences.emacsBack)
case NSRightArrowFunctionKey: return send(EscapeSequences.emacsForward)
default: break
}
}
super.interpretKeyEvents(events)
}
/// 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: Pointer
let pointerLayer = PointerLayer.workspace
var acceptsPointerText: Bool { true }
/// The grid takes the I-beam: its output selects and its prompt takes input. SwiftTerm's scroller keeps the arrow.
func isPointerOverText(atWindowPoint point: NSPoint) -> Bool {
guard let hit = hitView(atWindowPoint: point) else { return false }
return hit.isDescendant(of: self) && !(hit is NSScroller)
}
/// The first click in an inactive window already places the selection or reaches the program.
override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
/// SwiftTerm's own tracking area has no cursor updates, so entering the grid would not re-read the pointer.
override func updateTrackingAreas() {
super.updateTrackingAreas()
pointerTracker.update()
}
/// SwiftTerm's `resetCursorRects` is not open, so its I-beam rect is filtered here and leaves out the scroller.
override func addCursorRect(_ rect: NSRect, cursor object: NSCursor) {
guard rect.isUsableCursorRect else { return }
guard object == .iBeam else { return super.addCursorRect(rect, cursor: object) }
guard allowsIBeamRect else { return }
let scroller = subviews.first { $0 is NSScroller && !$0.isHidden }
let area = scroller.map { rect.removing($0.frame) } ?? rect
guard area.isUsableCursorRect else { return }
super.addCursorRect(area, cursor: object)
}
/// Gives this class its own `cursorUpdate:` that asks the policy; Swift cannot override SwiftTerm's I-beam one,
/// which runs when an update reaches the pane through a subview or a neighbour's tracking area.
private static let policyCursorUpdate: Void = {
let block: @convention(block) (AnyObject, NSEvent) -> Void = { view, _ in
MainActor.assumeIsolated {
guard let view = view as? HelderTerminalView, let window = view.window else { return }
let point = window.mouseLocationOutsideOfEventStream
if PointerPolicy.isSelecting || view.isTopmost(atWindowPoint: point) {
view.updatePointer(atWindowPoint: point)
} else {
PointerPolicy.scheduleUpdate(in: window)
}
}
}
let selector = #selector(NSResponder.cursorUpdate(with:))
let types = method_getTypeEncoding(class_getInstanceMethod(NSView.self, selector)!)
class_addMethod(HelderTerminalView.self, selector, imp_implementationWithBlock(block), types)
}()
/// A drag that starts on the grid selects text, so it keeps the I-beam until mouse-up wherever it goes.
override func mouseDown(with event: NSEvent) {
PointerPolicy.beginSelection()
super.mouseDown(with: event)
}
override func mouseDragged(with event: NSEvent) {
super.mouseDragged(with: event)
if PointerPolicy.isSelecting { NSCursor.iBeam.set() }
}
override func mouseUp(with event: NSEvent) {
super.mouseUp(with: event)
PointerPolicy.endSelection(in: window)
}
// MARK: Lifetime
override func viewWillMove(toWindow newWindow: NSWindow?) {
PointerPolicy.endSelection(in: nil)
super.viewWillMove(toWindow: newWindow)
}
/// 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) }
}
}
}