Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

TerminalSurfaceView.swift

1,385 lines50.2 KB

1import GhosttyKit
2import QuartzCore
3import SwiftUI
4import UIKit
5​
6/// Ghostty's worker threads wake the host to drain its bounded app mailbox.
7/// Coalesce wakeups without polling or touching the native app off the main thread.
8private final class GhosttyAppEventLoop: @unchecked Sendable {
9 private let lock = NSLock()
10 private var scheduled = false
11 @MainActor var app: ghostty_app_t?
12​
13 @MainActor init() {}
14​
15 func wakeup() {
16 lock.lock()
17 guard !scheduled else { lock.unlock(); return }
18 scheduled = true
19 lock.unlock()
20 DispatchQueue.main.async { [self] in
21 lock.lock()
22 scheduled = false
23 lock.unlock()
24 if let app { ghostty_app_tick(app) }
25 }
26 }
28​
29private final class GhosttyRetirementFence: @unchecked Sendable {
30 private let lock = NSLock()
31 private var delivered = false
32 private let completion: @MainActor () -> Void
33​
34 init(completion: @escaping @MainActor () -> Void) { self.completion = completion }
35​
36 func complete() {
37 lock.lock()
38 guard !delivered else { lock.unlock(); return }
39 delivered = true
40 lock.unlock()
41 DispatchQueue.main.async { [self] in
42 completion()
43 // The native callback owns a retain until the I/O thread stops.
44 Unmanaged.passUnretained(self).release()
45 }
46 }
48​
49struct GhosttyTerminalSurface: UIViewRepresentable {
50 @SwiftUI.Environment(\.colorScheme) private var colorScheme
51 let terminalKey: String
52 let lifecycleVersion: Int
53 let buffer: String
54 let fontSize: CGFloat
55 let isRunning: Bool
56 let hostPlatform: TerminalHostPlatform
57 let focusRequest: Int
58 let onInput: (String) -> Void
59 let onPaste: (String) -> Void
60 let onResize: (Int, Int) -> Void
61 let onClear: () -> Void
62 let onFontSizeStep: (Int) -> Void
63 var onAttachOutput: ((String) -> Void)? = nil
64​
65 func makeUIView(context _: Context) -> GhosttyTerminalView {
66 let view = GhosttyTerminalView()
67 configure(view)
68 return view
69 }
70​
71 func updateUIView(_ view: GhosttyTerminalView, context _: Context) {
72 configure(view)
73 }
74​
75 static func dismantleUIView(_ view: GhosttyTerminalView, coordinator _: ()) {
76 view.tearDown()
77 }
78​
79 private func configure(_ view: GhosttyTerminalView) {
80 view.isDarkMode = colorScheme == .dark
81 view.onInput = onInput
82 view.onPaste = onPaste
83 view.onResize = onResize
84 view.onClear = onClear
85 view.onFontSizeStep = onFontSizeStep
86 view.onAttachOutput = onAttachOutput
87 view.terminalKey = terminalKey
88 view.lifecycleVersion = lifecycleVersion
89 view.fontSize = fontSize
90 view.isRunning = isRunning
91 view.hostPlatform = hostPlatform
92 view.buffer = buffer
93 view.focusRequest = focusRequest
94 }
96​
97enum TerminalHostPlatform: Equatable {
98 case mac
99 case linux
100 case windows
101 case unknown
102​
103 init(os: String?) {
104 self = switch os {
105 case "darwin": .mac
106 case "linux": .linux
107 case "windows": .windows
108 default: .unknown
109 }
110 }
112​
113enum TerminalInputModifier: Equatable {
114 case command
115 case control
117​
118enum TerminalInputAction: Equatable {
119 case write(String)
120 case paste
122​
123enum TerminalInputEncoder {
124 // TerminalWriteInput.data is limited to UTF-16 code units, not Swift characters.
125 static let maximumWriteLength = 65_536
126​
127 static func modified(
128 _ input: String,
129 modifier: TerminalInputModifier,
130 hostPlatform: TerminalHostPlatform
131 ) -> TerminalInputAction {
132 let pasteModifier: TerminalInputModifier = hostPlatform == .mac ? .command : .control
133 if modifier == pasteModifier, input.lowercased() == "v" {
134 return .paste
135 }
136 return .write(modifier == .control ? applyingControl(to: input) : "\u{1B}\(input)")
137 }
138​
139 static func applyingControl(to input: String) -> String {
140 guard let scalar = input.lowercased().unicodeScalars.first else { return input }
141 return controlSequence(for: scalar) ?? input
142 }
143​
144 static func controlSequence(for scalar: Unicode.Scalar) -> String? {
145 switch scalar {
146 case "a"..."z": return UnicodeScalar(scalar.value - 96).map(String.init)
147 case " ", "@": return "\u{00}"
148 case "[": return "\u{1B}"
149 case "\\": return "\u{1C}"
150 case "]": return "\u{1D}"
151 case "^": return "\u{1E}"
152 case "_", "-": return "\u{1F}"
153 case "?": return "\u{7F}"
154 default: return nil
155 }
156 }
157​
158 /// The native surface does not expose bracketed paste. Remove raw controls
159 /// and use carriage returns so pasted line breaks work in raw-mode programs.
160 static func paste(_ text: String) -> String {
161 var result = ""
162 result.reserveCapacity(text.utf8.count)
163 var previousWasCarriageReturn = false
164 for scalar in text.unicodeScalars {
165 switch scalar.value {
166 case 0x0A:
167 if !previousWasCarriageReturn { result.append("\r") }
168 case 0x00...0x08, 0x0B, 0x0C, 0x0E...0x1F, 0x7F:
169 result.append(" ")
170 default:
171 result.unicodeScalars.append(scalar)
172 }
173 previousWasCarriageReturn = scalar.value == 0x0D
174 }
175 return result
176 }
177​
178 static func chunks(_ data: String) -> [String] {
179 let units = data.utf16
180 var chunks = [String]()
181 var start = units.startIndex
182 while start < units.endIndex {
183 var end = units.index(start, offsetBy: maximumWriteLength, limitedBy: units.endIndex)
184 ?? units.endIndex
185 if end < units.endIndex, (0xD800...0xDBFF).contains(units[units.index(before: end)]) {
186 end = units.index(before: end)
187 }
188 chunks.append(String(decoding: units[start..<end], as: UTF16.self))
189 start = end
190 }
191 return chunks
192 }
194​
195enum TerminalText {
196 static func plainText(from value: String) -> String {
197 let withoutEscapes = value
198 .replacingOccurrences(
199 of: "\u{1B}\\][^\u{7}\u{1B}]*(?:\u{7}|\u{1B}\\\\)",
200 with: "",
201 options: .regularExpression
202 )
203 .replacingOccurrences(
204 of: "\u{1B}\\[[0-?]*[ -/]*[@-~]",
205 with: "",
206 options: .regularExpression
207 )
208 .replacingOccurrences(
209 of: "\u{1B}[@-_]",
210 with: "",
211 options: .regularExpression
212 )
213​
214 return withoutEscapes.reduce(into: "") { output, character in
215 if character == "\u{8}" || character == "\u{7F}" {
216 if !output.isEmpty { output.removeLast() }
217 return
218 }
219 if character == "\r" { return }
220 if character.unicodeScalars.count == 1,
221 let scalar = character.unicodeScalars.first,
222 scalar.value < 32,
223 character != "\n",
224 character != "\t" {
225 return
226 }
227 output.append(character)
228 }
229 }
231​
232/// Ghostty accepts appended bytes. Compare UTF-8 directly so unchanged buffers
233/// do not require a walk over Swift characters. A trimmed or replaced snapshot
234/// resets terminal content without rebuilding its native surface.
235enum TerminalBufferDelta: Equatable {
236 case append(Data)
237 case replace(Data)
238​
239 struct Applied: Equatable {
240 private(set) var bytes = Data()
241​
242 init() {}
243​
244 init(buffer: String) {
245 bytes = Data(buffer.utf8)
246 }
247​
248 mutating func apply(_ delta: TerminalBufferDelta) {
249 switch delta {
250 case .append(let data): bytes.append(data)
251 case .replace(let data): bytes = data
252 }
253 }
254 }
255​
256 static func compute(previous: Applied, next: String) -> TerminalBufferDelta {
257 var next = next
258 return next.withUTF8 { bytes in
259 guard !previous.bytes.isEmpty else { return .append(Data(buffer: bytes)) }
260 return previous.bytes.withUnsafeBytes { oldBytes in
261 guard bytes.count >= oldBytes.count,
262 let oldBase = oldBytes.baseAddress,
263 let nextBase = bytes.baseAddress,
264 memcmp(oldBase, nextBase, oldBytes.count) == 0 else {
265 return .replace(Data(buffer: bytes))
266 }
267 return .append(Data(buffer: UnsafeBufferPointer(rebasing: bytes[oldBytes.count...])))
268 }
269 }
270 }
272​
273private enum GhosttyRuntime {
274 private static let lock = NSLock()
275 nonisolated(unsafe) private static var initialized = false
276​
277 static func ensureInitialized() -> Bool {
278 lock.lock()
279 defer { lock.unlock() }
280​
281 if initialized { return true }
282 initialized = ghostty_init(0, nil) == GHOSTTY_SUCCESS
283 return initialized
284 }
286​
287@MainActor
288enum TerminalHardwareKeyEncoder {
289 private static let controlInputs = "abcdefghijklmnopqrstuvwxyz@[\\]^_-? "
290​
291 static func makeKeyCommands(action: Selector) -> [UIKeyCommand] {
292 var commands = [UIKeyCommand]()
293 let specialInputs = [
294 UIKeyCommand.inputEscape,
295 UIKeyCommand.inputUpArrow,
296 UIKeyCommand.inputDownArrow,
297 UIKeyCommand.inputLeftArrow,
298 UIKeyCommand.inputRightArrow,
299 "\t",
300 ]
301​
302 for input in specialInputs {
303 commands.append(makeCommand(input: input, modifierFlags: [], action: action))
304 }
305 commands.append(makeCommand(input: "\t", modifierFlags: .shift, action: action))
306​
307 for character in controlInputs {
308 commands.append(
309 makeCommand(
310 input: String(character),
311 modifierFlags: .control,
312 action: action
313 )
314 )
315 commands.append(
316 makeCommand(
317 input: String(character),
318 modifierFlags: [.control, .shift],
319 action: action
320 )
321 )
322 }
323​
324 commands.append(makeCommand(input: "c", modifierFlags: .command, action: action))
325 commands.append(makeCommand(input: "v", modifierFlags: .command, action: action))
326 return commands
327 }
328​
329 private static func makeCommand(
330 input: String,
331 modifierFlags: UIKeyModifierFlags,
332 action: Selector
333 ) -> UIKeyCommand {
334 let command = UIKeyCommand(input: input, modifierFlags: modifierFlags, action: action)
335 command.wantsPriorityOverSystemBehavior = true
336 return command
337 }
338​
339 static func sequence(
340 input: String,
341 modifiers: UIKeyModifierFlags,
342 hostPlatform: TerminalHostPlatform
343 ) -> String? {
344 if modifiers == .command {
345 return input.lowercased() == "c" ? "copy" : input.lowercased() == "v" ? "paste" : nil
346 }
347 if modifiers.contains(.control), hostPlatform != .mac, input.lowercased() == "v" {
348 return "paste"
349 }
350​
351 switch input {
352 case UIKeyCommand.inputEscape: return "\u{1B}"
353 case UIKeyCommand.inputUpArrow: return "\u{1B}[A"
354 case UIKeyCommand.inputDownArrow: return "\u{1B}[B"
355 case UIKeyCommand.inputRightArrow: return "\u{1B}[C"
356 case UIKeyCommand.inputLeftArrow: return "\u{1B}[D"
357 case "\t": return modifiers.contains(.shift) ? "\u{1B}[Z" : "\t"
358 default: break
359 }
360​
361 guard modifiers.contains(.control),
362 let scalar = input.lowercased().unicodeScalars.first else {
363 return nil
364 }
365 return TerminalInputEncoder.controlSequence(for: scalar)
366 }
368​
369private final class TerminalInputField: UITextField {
370 var hostPlatform = TerminalHostPlatform.unknown
371 var onDeleteBackward: (() -> Void)?
372 var onInsert: ((String) -> Void)?
373 var onCopyOutput: (() -> Void)?
374 var onPasteText: (() -> Void)?
375​
376 private static let terminalKeyCommands = TerminalHardwareKeyEncoder.makeKeyCommands(
377 action: #selector(handleHardwareKeyCommand(_:))
378 )
379​
380 override var keyCommands: [UIKeyCommand]? { Self.terminalKeyCommands }
381​
382 override func deleteBackward() {
383 onDeleteBackward?()
384 super.deleteBackward()
385 }
386​
387 override func paste(_ sender: Any?) {
388 onPasteText?()
389 }
390​
391 @objc private func handleHardwareKeyCommand(_ command: UIKeyCommand) {
392 guard let input = command.input,
393 let sequence = TerminalHardwareKeyEncoder.sequence(
394 input: input,
395 modifiers: command.modifierFlags,
396 hostPlatform: hostPlatform
397 ) else {
398 return
399 }
400​
401 if sequence == "copy" {
402 onCopyOutput?()
403 } else if sequence == "paste" {
404 onPasteText?()
405 } else {
406 onInsert?(sequence)
407 }
408 }
410​
411private enum TerminalAccessoryAction: String {
412 case escape
413 case command
414 case control
415 case tab
416 case paste
417 case clear
418 case up
419 case down
420 case left
421 case right
422 case tilde
423 case pipe
424 case slash
425 case dash
426 case dismiss
427​
428 var label: String {
429 switch self {
430 case .escape: "esc"
431 case .command: "cmd"
432 case .control: "ctrl"
433 case .tab: "tab"
434 case .paste: "paste"
435 case .clear: "clear"
436 case .up: "↑"
437 case .down: "↓"
438 case .left: "←"
439 case .right: "→"
440 case .tilde: "~"
441 case .pipe: "|"
442 case .slash: "/"
443 case .dash: "-"
444 case .dismiss: ""
445 }
446 }
447​
448 var sequence: String? {
449 switch self {
450 case .escape: "\u{1B}"
451 case .tab: "\t"
452 case .up: "\u{1B}[A"
453 case .down: "\u{1B}[B"
454 case .left: "\u{1B}[D"
455 case .right: "\u{1B}[C"
456 case .tilde: "~"
457 case .pipe: "|"
458 case .slash: "/"
459 case .dash: "-"
460 case .command, .control, .paste, .clear, .dismiss: nil
461 }
462 }
463​
464 var width: CGFloat {
465 switch self {
466 case .escape, .tab: 44
467 case .command: 48
468 case .control, .paste, .clear: 50
469 case .up, .down, .left, .right, .tilde, .pipe, .slash, .dash: 38
470 case .dismiss: 36
471 }
472 }
474​
475private final class TerminalAccessoryButton: UIButton {
476 let terminalAction: TerminalAccessoryAction
477​
478 init(action: TerminalAccessoryAction) {
479 terminalAction = action
480 super.init(frame: .zero)
481 }
482​
483 @available(*, unavailable)
484 required init?(coder _: NSCoder) { nil }
486​
487private final class TerminalAccessoryView: UIInputView {
488 private let scrollView = UIScrollView()
489 private let stackView = UIStackView()
490 private let dismissButton = TerminalAccessoryButton(action: .dismiss)
491 private var actionButtons = [TerminalAccessoryAction: TerminalAccessoryButton]()
492 private var activeModifier: TerminalAccessoryAction?
493 private var hostPlatform = TerminalHostPlatform.unknown
494 var onAction: ((TerminalAccessoryAction) -> Void)?
495​
496 init() {
497 super.init(frame: CGRect(x: 0, y: 0, width: 0, height: 50), inputViewStyle: .keyboard)
498 allowsSelfSizing = true
499 backgroundColor = T3Colors.uiBackground
500​
501 scrollView.showsHorizontalScrollIndicator = false
502 scrollView.alwaysBounceHorizontal = true
503 scrollView.translatesAutoresizingMaskIntoConstraints = false
504 stackView.axis = .horizontal
505 stackView.alignment = .center
506 stackView.spacing = 7
507 stackView.translatesAutoresizingMaskIntoConstraints = false
508​
509 addSubview(scrollView)
510 addSubview(dismissButton)
511 scrollView.addSubview(stackView)
512​
513 let actions: [TerminalAccessoryAction] = [
514 .escape, .control, .command, .tab, .paste, .clear,
515 .up, .down, .left, .right, .tilde, .pipe, .slash, .dash,
516 ]
517 for action in actions {
518 let button = TerminalAccessoryButton(action: action)
519 configure(button, label: action.label)
520 actionButtons[action] = button
521 stackView.addArrangedSubview(button)
522 }
523​
524 dismissButton.accessibilityLabel = "Dismiss keyboard"
525 dismissButton.addTarget(self, action: #selector(handleButton(_:)), for: .touchUpInside)
526 dismissButton.translatesAutoresizingMaskIntoConstraints = false
527​
528 NSLayoutConstraint.activate([
529 heightAnchor.constraint(equalToConstant: 50),
530 scrollView.leadingAnchor.constraint(equalTo: leadingAnchor),
531 scrollView.topAnchor.constraint(equalTo: topAnchor),
532 scrollView.bottomAnchor.constraint(equalTo: bottomAnchor),
533 scrollView.trailingAnchor.constraint(equalTo: dismissButton.leadingAnchor),
534 dismissButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -4),
535 dismissButton.centerYAnchor.constraint(equalTo: centerYAnchor),
536 dismissButton.widthAnchor.constraint(equalToConstant: TerminalAccessoryAction.dismiss.width),
537 dismissButton.heightAnchor.constraint(equalToConstant: 42),
538 stackView.leadingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.leadingAnchor, constant: 8),
539 stackView.trailingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.trailingAnchor, constant: -8),
540 stackView.topAnchor.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor),
541 stackView.bottomAnchor.constraint(equalTo: scrollView.contentLayoutGuide.bottomAnchor),
542 stackView.heightAnchor.constraint(equalTo: scrollView.frameLayoutGuide.heightAnchor),
543 ])
544 refreshAppearance()
545 registerForTraitChanges([UITraitUserInterfaceStyle.self]) {
546 (self: Self, _: UITraitCollection) in
547 self.refreshAppearance()
548 }
549 }
550​
551 @available(*, unavailable)
552 required init?(coder _: NSCoder) { nil }
553​
554 func setRunning(_ running: Bool) {
555 for (action, button) in actionButtons {
556 button.isEnabled = running || action == .clear
557 }
558 }
559​
560 func setHostPlatform(_ platform: TerminalHostPlatform) {
561 guard hostPlatform != platform else { return }
562 hostPlatform = platform
563 if let command = actionButtons[.command] {
564 stackView.removeArrangedSubview(command)
565 stackView.insertArrangedSubview(command, at: platform == .mac ? 1 : 2)
566 }
567 refreshAppearance()
568 }
569​
570 func setActiveModifier(_ action: TerminalAccessoryAction?) {
571 activeModifier = action
572 for modifier in [TerminalAccessoryAction.command, .control] {
573 guard let button = actionButtons[modifier] else { continue }
574 applyStyle(to: button, active: modifier == action)
575 }
576 }
577​
578 func refreshAppearance() {
579 backgroundColor = T3Colors.uiBackground
580 for (action, button) in actionButtons {
581 applyStyle(to: button, active: action == activeModifier)
582 }
583​
584 var dismissConfiguration = UIButton.Configuration.plain()
585 dismissConfiguration.image = UIImage(systemName: "keyboard.chevron.compact.down")
586 dismissConfiguration.baseForegroundColor = .secondaryLabel
587 dismissConfiguration.contentInsets = .zero
588 dismissButton.configuration = dismissConfiguration
589 }
590​
591 private func configure(_ button: TerminalAccessoryButton, label: String) {
592 button.setTitle(label.uppercased(), for: .normal)
593 button.titleLabel?.font = .systemFont(ofSize: 10, weight: .semibold)
594 button.accessibilityLabel = label
595 button.addTarget(self, action: #selector(handleButton(_:)), for: .touchUpInside)
596 button.translatesAutoresizingMaskIntoConstraints = false
597 button.heightAnchor.constraint(equalToConstant: 34).isActive = true
598 button.widthAnchor.constraint(equalToConstant: button.terminalAction.width).isActive = true
599 applyStyle(to: button, active: false)
600 }
601​
602 private func applyStyle(to button: UIButton, active: Bool) {
603 var configuration = UIButton.Configuration.plain()
604 if let terminalButton = button as? TerminalAccessoryButton,
605 terminalButton.terminalAction != .dismiss {
606 let action = terminalButton.terminalAction
607 let label = action == .command && hostPlatform != .mac ? "alt" : action.label
608 configuration.title = label.uppercased()
609 button.accessibilityLabel = action == .paste ? "Paste" : label
610 button.accessibilityIdentifier = "terminal-key-\(label)"
611 }
612 let isDark = traitCollection.userInterfaceStyle == .dark
613 configuration.baseForegroundColor = if active {
614 isDark ? UIColor(white: 0.04, alpha: 1) : .white
615 } else {
616 isDark ? UIColor(white: 0.88, alpha: 1) : T3Colors.uiTextPrimary
617 }
618 configuration.background.backgroundColor = if active {
619 isDark ? UIColor(white: 0.94, alpha: 1) : T3Colors.uiTextPrimary
620 } else {
621 isDark ? UIColor(white: 0.08, alpha: 1) : .white
622 }
623 configuration.background.cornerRadius = 7
624 configuration.background.strokeColor = isDark
625 ? UIColor(white: active ? 0.55 : 0.20, alpha: 1)
626 : UIColor(white: 0, alpha: active ? 0.18 : 0.10)
627 configuration.background.strokeWidth = 1
628 configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer {
629 var attributes = $0
630 attributes.font = .systemFont(ofSize: 10, weight: .semibold)
631 return attributes
632 }
633 configuration.contentInsets = NSDirectionalEdgeInsets(
634 top: 0,
635 leading: 4,
636 bottom: 0,
637 trailing: 4
638 )
639 button.configuration = configuration
640 }
641​
642 @objc private func handleButton(_ sender: TerminalAccessoryButton) {
643 onAction?(sender.terminalAction)
644 }
646​
647final class GhosttyTerminalView: UIView, UITextFieldDelegate, UIContextMenuInteractionDelegate {
648 private static let minimumVerticalScrollStepPoints: CGFloat = 18
649 private static let verticalScrollStepMultiplier: CGFloat = 1.15
650 private static let darkThemeConfig = """
651 background = #000000
652 foreground = #adadb1
653 cursor-color = #009fff
654 cursor-text = #000000
655 cursor-style-blink = false
656 palette = 0=#141415
657 palette = 1=#ff2e3f
658 palette = 2=#0dbe4e
659 palette = 3=#ffca00
660 palette = 4=#009fff
661 palette = 5=#c635e4
662 palette = 6=#08c0ef
663 palette = 7=#c6c6c8
664 palette = 8=#141415
665 palette = 9=#ff2e3f
666 palette = 10=#0dbe4e
667 palette = 11=#ffca00
668 palette = 12=#009fff
669 palette = 13=#c635e4
670 palette = 14=#08c0ef
671 palette = 15=#c6c6c8
672 """
673 private static let lightThemeConfig = """
674 background = #f2f2f7
675 foreground = #6c6c71
676 cursor-color = #009fff
677 cursor-text = #f2f2f7
678 cursor-style-blink = false
679 palette = 0=#1f1f21
680 palette = 1=#ff2e3f
681 palette = 2=#0dbe4e
682 palette = 3=#ffca00
683 palette = 4=#009fff
684 palette = 5=#c635e4
685 palette = 6=#08c0ef
686 palette = 7=#c6c6c8
687 palette = 8=#1f1f21
688 palette = 9=#ff2e3f
689 palette = 10=#0dbe4e
690 palette = 11=#ffca00
691 palette = 12=#009fff
692 palette = 13=#c635e4
693 palette = 14=#08c0ef
694 palette = 15=#c6c6c8
695 """
696 /// Full reset, drop scrollback, clear, home. Puts an existing surface in
697 /// the same state as a new one without rebuilding it.
698 private static let resetSequence = Data("\u{1B}c\u{1B}[3J\u{1B}[2J\u{1B}[H".utf8)
699​
700 var onInput: ((String) -> Void)?
701 var onPaste: ((String) -> Void)?
702 var onResize: ((Int, Int) -> Void)?
703 var onClear: (() -> Void)?
704 var onFontSizeStep: ((Int) -> Void)?
705 var onAttachOutput: ((String) -> Void)?
706​
707 var isDarkMode = true {
708 didSet {
709 guard oldValue != isDarkMode else { return }
710 applyChromeAppearance()
711 refreshSurfaceIfCreated()
712 }
713 }
714​
715 var terminalKey = "" {
716 didSet {
717 accessibilityIdentifier = "t3-terminal-\(terminalKey)"
718 inputField.accessibilityIdentifier = "t3-terminal-input-\(terminalKey)"
719 guard oldValue != terminalKey else { return }
720 pendingModifier = nil
721 resetSurface()
722 }
723 }
724​
725 var lifecycleVersion = 0 {
726 didSet {
727 if oldValue != lifecycleVersion { pendingModifier = nil }
728 }
729 }
730​
731 var buffer = "" {
732 didSet {
733 guard applyRemoteBuffer(buffer), UIAccessibility.isVoiceOverRunning else { return }
734 terminalViewport.accessibilityValue = TerminalText.plainText(
735 from: String(buffer.suffix(8_192))
736 )
737 }
738 }
739​
740 var fontSize: CGFloat = 10.5 {
741 didSet {
742 guard oldValue != fontSize else { return }
743 inputField.font = .monospacedSystemFont(ofSize: max(fontSize, 13), weight: .regular)
744 refreshSurfaceIfCreated()
745 }
746 }
747​
748 var isRunning = false {
749 didSet {
750 guard oldValue != isRunning else { return }
751 inputField.isEnabled = isRunning
752 accessoryView.setRunning(isRunning)
753 keyboardButton.isHidden = !isRunning || inputField.isFirstResponder
754 if isRunning, window != nil, !hasAutoFocused {
755 hasAutoFocused = true
756 DispatchQueue.main.async { [weak self] in self?.requestKeyboardFocus() }
757 } else if !isRunning {
758 pendingModifier = nil
759 }
760 }
761 }
762​
763 var hostPlatform = TerminalHostPlatform.unknown {
764 didSet {
765 guard oldValue != hostPlatform else { return }
766 inputField.hostPlatform = hostPlatform
767 accessoryView.setHostPlatform(hostPlatform)
768 pendingModifier = nil
769 }
770 }
771​
772 var focusRequest = 0 {
773 didSet {
774 guard oldValue != focusRequest else { return }
775 DispatchQueue.main.async { [weak self] in self?.requestKeyboardFocus() }
776 }
777 }
778​
779 private let terminalViewport = UIView()
780 private let inputField = TerminalInputField()
781 private let accessoryView = TerminalAccessoryView()
782 private let keyboardButton = UIButton(type: .system)
783 private let focusTapGesture = UITapGestureRecognizer()
784 private let scrollPanGesture = UIPanGestureRecognizer()
785 private let fontPinchGesture = UIPinchGestureRecognizer()
786 private var pendingModifier: TerminalInputModifier? {
787 didSet {
788 accessoryView.setActiveModifier(pendingModifier.map { $0 == .command ? .command : .control })
789 }
790 }
791 private var lastViewportSize: CGSize = .zero
792 private var lastContentScale: CGFloat = 0
793 private var lastReportedGrid: (columns: Int, rows: Int)?
794 private var appliedBuffer = TerminalBufferDelta.Applied()
795 private var isReplayingBuffer = false
796 private var pendingVerticalScrollPoints: CGFloat = 0
797 private var hasAutoFocused = false
798 private var app: ghostty_app_t?
799 private var eventLoop: GhosttyAppEventLoop?
800 private var surface: ghostty_surface_t?
801 private var isCreatingSurface = false
802 private var surfaceCreationFailed = false
803 private var isTornDown = false
804 private var teardownTask: Task<Void, Never>?
805​
806 init() {
807 super.init(frame: .zero)
808 clipsToBounds = true
809 contentScaleFactor = UIScreen.main.scale
810 accessibilityLabel = "Terminal"
811​
812 terminalViewport.clipsToBounds = true
813 terminalViewport.contentScaleFactor = contentScaleFactor
814 terminalViewport.translatesAutoresizingMaskIntoConstraints = false
815 terminalViewport.isUserInteractionEnabled = true
816 terminalViewport.isAccessibilityElement = true
817 terminalViewport.accessibilityLabel = "Terminal output"
818 terminalViewport.accessibilityTraits = .staticText
819​
820 inputField.delegate = self
821 inputField.inputAccessoryView = accessoryView
822 inputField.backgroundColor = .clear
823 inputField.textColor = .clear
824 inputField.tintColor = .clear
825 inputField.font = .monospacedSystemFont(ofSize: max(fontSize, 13), weight: .regular)
826 inputField.placeholder = ""
827 inputField.autocorrectionType = .no
828 inputField.autocapitalizationType = .none
829 inputField.spellCheckingType = .no
830 inputField.smartDashesType = .no
831 inputField.smartQuotesType = .no
832 inputField.returnKeyType = .send
833 inputField.keyboardType = .asciiCapable
834 inputField.enablesReturnKeyAutomatically = false
835 inputField.translatesAutoresizingMaskIntoConstraints = false
836 inputField.alpha = 0.02
837 inputField.isAccessibilityElement = true
838 inputField.accessibilityLabel = "Terminal input"
839 inputField.addTarget(self, action: #selector(inputDidBegin), for: .editingDidBegin)
840 inputField.addTarget(self, action: #selector(inputDidEnd), for: .editingDidEnd)
841 inputField.onDeleteBackward = { [weak self] in self?.sendInput("\u{7F}") }
842 inputField.onInsert = { [weak self] in self?.sendInput($0) }
843 inputField.onCopyOutput = { [weak self] in self?.copyOutput() }
844 inputField.onPasteText = { [weak self] in self?.pasteText() }
845​
846 keyboardButton.accessibilityLabel = "Show keyboard"
847 keyboardButton.isHidden = true
848 keyboardButton.translatesAutoresizingMaskIntoConstraints = false
849 keyboardButton.addTarget(self, action: #selector(showKeyboard), for: .touchUpInside)
850​
851 accessoryView.onAction = { [weak self] in self?.handleAccessoryAction($0) }
852​
853 focusTapGesture.addTarget(self, action: #selector(viewportTapped))
854 terminalViewport.addGestureRecognizer(focusTapGesture)
855​
856 scrollPanGesture.addTarget(self, action: #selector(viewportPanned(_:)))
857 scrollPanGesture.maximumNumberOfTouches = 1
858 scrollPanGesture.cancelsTouchesInView = false
859 terminalViewport.addGestureRecognizer(scrollPanGesture)
860​
861 fontPinchGesture.addTarget(self, action: #selector(viewportPinched(_:)))
862 terminalViewport.addGestureRecognizer(fontPinchGesture)
863 terminalViewport.addInteraction(UIContextMenuInteraction(delegate: self))
864​
865 addSubview(terminalViewport)
866 addSubview(inputField)
867 addSubview(keyboardButton)
868​
869 NSLayoutConstraint.activate([
870 terminalViewport.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 6),
871 terminalViewport.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -6),
872 terminalViewport.topAnchor.constraint(equalTo: topAnchor, constant: 6),
873 terminalViewport.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -6),
874 inputField.trailingAnchor.constraint(equalTo: trailingAnchor),
875 inputField.topAnchor.constraint(equalTo: bottomAnchor, constant: 8),
876 inputField.widthAnchor.constraint(equalToConstant: 1),
877 inputField.heightAnchor.constraint(equalToConstant: 1),
878 keyboardButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16),
879 keyboardButton.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor, constant: -16),
880 keyboardButton.widthAnchor.constraint(equalToConstant: 48),
881 keyboardButton.heightAnchor.constraint(equalToConstant: 48),
882 ])
883 applyChromeAppearance()
884 }
885​
886 @available(*, unavailable)
887 required init?(coder _: NSCoder) { nil }
888​
889 override func layoutSubviews() {
890 super.layoutSubviews()
891 updateContentScale()
892 if surface == nil { createSurfaceIfPossible() }
893​
894 let viewportSize = terminalViewport.bounds.size
895 guard viewportSize != lastViewportSize || contentScaleFactor != lastContentScale else {
896 return
897 }
898 lastViewportSize = viewportSize
899 lastContentScale = contentScaleFactor
900 resizeSurface()
901 inputField.accessibilityFrame = terminalViewport.convert(terminalViewport.bounds, to: nil)
902 }
903​
904 override func didMoveToWindow() {
905 super.didMoveToWindow()
906 if let surface { ghostty_surface_set_occlusion(surface, window != nil) }
907 guard window != nil, isRunning, !hasAutoFocused else { return }
908 hasAutoFocused = true
909 DispatchQueue.main.async { [weak self] in self?.requestKeyboardFocus() }
910 }
911​
912 func textField(
913 _: UITextField,
914 shouldChangeCharactersIn _: NSRange,
915 replacementString string: String
916 ) -> Bool {
917 if !string.isEmpty {
918 sendInput(string == "\n" || string == "\r\n" ? "\r" : string)
919 }
920 return false
921 }
922​
923 func textFieldShouldReturn(_ textField: UITextField) -> Bool {
924 sendInput("\r")
925 textField.text = ""
926 return false
927 }
928​
929 func contextMenuInteraction(
930 _: UIContextMenuInteraction,
931 configurationForMenuAtLocation _: CGPoint
932 ) -> UIContextMenuConfiguration? {
933 UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { [weak self] _ in
934 guard let self else { return UIMenu() }
935 let copy = UIAction(title: "Copy output", image: UIImage(systemName: "doc.on.doc")) { [weak self] _ in
936 self?.copyOutput()
937 }
938 let paste = UIAction(
939 title: "Paste",
940 image: UIImage(systemName: "doc.on.clipboard"),
941 attributes: self.isRunning && UIPasteboard.general.hasStrings ? [] : .disabled
942 ) { [weak self] _ in
943 self?.pasteText()
944 }
945 let clear = UIAction(title: "Clear", image: UIImage(systemName: "eraser")) { [weak self] _ in
946 self?.onClear?()
947 }
948 var actions = [copy, paste, clear]
949 if self.onAttachOutput != nil {
950 actions.insert(UIAction(title: "Add output to message", image: UIImage(systemName: "text.bubble")) { [weak self] _ in
951 guard let self else { return }
952 self.onAttachOutput?(TerminalText.plainText(from: self.buffer))
953 }, at: 1)
954 }
955 return UIMenu(children: actions)
956 }
957 }
958​
959 private func createSurfaceIfPossible() {
960 guard !isTornDown, surface == nil, app == nil, !isCreatingSurface, !surfaceCreationFailed else { return }
961 guard terminalViewport.bounds.width > 0, terminalViewport.bounds.height > 0 else { return }
962 guard GhosttyRuntime.ensureInitialized() else {
963 surfaceCreationFailed = true
964 return
965 }
966​
967 isCreatingSurface = true
968 defer { isCreatingSurface = false }
969​
970 let eventLoop = GhosttyAppEventLoop()
971 var runtimeConfig = ghostty_runtime_config_s(
972 userdata: Unmanaged.passUnretained(eventLoop).toOpaque(),
973 supports_selection_clipboard: false,
974 wakeup_cb: { userdata in
975 guard let userdata else { return }
976 Unmanaged<GhosttyAppEventLoop>.fromOpaque(userdata).takeUnretainedValue().wakeup()
977 },
978 action_cb: { _, target, action in
979 // App ticks deliver render requests after queued output is parsed.
980 guard action.tag == GHOSTTY_ACTION_RENDER,
981 target.tag == GHOSTTY_TARGET_SURFACE,
982 let surface = target.target.surface else { return false }
983 ghostty_surface_draw(surface)
984 return true
985 },
986 read_clipboard_cb: { _, _, _, _, _, _ in GHOSTTY_CLIPBOARD_READ_UNSUPPORTED },
987 confirm_read_clipboard_cb: { _, _, _, _ in },
988 write_clipboard_cb: { _, _, _, _, _ in },
989 close_surface_cb: { _, _ in }
990 )
991​
992 guard let config = ghostty_config_new() else {
993 surfaceCreationFailed = true
994 return
995 }
996 loadThemeConfig(into: config)
997 ghostty_config_finalize(config)
998 defer { ghostty_config_free(config) }
999​
1000 guard let createdApp = ghostty_app_new(&runtimeConfig, config) else {
1001 surfaceCreationFailed = true
1002 return
1004​
1005 var surfaceConfig = ghostty_surface_config_new()
1006 surfaceConfig.platform_tag = GHOSTTY_PLATFORM_IOS
1007 surfaceConfig.platform.ios.uiview = Unmanaged.passUnretained(terminalViewport).toOpaque()
1008 surfaceConfig.userdata = Unmanaged.passUnretained(self).toOpaque()
1009 surfaceConfig.scale_factor = Double(contentScaleFactor)
1010 surfaceConfig.font_size = Float(fontSize)
1011 surfaceConfig.context = GHOSTTY_SURFACE_CONTEXT_WINDOW
1012 surfaceConfig.use_custom_io = true
1013​
1014 guard let createdSurface = ghostty_surface_new(createdApp, &surfaceConfig) else {
1015 ghostty_app_free(createdApp)
1016 surfaceCreationFailed = true
1017 return
1019​
1020 app = createdApp
1021 eventLoop.app = createdApp
1022 self.eventLoop = eventLoop
1023 surface = createdSurface
1024 let ghosttyColorScheme =
1025 isDarkMode
1026 ? GHOSTTY_COLOR_SCHEME_DARK
1027 : GHOSTTY_COLOR_SCHEME_LIGHT
1028 ghostty_app_set_color_scheme(createdApp, ghosttyColorScheme)
1029 ghostty_surface_set_color_scheme(createdSurface, ghosttyColorScheme)
1030 if inputField.isFirstResponder { ghostty_surface_set_focus(createdSurface, true) }
1031 setupWriteCallback()
1032 resizeSurface()
1033 feedBuffer(buffer)
1035​
1036 private func resetSurface() {
1037 destroySurface()
1038 appliedBuffer = TerminalBufferDelta.Applied()
1039 lastViewportSize = .zero
1040 lastContentScale = 0
1041 lastReportedGrid = nil
1042 surfaceCreationFailed = false
1043 setNeedsLayout()
1045​
1046 private func applyChromeAppearance() {
1047 let background = T3Colors.uiBackground.resolvedColor(
1048 with: UITraitCollection(userInterfaceStyle: isDarkMode ? .dark : .light)
1050 backgroundColor = background
1051 terminalViewport.backgroundColor = background
1052 accessoryView.overrideUserInterfaceStyle = isDarkMode ? .dark : .light
1053 accessoryView.refreshAppearance()
1054​
1055 var keyboardConfiguration = UIButton.Configuration.filled()
1056 keyboardConfiguration.image = UIImage(systemName: "keyboard")
1057 keyboardConfiguration.baseForegroundColor = isDarkMode ? .white : T3Colors.uiTextPrimary
1058 keyboardConfiguration.baseBackgroundColor =
1059 isDarkMode ? UIColor(white: 0.10, alpha: 0.96) : .white
1060 keyboardConfiguration.background.cornerRadius = 24
1061 keyboardConfiguration.background.strokeColor =
1062 isDarkMode
1063 ? UIColor(white: 0.25, alpha: 1)
1064 : UIColor(white: 0, alpha: 0.10)
1065 keyboardConfiguration.background.strokeWidth = 1
1066 keyboardButton.configuration = keyboardConfiguration
1068​
1069 /// Ghostty reads font size and theme when a surface is created, so those
1070 /// changes rebuild the surface. Before the first layout there is nothing to
1071 /// rebuild, and creation picks up the current values.
1072 private func refreshSurfaceIfCreated() {
1073 guard surface != nil else { return }
1074 resetSurface()
1075 createSurfaceIfPossible()
1077​
1078 @discardableResult
1079 func tearDown() -> Task<Void, Never>? {
1080 guard !isTornDown else { return teardownTask }
1081 isTornDown = true
1082 onInput = nil
1083 onPaste = nil
1084 onResize = nil
1085 onClear = nil
1086 onFontSizeStep = nil
1087 onAttachOutput = nil
1088 inputField.resignFirstResponder()
1089 teardownTask = destroySurface()
1090 return teardownTask
1092​
1093 @discardableResult
1094 private func destroySurface() -> Task<Void, Never>? {
1095 let surface = self.surface
1096 let app = self.app
1097 let eventLoop = self.eventLoop
1098 guard surface != nil || app != nil else { return nil }
1099 self.surface = nil
1100 self.app = nil
1101 self.eventLoop = nil
1102 // Remove the renderer's display callbacks from the view before a
1103 // dismissal layout or keyboard callback can try to use it again.
1104 terminalViewport.layer.sublayers?.forEach { $0.removeFromSuperlayer() }
1105 if let surface {
1106 ghostty_surface_set_focus(surface, false)
1107 ghostty_surface_set_occlusion(surface, false)
1109 return Task { @MainActor [self] in
1110 if let surface {
1111 await withCheckedContinuation { continuation in
1112 let fence = GhosttyRetirementFence {
1113 eventLoop?.app = nil
1114 ghostty_surface_free(surface)
1115 if let app { ghostty_app_free(app) }
1116 continuation.resume()
1118 // Callback changes and writes use the same FIFO as feed_data.
1119 // A write to this replacement callback proves all earlier output
1120 // was parsed. Swallow it here: it must never reach the remote PTY.
1121 // Keep ticking the app while waiting, or its bounded mailbox can
1122 // block the I/O thread that surface_free needs to join.
1123 ghostty_surface_set_write_callback(surface, { userdata, _, _ in
1124 guard let userdata else { return }
1125 Unmanaged<GhosttyRetirementFence>.fromOpaque(userdata).takeUnretainedValue().complete()
1126 }, Unmanaged.passRetained(fence).toOpaque())
1127 " ".withCString { ghostty_surface_text(surface, $0, 1) }
1129 } else {
1130 eventLoop?.app = nil
1131 if let app { ghostty_app_free(app) }
1133 withExtendedLifetime((self, eventLoop)) {}
1136​
1137 /// Feeds the surface whatever `newBuffer` adds on top of what it already
1138 /// shows. Returns false when nothing changed.
1139 @discardableResult
1140 private func applyRemoteBuffer(_ newBuffer: String) -> Bool {
1141 guard surface != nil else {
1142 createSurfaceIfPossible()
1143 return true
1145 let delta = TerminalBufferDelta.compute(previous: appliedBuffer, next: newBuffer)
1146 appliedBuffer.apply(delta)
1147 switch delta {
1148 case .append(let data):
1149 guard !data.isEmpty else { return false }
1150 feedData(data)
1151 case .replace(let data):
1152 replay {
1153 feedData(Self.resetSequence)
1154 feedData(data)
1157 return true
1159​
1160 /// Feeds the whole buffer into a fresh surface.
1161 private func feedBuffer(_ value: String) {
1162 appliedBuffer = TerminalBufferDelta.Applied(buffer: value)
1163 guard !value.isEmpty else { return }
1164 var value = value
1165 replay { value.withUTF8 { feedBytes($0) } }
1167​
1168 /// Replayed history must not echo terminal query replies back to the host.
1169 private func replay(_ body: () -> Void) {
1170 isReplayingBuffer = true
1171 defer { isReplayingBuffer = false }
1172 body()
1174​
1175 private func feedData(_ data: Data) {
1176 data.withUnsafeBytes { feedBytes($0.bindMemory(to: UInt8.self)) }
1178​
1179 private func feedBytes(_ bytes: UnsafeBufferPointer<UInt8>) {
1180 guard let surface, let pointer = bytes.baseAddress, !bytes.isEmpty else { return }
1181 ghostty_surface_feed_data(surface, pointer, bytes.count)
1182 redrawSurface()
1184​
1185 private func setupWriteCallback() {
1186 guard let surface else { return }
1187 let userdata = Unmanaged.passUnretained(self).toOpaque()
1188 ghostty_surface_set_write_callback(surface, { userdata, data, length in
1189 guard let userdata, let data, length > 0 else { return }
1190 let view = Unmanaged<GhosttyTerminalView>.fromOpaque(userdata).takeUnretainedValue()
1191 guard !view.isReplayingBuffer else { return }
1192 let bytes = Data(bytes: data, count: length)
1193 guard let input = String(data: bytes, encoding: .utf8), !input.isEmpty else { return }
1194 DispatchQueue.main.async { view.onInput?(input) }
1195 }, userdata)
1197​
1198 private func resizeSurface() {
1199 guard let surface else { return }
1200​
1201 let scale = contentScaleFactor
1202 let width = UInt32(max(floor(terminalViewport.bounds.width * scale), 1))
1203 let height = UInt32(max(floor(terminalViewport.bounds.height * scale), 1))
1204 terminalViewport.contentScaleFactor = scale
1205 ghostty_surface_set_content_scale(surface, Double(scale), Double(scale))
1206 ghostty_surface_set_size(surface, width, height)
1207 ghostty_surface_set_occlusion(surface, window != nil)
1208 configureIOSurfaceLayers()
1209 redrawSurface()
1210 emitGhosttyResize()
1212​
1213 private func redrawSurface() {
1214 guard let surface else { return }
1215 ghostty_surface_refresh(surface)
1216 ghostty_surface_draw(surface)
1217 markIOSurfaceLayersForDisplay()
1218 emitGhosttyResize()
1220​
1221 /// Reports the grid only once the surface has measured it, so the host
1222 /// never sees a guessed size followed by the real one.
1223 private func emitGhosttyResize() {
1224 guard let surface else { return }
1225 let size = ghostty_surface_size(surface)
1226 emitResize(columns: max(1, Int(size.columns)), rows: max(1, Int(size.rows)))
1228​
1229 private func emitResize(columns: Int, rows: Int) {
1230 guard lastReportedGrid?.columns != columns || lastReportedGrid?.rows != rows else { return }
1231 lastReportedGrid = (columns, rows)
1232 onResize?(columns, rows)
1234​
1235 private func updateContentScale() {
1236 let scale = window?.screen.scale ?? UIScreen.main.scale
1237 if contentScaleFactor != scale { contentScaleFactor = scale }
1239​
1240 private func requestKeyboardFocus() {
1241 guard !isTornDown, window != nil, isRunning else { return }
1242 inputField.becomeFirstResponder()
1243 if let surface { ghostty_surface_set_focus(surface, true) }
1244 if let app { ghostty_app_keyboard_changed(app) }
1246​
1247 private func sendInput(_ data: String) {
1248 guard isRunning, !data.isEmpty else { return }
1249 let modifier = pendingModifier
1250 pendingModifier = nil
1251 guard let modifier else {
1252 onInput?(data)
1253 return
1255 switch TerminalInputEncoder.modified(data, modifier: modifier, hostPlatform: hostPlatform) {
1256 case .write(let data): onInput?(data)
1257 case .paste: pasteText()
1260​
1261 private func copyOutput() {
1262 UIPasteboard.general.string = TerminalText.plainText(from: buffer)
1264​
1265 private func pasteText() {
1266 pendingModifier = nil
1267 let key = terminalKey
1268 let version = lifecycleVersion
1269 guard isRunning, let value = UIPasteboard.general.string, !value.isEmpty else { return }
1270 guard terminalKey == key, lifecycleVersion == version, isRunning else { return }
1271 onPaste?(value)
1273​
1274 private func handleAccessoryAction(_ action: TerminalAccessoryAction) {
1275 switch action {
1276 case .command:
1277 pendingModifier = pendingModifier == .command ? nil : .command
1278 case .control:
1279 pendingModifier = pendingModifier == .control ? nil : .control
1280 case .paste:
1281 pasteText()
1282 case .clear:
1283 pendingModifier = nil
1284 onClear?()
1285 case .dismiss:
1286 pendingModifier = nil
1287 inputField.resignFirstResponder()
1288 default:
1289 if let sequence = action.sequence { sendInput(sequence) }
1292​
1293 private func configureIOSurfaceLayers() {
1294 let targetBounds = CGRect(origin: .zero, size: terminalViewport.bounds.size)
1295 CATransaction.begin()
1296 CATransaction.setDisableActions(true)
1297 terminalViewport.layer.sublayers?.forEach { layer in
1298 layer.frame = targetBounds
1299 layer.contentsScale = contentScaleFactor
1301 CATransaction.commit()
1303​
1304 private func markIOSurfaceLayersForDisplay() {
1305 terminalViewport.layer.setNeedsDisplay()
1306 terminalViewport.layer.sublayers?.forEach { $0.setNeedsDisplay() }
1308​
1309 private func loadThemeConfig(into config: ghostty_config_t) {
1310 let url = FileManager.default.temporaryDirectory
1311 .appendingPathComponent("t3-swiftui-terminal.ghostty")
1312 do {
1313 let themeConfig = isDarkMode ? Self.darkThemeConfig : Self.lightThemeConfig
1314 if (try? String(contentsOf: url, encoding: .utf8)) != themeConfig {
1315 try themeConfig.write(to: url, atomically: true, encoding: .utf8)
1317 url.path.withCString { ghostty_config_load_file(config, $0) }
1318 } catch {
1319 // The default Ghostty configuration is still usable if the theme file cannot be staged.
1322​
1323 @objc private func viewportTapped() {
1324 requestKeyboardFocus()
1326​
1327 @objc private func viewportPanned(_ gesture: UIPanGestureRecognizer) {
1328 guard let surface else { return }
1329 let location = gesture.location(in: terminalViewport)
1330 ghostty_surface_mouse_pos(
1331 surface,
1332 Double(location.x * contentScaleFactor),
1333 Double(location.y * contentScaleFactor),
1334 GHOSTTY_MODS_NONE
1336​
1337 switch gesture.state {
1338 case .began:
1339 pendingVerticalScrollPoints = 0
1340 gesture.setTranslation(.zero, in: terminalViewport)
1341 case .changed:
1342 let translation = gesture.translation(in: terminalViewport)
1343 let stepSize = max(
1344 fontSize * Self.verticalScrollStepMultiplier,
1345 Self.minimumVerticalScrollStepPoints
1347 let total = pendingVerticalScrollPoints + translation.y
1348 let steps = Int(total / stepSize)
1349 pendingVerticalScrollPoints = total - CGFloat(steps) * stepSize
1350 if steps != 0 {
1351 ghostty_surface_mouse_scroll(surface, 0, Double(steps), 0)
1352 redrawSurface()
1354 gesture.setTranslation(.zero, in: terminalViewport)
1355 default:
1356 pendingVerticalScrollPoints = 0
1357 gesture.setTranslation(.zero, in: terminalViewport)
1360​
1361 @objc private func viewportPinched(_ gesture: UIPinchGestureRecognizer) {
1362 guard gesture.state == .ended else { return }
1363 if gesture.scale >= 1.08 {
1364 onFontSizeStep?(1)
1365 } else if gesture.scale <= 0.92 {
1366 onFontSizeStep?(-1)
1369​
1370 @objc private func inputDidBegin() {
1371 keyboardButton.isHidden = true
1372 if let surface { ghostty_surface_set_focus(surface, true) }
1373 if let app { ghostty_app_keyboard_changed(app) }
1375​
1376 @objc private func inputDidEnd() {
1377 pendingModifier = nil
1378 keyboardButton.isHidden = !isRunning
1379 if let surface { ghostty_surface_set_focus(surface, false) }
1381​
1382 @objc private func showKeyboard() {
1383 requestKeyboardFocus()