初始提交:terminalX 可运行态(M0/M1/M1.5 已真机验证)
- M0: libghostty SSH 终端(渲染/输入/连接)+ 白屏修复(OutputGate) + 会话状态机/自动重连 - M1: tsnet 用户态组网 + SSH-over-tsnet(fd 桥),shell 级真机验证;R5(Go+gvisor+C+++Swift 同进程) retire - M1.5: tmux -CC 原生 tab(MVP) - 结构: packages/(TXCore·TXTransport), apps/TerminalX, vendor/(libghostty-spm/libssh2/mbedtls/tsnet-bridge), artifacts/ - 文档: CLAUDE.md + docs/HANDOFF.md(新会话入口) - 环境: 认证代理→依赖 vendor 本地化;Go 在 ~/.local/go;仅模拟器/未签名 - 待续: M2 mosh, tmux 多 pane, M4 安全(host key/SE) Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
197
vendor/libghostty-spm/Sources/GhosttyTerminal/Controller/TerminalController+Callbacks.swift
vendored
Normal file
197
vendor/libghostty-spm/Sources/GhosttyTerminal/Controller/TerminalController+Callbacks.swift
vendored
Normal file
@@ -0,0 +1,197 @@
|
||||
//
|
||||
// TerminalController+Callbacks.swift
|
||||
// libghostty-spm
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import GhosttyKit
|
||||
|
||||
#if canImport(UIKit)
|
||||
import UIKit
|
||||
#elseif canImport(AppKit)
|
||||
import AppKit
|
||||
#endif
|
||||
|
||||
private enum TerminalCallbacks {
|
||||
static func wakeup(userdata: UnsafeMutableRawPointer?) {
|
||||
guard let userdata else { return }
|
||||
let controller = Unmanaged<TerminalController>.fromOpaque(userdata)
|
||||
.takeUnretainedValue()
|
||||
terminalRunOnMain {
|
||||
controller.handleWakeup()
|
||||
}
|
||||
}
|
||||
|
||||
static func action(
|
||||
appPtr: ghostty_app_t?,
|
||||
target: ghostty_target_s,
|
||||
action: ghostty_action_s
|
||||
) -> Bool {
|
||||
guard let appPtr else { return false }
|
||||
guard ghostty_app_userdata(appPtr) != nil else { return false }
|
||||
guard target.tag == GHOSTTY_TARGET_SURFACE else { return false }
|
||||
guard let surfacePtr = target.target.surface else { return false }
|
||||
guard let bridgePtr = ghostty_surface_userdata(surfacePtr) else { return false }
|
||||
|
||||
let bridge = Unmanaged<TerminalCallbackBridge>
|
||||
.fromOpaque(bridgePtr)
|
||||
.takeUnretainedValue()
|
||||
terminalRunOnMain {
|
||||
bridge.handleAction(action)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
static func closeSurface(
|
||||
userdata: UnsafeMutableRawPointer?,
|
||||
processAlive: Bool
|
||||
) {
|
||||
guard let userdata else { return }
|
||||
let bridge = Unmanaged<TerminalCallbackBridge>
|
||||
.fromOpaque(userdata)
|
||||
.takeUnretainedValue()
|
||||
terminalRunOnMain {
|
||||
bridge.handleClose(processAlive: processAlive)
|
||||
}
|
||||
}
|
||||
|
||||
static func writeClipboard(
|
||||
userdata _: UnsafeMutableRawPointer?,
|
||||
clipboard _: ghostty_clipboard_e,
|
||||
contents: UnsafePointer<ghostty_clipboard_content_s>?,
|
||||
contentsLen: Int,
|
||||
confirm _: Bool
|
||||
) {
|
||||
guard contentsLen > 0 else { return }
|
||||
guard let content = contents?.pointee else { return }
|
||||
guard let data = content.data else { return }
|
||||
let string = String(cString: data)
|
||||
|
||||
#if canImport(UIKit)
|
||||
UIPasteboard.general.string = string
|
||||
#elseif canImport(AppKit)
|
||||
let pasteboard = NSPasteboard.general
|
||||
pasteboard.clearContents()
|
||||
pasteboard.setString(string, forType: .string)
|
||||
#endif
|
||||
}
|
||||
|
||||
static func readClipboard(
|
||||
userdata: UnsafeMutableRawPointer?,
|
||||
clipboard _: ghostty_clipboard_e,
|
||||
opaquePtr: UnsafeMutableRawPointer?
|
||||
) -> Bool {
|
||||
guard let userdata, let opaquePtr else { return false }
|
||||
|
||||
let bridge = Unmanaged<TerminalCallbackBridge>
|
||||
.fromOpaque(userdata)
|
||||
.takeUnretainedValue()
|
||||
guard let surface = bridge.rawSurface else { return false }
|
||||
|
||||
#if canImport(UIKit)
|
||||
let string = UIPasteboard.general.string
|
||||
#elseif canImport(AppKit)
|
||||
let string = NSPasteboard.general.string(forType: .string)
|
||||
#endif
|
||||
|
||||
guard let string else {
|
||||
TerminalDebugLog.log(.input, "clipboard paste read empty")
|
||||
return false
|
||||
}
|
||||
TerminalDebugLog.log(
|
||||
.input,
|
||||
"clipboard paste read bytes=\(string.utf8.count) lines=\(TerminalInputText.lineCount(in: string))"
|
||||
)
|
||||
string.withCString { cString in
|
||||
ghostty_surface_complete_clipboard_request(surface, cString, opaquePtr, false)
|
||||
}
|
||||
TerminalDebugLog.log(.input, "clipboard paste complete")
|
||||
return true
|
||||
}
|
||||
|
||||
static func confirmReadClipboard(
|
||||
userdata: UnsafeMutableRawPointer?,
|
||||
string: UnsafePointer<CChar>?,
|
||||
opaquePtr: UnsafeMutableRawPointer?,
|
||||
request: ghostty_clipboard_request_e
|
||||
) {
|
||||
guard let userdata, let string, let opaquePtr else { return }
|
||||
|
||||
let bridge = Unmanaged<TerminalCallbackBridge>
|
||||
.fromOpaque(userdata)
|
||||
.takeUnretainedValue()
|
||||
guard let surface = bridge.rawSurface else { return }
|
||||
|
||||
let text = String(cString: string)
|
||||
TerminalDebugLog.log(
|
||||
.input,
|
||||
"clipboard paste confirm request=\(request.rawValue) bytes=\(text.utf8.count) lines=\(TerminalInputText.lineCount(in: text))"
|
||||
)
|
||||
text.withCString { cString in
|
||||
ghostty_surface_complete_clipboard_request(surface, cString, opaquePtr, true)
|
||||
}
|
||||
TerminalDebugLog.log(.input, "clipboard paste confirmed")
|
||||
}
|
||||
}
|
||||
|
||||
func terminalControllerWakeupCallback(userdata: UnsafeMutableRawPointer?) {
|
||||
TerminalCallbacks.wakeup(userdata: userdata)
|
||||
}
|
||||
|
||||
func terminalControllerActionCallback(
|
||||
appPtr: ghostty_app_t?,
|
||||
target: ghostty_target_s,
|
||||
action: ghostty_action_s
|
||||
) -> Bool {
|
||||
TerminalCallbacks.action(appPtr: appPtr, target: target, action: action)
|
||||
}
|
||||
|
||||
func terminalControllerCloseSurfaceCallback(
|
||||
userdata: UnsafeMutableRawPointer?,
|
||||
processAlive: Bool
|
||||
) {
|
||||
TerminalCallbacks.closeSurface(userdata: userdata, processAlive: processAlive)
|
||||
}
|
||||
|
||||
func terminalControllerWriteClipboardCallback(
|
||||
userdata: UnsafeMutableRawPointer?,
|
||||
clipboard: ghostty_clipboard_e,
|
||||
contents: UnsafePointer<ghostty_clipboard_content_s>?,
|
||||
contentsLen: Int,
|
||||
confirm: Bool
|
||||
) {
|
||||
TerminalCallbacks.writeClipboard(
|
||||
userdata: userdata,
|
||||
clipboard: clipboard,
|
||||
contents: contents,
|
||||
contentsLen: contentsLen,
|
||||
confirm: confirm
|
||||
)
|
||||
}
|
||||
|
||||
func terminalControllerReadClipboardCallback(
|
||||
userdata: UnsafeMutableRawPointer?,
|
||||
clipboard: ghostty_clipboard_e,
|
||||
opaquePtr: UnsafeMutableRawPointer?
|
||||
) -> Bool {
|
||||
TerminalCallbacks.readClipboard(
|
||||
userdata: userdata,
|
||||
clipboard: clipboard,
|
||||
opaquePtr: opaquePtr
|
||||
)
|
||||
}
|
||||
|
||||
func terminalControllerConfirmReadClipboardCallback(
|
||||
userdata: UnsafeMutableRawPointer?,
|
||||
string: UnsafePointer<CChar>?,
|
||||
opaquePtr: UnsafeMutableRawPointer?,
|
||||
request: ghostty_clipboard_request_e
|
||||
) {
|
||||
TerminalCallbacks.confirmReadClipboard(
|
||||
userdata: userdata,
|
||||
string: string,
|
||||
opaquePtr: opaquePtr,
|
||||
request: request
|
||||
)
|
||||
}
|
||||
218
vendor/libghostty-spm/Sources/GhosttyTerminal/Controller/TerminalController+Config.swift
vendored
Normal file
218
vendor/libghostty-spm/Sources/GhosttyTerminal/Controller/TerminalController+Config.swift
vendored
Normal file
@@ -0,0 +1,218 @@
|
||||
//
|
||||
// TerminalController+Config.swift
|
||||
// libghostty-spm
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import GhosttyKit
|
||||
|
||||
extension TerminalController {
|
||||
@discardableResult
|
||||
public func updateConfigSource(_ source: ConfigSource) -> Bool {
|
||||
guard source != configSource else { return true }
|
||||
|
||||
switch Self.prepareConfig(source: source) {
|
||||
case let .success(value):
|
||||
applyPreparedConfigToRuntime(value, source: source)
|
||||
return true
|
||||
|
||||
case let .failure(issue):
|
||||
lastConfigurationIssue = issue.description
|
||||
Self.reportConfigurationIssue(issue.description)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func applyResolvedConfig(
|
||||
_ resolved: (source: ConfigSource, contents: String),
|
||||
willChange: (() -> Void)?,
|
||||
applyState: () -> Void = {}
|
||||
) -> Bool {
|
||||
guard resolved.source != configSource else {
|
||||
// ObservableObject subscribers expect will-change semantics.
|
||||
willChange?()
|
||||
applyState()
|
||||
renderedConfigContents = resolved.contents
|
||||
return true
|
||||
}
|
||||
|
||||
switch Self.prepareConfig(source: resolved.source) {
|
||||
case let .success(prepared):
|
||||
// Notify after validation succeeds, but before committed state
|
||||
// changes become visible through computed TerminalViewState APIs.
|
||||
willChange?()
|
||||
applyState()
|
||||
applyPreparedConfigToRuntime(prepared, source: resolved.source)
|
||||
return true
|
||||
|
||||
case let .failure(issue):
|
||||
lastConfigurationIssue = issue.description
|
||||
Self.reportConfigurationIssue(issue.description)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
private func applyPreparedConfigToRuntime(_ prepared: PreparedConfig, source: ConfigSource) {
|
||||
let previousConfig = config
|
||||
let previousManagedConfigURL = managedConfigURL
|
||||
let nextConfig = prepared.rawValue
|
||||
|
||||
if let app {
|
||||
ghostty_app_update_config(app, nextConfig)
|
||||
}
|
||||
|
||||
for bridge in retainedBridges {
|
||||
guard let surface = bridge.rawSurface else { continue }
|
||||
ghostty_surface_update_config(surface, nextConfig)
|
||||
}
|
||||
|
||||
applyPreparedConfig(prepared, source: source)
|
||||
|
||||
if let previousConfig {
|
||||
ghostty_config_free(previousConfig)
|
||||
}
|
||||
|
||||
if let previousManagedConfigURL, previousManagedConfigURL != managedConfigURL {
|
||||
try? FileManager.default.removeItem(at: previousManagedConfigURL)
|
||||
}
|
||||
}
|
||||
|
||||
func applyInitialConfig(source: ConfigSource) {
|
||||
switch Self.prepareConfig(source: source) {
|
||||
case let .success(prepared):
|
||||
applyPreparedConfig(prepared, source: source)
|
||||
|
||||
case let .failure(issue):
|
||||
lastConfigurationIssue = issue.description
|
||||
Self.reportConfigurationIssue(issue.description)
|
||||
|
||||
guard source != .none else { return }
|
||||
guard case let .success(fallback) = Self.prepareConfig(source: ConfigSource.none) else {
|
||||
return
|
||||
}
|
||||
applyPreparedConfig(fallback, source: .none)
|
||||
}
|
||||
}
|
||||
|
||||
func createApp() {
|
||||
guard let cfg = config else { return }
|
||||
|
||||
let userdata = Unmanaged.passUnretained(self).toOpaque()
|
||||
|
||||
var runtimeConfig = ghostty_runtime_config_s()
|
||||
runtimeConfig.userdata = userdata
|
||||
runtimeConfig.supports_selection_clipboard = true
|
||||
runtimeConfig.wakeup_cb = terminalControllerWakeupCallback
|
||||
runtimeConfig.action_cb = terminalControllerActionCallback
|
||||
runtimeConfig.close_surface_cb = terminalControllerCloseSurfaceCallback
|
||||
runtimeConfig.write_clipboard_cb = terminalControllerWriteClipboardCallback
|
||||
runtimeConfig.read_clipboard_cb = terminalControllerReadClipboardCallback
|
||||
runtimeConfig.confirm_read_clipboard_cb = terminalControllerConfirmReadClipboardCallback
|
||||
|
||||
app = ghostty_app_new(&runtimeConfig, cfg)
|
||||
}
|
||||
|
||||
private static func prepareConfig(
|
||||
source: ConfigSource
|
||||
) -> Result<PreparedConfig, ConfigurationIssue> {
|
||||
let resolvedContents: String
|
||||
let configPath: String
|
||||
let managedConfigURL: URL?
|
||||
|
||||
switch source {
|
||||
case .none:
|
||||
resolvedContents = defaultRenderedConfig
|
||||
switch writeManagedConfig(contents: resolvedContents) {
|
||||
case let .success(url):
|
||||
managedConfigURL = url
|
||||
configPath = url.path
|
||||
case let .failure(issue):
|
||||
return .failure(issue)
|
||||
}
|
||||
|
||||
case let .generated(contents):
|
||||
resolvedContents = contents
|
||||
switch writeManagedConfig(contents: contents) {
|
||||
case let .success(url):
|
||||
managedConfigURL = url
|
||||
configPath = url.path
|
||||
case let .failure(issue):
|
||||
return .failure(issue)
|
||||
}
|
||||
|
||||
case let .file(path):
|
||||
do {
|
||||
resolvedContents = try String(contentsOfFile: path, encoding: .utf8)
|
||||
} catch {
|
||||
return .failure(ConfigurationIssue("failed to load ghostty config template: \(error)"))
|
||||
}
|
||||
managedConfigURL = nil
|
||||
configPath = path
|
||||
}
|
||||
|
||||
guard let rawValue = ghostty_config_new() else {
|
||||
if let managedConfigURL {
|
||||
try? FileManager.default.removeItem(at: managedConfigURL)
|
||||
}
|
||||
return .failure(ConfigurationIssue("ghostty_config_new returned nil"))
|
||||
}
|
||||
|
||||
ghostty_config_load_file(rawValue, configPath)
|
||||
ghostty_config_finalize(rawValue)
|
||||
|
||||
let diagnostics = configDiagnostics(from: rawValue)
|
||||
guard diagnostics.isEmpty else {
|
||||
ghostty_config_free(rawValue)
|
||||
if let managedConfigURL {
|
||||
try? FileManager.default.removeItem(at: managedConfigURL)
|
||||
}
|
||||
return .failure(
|
||||
ConfigurationIssue("ghostty config diagnostics: \(diagnostics.joined(separator: " | "))")
|
||||
)
|
||||
}
|
||||
|
||||
return .success(
|
||||
PreparedConfig(
|
||||
rawValue: rawValue,
|
||||
managedConfigURL: managedConfigURL,
|
||||
renderedContents: resolvedContents
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
private static func writeManagedConfig(contents: String) -> Result<URL, ConfigurationIssue> {
|
||||
let url = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("ghostty-config-\(UUID().uuidString)")
|
||||
.appendingPathExtension("conf")
|
||||
|
||||
do {
|
||||
try contents.write(to: url, atomically: true, encoding: .utf8)
|
||||
return .success(url)
|
||||
} catch {
|
||||
return .failure(ConfigurationIssue("failed to write generated ghostty config: \(error)"))
|
||||
}
|
||||
}
|
||||
|
||||
private static func configDiagnostics(from config: ghostty_config_t) -> [String] {
|
||||
let count = ghostty_config_diagnostics_count(config)
|
||||
guard count > 0 else { return [] }
|
||||
|
||||
return (0 ..< count).compactMap { index in
|
||||
let diagnostic = ghostty_config_get_diagnostic(config, index)
|
||||
guard let message = diagnostic.message else { return nil }
|
||||
return String(cString: message)
|
||||
}
|
||||
}
|
||||
|
||||
private static func reportConfigurationIssue(_ message: String) {
|
||||
NSLog("GhosttyTerminal configuration issue: %@", message)
|
||||
}
|
||||
|
||||
private func applyPreparedConfig(_ prepared: PreparedConfig, source: ConfigSource) {
|
||||
config = prepared.rawValue
|
||||
managedConfigURL = prepared.managedConfigURL
|
||||
renderedConfigContents = prepared.renderedContents
|
||||
configSource = source
|
||||
lastConfigurationIssue = nil
|
||||
}
|
||||
}
|
||||
145
vendor/libghostty-spm/Sources/GhosttyTerminal/Controller/TerminalController+Surface.swift
vendored
Normal file
145
vendor/libghostty-spm/Sources/GhosttyTerminal/Controller/TerminalController+Surface.swift
vendored
Normal file
@@ -0,0 +1,145 @@
|
||||
//
|
||||
// TerminalController+Surface.swift
|
||||
// libghostty-spm
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import GhosttyKit
|
||||
|
||||
extension TerminalController {
|
||||
/// Creates a new Ghostty surface with the given configuration.
|
||||
///
|
||||
/// The `platformSetup` closure lets the caller fill in
|
||||
/// platform-specific fields (`platform_tag`, `platform`, `scale_factor`)
|
||||
/// on the raw surface config struct before the surface is created.
|
||||
func createSurface(
|
||||
bridge: TerminalCallbackBridge,
|
||||
configuration: TerminalSurfaceOptions,
|
||||
platformSetup: (inout ghostty_surface_config_s) -> Void
|
||||
) -> ghostty_surface_t? {
|
||||
guard let app else { return nil }
|
||||
|
||||
var surfaceConfig = ghostty_surface_config_new()
|
||||
surfaceConfig.userdata = Unmanaged.passUnretained(bridge).toOpaque()
|
||||
surfaceConfig.context = configuration.context.ghosttyValue
|
||||
configureBackend(&surfaceConfig, from: configuration)
|
||||
|
||||
if let fontSize = configuration.fontSize {
|
||||
surfaceConfig.font_size = fontSize
|
||||
}
|
||||
|
||||
// Like `working_directory` below, the pointers only need to outlive
|
||||
// `ghostty_surface_new`, which copies the values during surface init.
|
||||
return withEnvVarEntries(configuration.envVars) { entries, count in
|
||||
surfaceConfig.env_vars = entries
|
||||
surfaceConfig.env_var_count = count
|
||||
return finalizeSurface(
|
||||
app: app,
|
||||
bridge: bridge,
|
||||
configuration: configuration,
|
||||
config: &surfaceConfig,
|
||||
workingDirectory: configuration.workingDirectory,
|
||||
platformSetup: platformSetup
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `body` with a C representation of `envVars` (`ghostty_env_var_s`
|
||||
/// entries) that stays valid for the duration of the call.
|
||||
private func withEnvVarEntries<T>(
|
||||
_ envVars: [String: String],
|
||||
_ body: (UnsafeMutablePointer<ghostty_env_var_s>?, Int) -> T
|
||||
) -> T {
|
||||
guard !envVars.isEmpty else { return body(nil, 0) }
|
||||
let strings: [(key: UnsafeMutablePointer<CChar>, value: UnsafeMutablePointer<CChar>)] =
|
||||
envVars.map { (strdup($0.key), strdup($0.value)) }
|
||||
defer {
|
||||
for entry in strings {
|
||||
free(entry.key)
|
||||
free(entry.value)
|
||||
}
|
||||
}
|
||||
var entries = strings.map { ghostty_env_var_s(key: $0.key, value: $0.value) }
|
||||
return entries.withUnsafeMutableBufferPointer { buffer in
|
||||
body(buffer.baseAddress, buffer.count)
|
||||
}
|
||||
}
|
||||
|
||||
func retain(_ bridge: TerminalCallbackBridge) {
|
||||
retainedBridges.append(bridge)
|
||||
}
|
||||
|
||||
func remove(_ bridge: TerminalCallbackBridge) {
|
||||
retainedBridges.removeAll { $0 === bridge }
|
||||
}
|
||||
|
||||
var retainedBridgeCount: Int {
|
||||
retainedBridges.count
|
||||
}
|
||||
|
||||
private func configureBackend(
|
||||
_ config: inout ghostty_surface_config_s,
|
||||
from options: TerminalSurfaceOptions
|
||||
) {
|
||||
guard case let .inMemory(session) = options.backend else {
|
||||
config.backend = GHOSTTY_SURFACE_IO_BACKEND_EXEC
|
||||
return
|
||||
}
|
||||
|
||||
config.backend = GHOSTTY_SURFACE_IO_BACKEND_HOST_MANAGED
|
||||
config.receive_userdata = Unmanaged.passUnretained(session).toOpaque()
|
||||
config.receive_buffer = InMemoryTerminalSession.receiveBufferCallback
|
||||
config.receive_resize = InMemoryTerminalSession.receiveResizeCallback
|
||||
}
|
||||
|
||||
private func finalizeSurface(
|
||||
app: ghostty_app_t,
|
||||
bridge: TerminalCallbackBridge,
|
||||
configuration: TerminalSurfaceOptions,
|
||||
config: inout ghostty_surface_config_s,
|
||||
workingDirectory: String?,
|
||||
platformSetup: (inout ghostty_surface_config_s) -> Void
|
||||
) -> ghostty_surface_t? {
|
||||
guard let workingDirectory else {
|
||||
return buildSurface(
|
||||
app: app,
|
||||
bridge: bridge,
|
||||
configuration: configuration,
|
||||
config: &config,
|
||||
platformSetup: platformSetup
|
||||
)
|
||||
}
|
||||
|
||||
return workingDirectory.withCString { ptr in
|
||||
config.working_directory = ptr
|
||||
return buildSurface(
|
||||
app: app,
|
||||
bridge: bridge,
|
||||
configuration: configuration,
|
||||
config: &config,
|
||||
platformSetup: platformSetup
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private func buildSurface(
|
||||
app: ghostty_app_t,
|
||||
bridge: TerminalCallbackBridge,
|
||||
configuration: TerminalSurfaceOptions,
|
||||
config: inout ghostty_surface_config_s,
|
||||
platformSetup: (inout ghostty_surface_config_s) -> Void
|
||||
) -> ghostty_surface_t? {
|
||||
platformSetup(&config)
|
||||
guard let surface = ghostty_surface_new(app, &config) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
retain(bridge)
|
||||
|
||||
if case let .inMemory(session) = configuration.backend {
|
||||
session.setSurface(surface)
|
||||
}
|
||||
|
||||
return surface
|
||||
}
|
||||
}
|
||||
313
vendor/libghostty-spm/Sources/GhosttyTerminal/Controller/TerminalController.swift
vendored
Normal file
313
vendor/libghostty-spm/Sources/GhosttyTerminal/Controller/TerminalController.swift
vendored
Normal file
@@ -0,0 +1,313 @@
|
||||
//
|
||||
// TerminalController.swift
|
||||
// libghostty-spm
|
||||
//
|
||||
// Created by Lakr233 on 2026/3/16.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import GhosttyKit
|
||||
|
||||
#if canImport(UIKit)
|
||||
import UIKit
|
||||
#elseif canImport(AppKit)
|
||||
import AppKit
|
||||
#endif
|
||||
|
||||
/// Manages the Ghostty app lifecycle, configuration loading, and surface
|
||||
/// creation.
|
||||
///
|
||||
/// `TerminalController` is the **single source of truth** for terminal
|
||||
/// configuration, including the base config, per-session overrides, theme
|
||||
/// colors, and the active color scheme. When any of these change the
|
||||
/// controller re-resolves the effective config and pushes it to ghostty.
|
||||
@MainActor
|
||||
public final class TerminalController {
|
||||
struct PreparedConfig {
|
||||
let rawValue: ghostty_config_t
|
||||
let managedConfigURL: URL?
|
||||
let renderedContents: String
|
||||
}
|
||||
|
||||
struct ConfigurationIssue: Error, CustomStringConvertible {
|
||||
let description: String
|
||||
|
||||
init(_ description: String) {
|
||||
self.description = description
|
||||
}
|
||||
}
|
||||
|
||||
public enum ConfigSource: Sendable, Hashable {
|
||||
case none
|
||||
case file(String)
|
||||
case generated(String)
|
||||
}
|
||||
|
||||
public static let shared = TerminalController()
|
||||
|
||||
static let defaultRenderedConfig = TerminalConfiguration.default.rendered
|
||||
private static var runtimeInitialized = false
|
||||
|
||||
nonisolated(unsafe) var app: ghostty_app_t?
|
||||
nonisolated(unsafe) var config: ghostty_config_t?
|
||||
var retainedBridges: [TerminalCallbackBridge] = []
|
||||
var configSource: ConfigSource
|
||||
var managedConfigURL: URL?
|
||||
var renderedConfigContents: String = TerminalController.defaultRenderedConfig
|
||||
|
||||
public internal(set) var lastConfigurationIssue: String?
|
||||
var onWakeup: (() -> Void)?
|
||||
var shouldProcessWakeup: (() -> Bool)?
|
||||
|
||||
// MARK: - Config Resolution State
|
||||
|
||||
/// The base config before theme/colorScheme are applied.
|
||||
private let baseConfigSource: ConfigSource
|
||||
private var baseConfigTemplate: String = ""
|
||||
|
||||
/// Per-session configuration overrides (e.g. font size changes).
|
||||
public private(set) var terminalConfiguration: TerminalConfiguration
|
||||
|
||||
/// Color theme (light + dark variants).
|
||||
public private(set) var theme: TerminalTheme
|
||||
|
||||
/// The currently active color scheme.
|
||||
public private(set) var effectiveColorScheme: TerminalColorScheme = .light
|
||||
|
||||
// MARK: - Public Accessors
|
||||
|
||||
public var currentConfigSource: ConfigSource {
|
||||
configSource
|
||||
}
|
||||
|
||||
public var renderedConfig: String {
|
||||
renderedConfigContents
|
||||
}
|
||||
|
||||
// MARK: - Initializers
|
||||
|
||||
/// Creates a controller with the default terminal configuration.
|
||||
public convenience init() {
|
||||
self.init(configuration: .default)
|
||||
}
|
||||
|
||||
/// Creates a controller with a fully custom configuration.
|
||||
public convenience init(
|
||||
configuration: TerminalConfiguration,
|
||||
theme: TerminalTheme = .default
|
||||
) {
|
||||
self.init(
|
||||
configSource: .generated(configuration.rendered),
|
||||
theme: theme
|
||||
)
|
||||
}
|
||||
|
||||
/// Creates a controller by composing additional commands on top of
|
||||
/// the default configuration.
|
||||
///
|
||||
/// TerminalController {
|
||||
/// $0.withBackgroundOpacity(0)
|
||||
/// $0.withCustom("keybind", "super+k=text:\\x0c")
|
||||
/// }
|
||||
public convenience init(
|
||||
theme: TerminalTheme = .default,
|
||||
configure: (inout TerminalConfiguration.Builder) -> Void
|
||||
) {
|
||||
self.init(
|
||||
configuration: TerminalConfiguration(
|
||||
startingFrom: .default,
|
||||
configure: configure
|
||||
),
|
||||
theme: theme
|
||||
)
|
||||
}
|
||||
|
||||
/// Creates a controller that loads its configuration from a file.
|
||||
public convenience init(
|
||||
configFilePath: String?,
|
||||
theme: TerminalTheme = .default
|
||||
) {
|
||||
guard let configFilePath else {
|
||||
self.init(configSource: .none, theme: theme)
|
||||
return
|
||||
}
|
||||
self.init(configSource: .file(configFilePath), theme: theme)
|
||||
}
|
||||
|
||||
/// Low-level initialiser for full control over the config source.
|
||||
public init(
|
||||
configSource: ConfigSource = .none,
|
||||
theme: TerminalTheme = .default,
|
||||
terminalConfiguration: TerminalConfiguration = .init()
|
||||
) {
|
||||
Self.initializeRuntimeIfNeeded()
|
||||
|
||||
baseConfigSource = configSource
|
||||
self.theme = theme
|
||||
self.terminalConfiguration = terminalConfiguration
|
||||
self.configSource = configSource
|
||||
|
||||
// Load the base config (without theme) so ghostty validates it.
|
||||
applyInitialConfig(source: configSource)
|
||||
baseConfigTemplate = renderedConfigContents
|
||||
|
||||
// Now apply theme on top and push to ghostty.
|
||||
reconfigure()
|
||||
createApp()
|
||||
}
|
||||
|
||||
// MARK: - Color Scheme
|
||||
|
||||
/// Updates the active color scheme and reconfigures the terminal.
|
||||
///
|
||||
/// Called by platform views when the OS appearance changes. This is
|
||||
/// the only method views need to call — the controller handles all
|
||||
/// config resolution internally.
|
||||
public func setColorScheme(_ scheme: TerminalColorScheme) {
|
||||
setColorScheme(scheme, willChange: nil)
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func setColorScheme(
|
||||
_ scheme: TerminalColorScheme,
|
||||
willChange: (() -> Void)?
|
||||
) -> Bool {
|
||||
let previous = effectiveColorScheme
|
||||
guard scheme != previous else {
|
||||
if let app {
|
||||
ghostty_app_set_color_scheme(app, scheme.ghosttyValue)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
let resolved = resolveEffectiveConfig(colorScheme: scheme)
|
||||
guard applyResolvedConfig(
|
||||
resolved,
|
||||
willChange: willChange,
|
||||
applyState: { effectiveColorScheme = scheme }
|
||||
) else {
|
||||
return false
|
||||
}
|
||||
|
||||
if let app {
|
||||
ghostty_app_set_color_scheme(app, scheme.ghosttyValue)
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// MARK: - Theme
|
||||
|
||||
/// Updates the theme and reconfigures the terminal.
|
||||
@discardableResult
|
||||
public func setTheme(_ theme: TerminalTheme) -> Bool {
|
||||
setTheme(theme, willChange: nil)
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func setTheme(
|
||||
_ theme: TerminalTheme,
|
||||
willChange: (() -> Void)?
|
||||
) -> Bool {
|
||||
guard theme != self.theme else { return false }
|
||||
let resolved = resolveEffectiveConfig(theme: theme)
|
||||
return applyResolvedConfig(
|
||||
resolved,
|
||||
willChange: willChange,
|
||||
applyState: { self.theme = theme }
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Terminal Configuration
|
||||
|
||||
/// Updates per-session configuration overrides and reconfigures.
|
||||
@discardableResult
|
||||
public func setTerminalConfiguration(
|
||||
_ terminalConfiguration: TerminalConfiguration
|
||||
) -> Bool {
|
||||
setTerminalConfiguration(terminalConfiguration, willChange: nil)
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func setTerminalConfiguration(
|
||||
_ terminalConfiguration: TerminalConfiguration,
|
||||
willChange: (() -> Void)?
|
||||
) -> Bool {
|
||||
guard terminalConfiguration != self.terminalConfiguration else { return false }
|
||||
let resolved = resolveEffectiveConfig(terminalConfiguration: terminalConfiguration)
|
||||
return applyResolvedConfig(
|
||||
resolved,
|
||||
willChange: willChange,
|
||||
applyState: { self.terminalConfiguration = terminalConfiguration }
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Config Resolution
|
||||
|
||||
@discardableResult
|
||||
private func reconfigure() -> Bool {
|
||||
applyResolvedConfig(resolveEffectiveConfig(), willChange: nil)
|
||||
}
|
||||
|
||||
private func resolveEffectiveConfig() -> (
|
||||
source: ConfigSource, contents: String
|
||||
) {
|
||||
resolveEffectiveConfig(
|
||||
theme: theme,
|
||||
terminalConfiguration: terminalConfiguration,
|
||||
colorScheme: effectiveColorScheme
|
||||
)
|
||||
}
|
||||
|
||||
private func resolveEffectiveConfig(
|
||||
theme: TerminalTheme? = nil,
|
||||
terminalConfiguration: TerminalConfiguration? = nil,
|
||||
colorScheme: TerminalColorScheme? = nil
|
||||
) -> (source: ConfigSource, contents: String) {
|
||||
let nextTheme = theme ?? self.theme
|
||||
let nextTerminalConfiguration = terminalConfiguration ?? self.terminalConfiguration
|
||||
let nextColorScheme = colorScheme ?? effectiveColorScheme
|
||||
let themeConfig = nextTheme.configuration(for: nextColorScheme)
|
||||
if nextTerminalConfiguration.isEmpty, themeConfig.isEmpty {
|
||||
return (baseConfigSource, baseConfigTemplate)
|
||||
}
|
||||
|
||||
let contents = GhosttyConfigRenderer.render(
|
||||
baseContents: baseConfigTemplate,
|
||||
configuration: nextTerminalConfiguration,
|
||||
theme: themeConfig
|
||||
)
|
||||
return (.generated(contents), contents)
|
||||
}
|
||||
|
||||
// MARK: - Tick
|
||||
|
||||
public func tick() {
|
||||
guard let app else { return }
|
||||
ghostty_app_tick(app)
|
||||
}
|
||||
|
||||
func handleWakeup() {
|
||||
guard shouldProcessWakeup?() ?? true else {
|
||||
TerminalDebugLog.log(.lifecycle, "wakeup suspended")
|
||||
return
|
||||
}
|
||||
|
||||
tick()
|
||||
onWakeup?()
|
||||
}
|
||||
|
||||
private static func initializeRuntimeIfNeeded() {
|
||||
guard !runtimeInitialized else { return }
|
||||
runtimeInitialized = true
|
||||
ghostty_init(0, nil)
|
||||
}
|
||||
|
||||
deinit {
|
||||
if let app { ghostty_app_free(app) }
|
||||
if let config { ghostty_config_free(config) }
|
||||
if let managedConfigURL {
|
||||
try? FileManager.default.removeItem(at: managedConfigURL)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user