restores Helder in all its glory

This commit is contained in:
2026-09-28 11:34:49 +02:00
parent c2b38b853c
commit 1d29d0952d
280 changed files with 29205 additions and 7 deletions
@@ -0,0 +1,30 @@
import AppKit
import SwiftUI
/// Column D: the agent terminal over a plain shell, split at `layout.agentFraction`.
public struct AgentColumn: View {
let model: WorkspaceModel
public init(model: WorkspaceModel) {
self.model = model
}
public var body: some View {
GeometryReader { proxy in
VStack(spacing: 0) {
TerminalPane(kind: .agent, store: model.terminal, scale: model.layout.textScale)
.frame(height: proxy.size.height * model.layout.agentFraction)
Splitter(.horizontal) { model.layout.dragAgentSplit(by: $0, height: proxy.size.height) }
TerminalPane(kind: .shell, store: model.terminal, scale: model.layout.textScale)
}
}
// A new project brings a new store, and with it fresh panes and processes.
.id(ObjectIdentifier(model.terminal))
.background(Palette.panel)
.onChange(of: model.focusRequest) { _, request in
guard request?.target == .panel(.terminal), let view = model.terminal.agent as? NSView else { return }
view.window?.makeFirstResponder(view)
model.focusTaken(.panel(.terminal))
}
}
}
@@ -0,0 +1,131 @@
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<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)
}
/// 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) }
}
}
}
@@ -0,0 +1,79 @@
import AppKit
import HelderCore
import SwiftTerm
/// Maps the config's CSS colour table onto SwiftTerm's ANSI palette.
enum TerminalColors {
/// Channels are 16-bit in SwiftTerm; a colour the config cannot parse falls back to the default theme's.
static func ansi(_ theme: TerminalTheme) -> [SwiftTerm.Color] {
let fallback = TerminalTheme().ansi
return zip(theme.ansi, fallback).map { value, backup in
let ns = (NSColor(css: value) ?? NSColor(css: backup) ?? .white).usingColorSpace(.sRGB) ?? .white
return SwiftTerm.Color(red: UInt16(ns.redComponent * 65535),
green: UInt16(ns.greenComponent * 65535),
blue: UInt16(ns.blueComponent * 65535))
}
}
/// One theme entry as an AppKit colour, with the default theme's value as fallback.
static func color(_ value: String, fallback: String) -> NSColor {
NSColor(css: value) ?? NSColor(css: fallback) ?? .white
}
}
/// Everything in `config.terminal` that SwiftTerm can express. Line height and letter
/// spacing have no SwiftTerm equivalent, so they are not applied.
enum TerminalAppearance {
static func cursorStyle(_ style: TerminalCursorStyle, blink: Bool) -> CursorStyle {
switch (style, blink) {
case (.bar, true): .blinkBar
case (.bar, false): .steadyBar
case (.block, true): .blinkBlock
case (.block, false): .steadyBlock
case (.underline, true): .blinkUnderline
case (.underline, false): .steadyUnderline
}
}
/// The configured family, else the bundled IBM Plex Mono at the terminal type size, times the window zoom.
static func font(_ settings: HelderConfig.Terminal, scale: Double = 1) -> NSFont {
FontRegistry.registerBundledFonts()
let size = CGFloat((settings.fontSize ?? Double(Typography.terminal.size)) * scale)
if let family = settings.fontFamily?.trimmingCharacters(in: .whitespaces), !family.isEmpty {
if let named = NSFont(name: family, size: size) { return named }
if let fromFamily = NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: size) {
return fromFamily
}
}
return NSFont(name: PlexFace.monoRegular.rawValue, size: size) ?? .monospacedSystemFont(ofSize: size, weight: .regular)
}
static func options(_ settings: HelderConfig.Terminal) -> TerminalOptions {
TerminalOptions(termName: "xterm-256color",
cursorStyle: cursorStyle(settings.cursorStyle, blink: settings.cursorBlink),
scrollback: max(0, settings.scrollback))
}
/// Restyles a running terminal; the buffer and the process are untouched.
@MainActor
static func apply(_ settings: HelderConfig.Terminal, scale: Double = 1, to view: TerminalView) {
let theme = settings.theme
let base = TerminalTheme()
let newFont = font(settings, scale: scale)
if view.font.fontName != newFont.fontName || view.font.pointSize != newFont.pointSize {
view.font = newFont
}
view.nativeBackgroundColor = TerminalColors.color(theme.background, fallback: base.background)
view.nativeForegroundColor = TerminalColors.color(theme.foreground, fallback: base.foreground)
view.caretColor = TerminalColors.color(theme.cursor, fallback: base.cursor)
view.caretTextColor = TerminalColors.color(theme.cursorAccent, fallback: base.cursorAccent)
view.selectedTextBackgroundColor = TerminalColors.color(theme.selectionBackground, fallback: base.selectionBackground)
view.installColors(TerminalColors.ansi(theme))
view.useBrightColors = settings.boldIsBright
view.optionAsMetaKey = settings.optionIsMeta
view.terminal.setCursorStyle(cursorStyle(settings.cursorStyle, blink: settings.cursorBlink))
if view.terminal.options.scrollback != settings.scrollback {
view.terminal.changeScrollback(max(0, settings.scrollback))
}
}
}
@@ -0,0 +1,49 @@
import AppKit
import HelderCore
import SwiftUI
/// One terminal pane: the live terminal fills it, with no header.
struct TerminalPane: View {
let kind: TerminalKind
let store: TerminalStore
/// The window zoom (⌘+ ⌘− ⌘0).
var scale: Double = 1
var body: some View {
TerminalHost(kind: kind, store: store, settings: store.config.terminal, scale: scale, isConfigured: store.isConfigured)
.padding(12)
.background(Color(nsColor: TerminalColors.color(store.config.terminal.theme.background,
fallback: TerminalTheme().background)))
}
}
/// Hosts the pane's `HelderTerminalView`. The view lives in the store, so SwiftUI rebuilding
/// this representable never restarts the process.
private struct TerminalHost: NSViewRepresentable {
let kind: TerminalKind
let store: TerminalStore
let settings: HelderConfig.Terminal
let scale: Double
let isConfigured: Bool
func makeNSView(context: Context) -> HelderTerminalView {
if let existing = store.session(kind) as? HelderTerminalView { return existing }
let view = HelderTerminalView(kind: kind, store: store)
store.attach(view, as: kind)
return view
}
func updateNSView(_ view: HelderTerminalView, context: Context) {
if view.appliedSettings != settings || view.appliedScale != scale {
view.appliedSettings = settings
view.appliedScale = scale
TerminalAppearance.apply(settings, scale: scale, to: view)
}
if isConfigured && !view.hasStarted {
store.start(kind, on: view)
if kind == .agent {
DispatchQueue.main.async { view.window?.makeFirstResponder(view) }
}
}
}
}