164 lines
6.8 KiB
Swift
164 lines
6.8 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 {
|
|
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))
|
|
Self.arrowCursorUpdate
|
|
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
|
|
|
|
/// The terminal shows the arrow, so SwiftTerm's I-beam rect is dropped; its `resetCursorRects` is not open.
|
|
override func addCursorRect(_ rect: NSRect, cursor object: NSCursor) {
|
|
guard object != .iBeam else { return }
|
|
super.addCursorRect(rect, cursor: object)
|
|
}
|
|
|
|
/// Gives this class its own `cursorUpdate:` that sets the arrow; 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 arrowCursorUpdate: Void = {
|
|
let block: @convention(block) (AnyObject, NSEvent) -> Void = { _, _ in NSCursor.arrow.set() }
|
|
let selector = #selector(NSResponder.cursorUpdate(with:))
|
|
let types = method_getTypeEncoding(class_getInstanceMethod(NSView.self, selector)!)
|
|
class_addMethod(HelderTerminalView.self, selector, imp_implementationWithBlock(block), types)
|
|
}()
|
|
|
|
// 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) }
|
|
}
|
|
}
|
|
}
|