Open History to see the last commit
1import ExpoModulesCore
2import Foundation
3import GhosttyKit
4import QuartzCore
5import UIKit
6
7private enum GhosttyRuntime {
8 private static let lock = NSLock()
9 private static var initialized = false
10
11 static func ensureInitialized() -> Bool {
12 lock.lock()
13 defer { lock.unlock() }
14
15 if initialized {
16 return true
17 }
18
19 let result = ghostty_init(0, nil)
20 initialized = result == GHOSTTY_SUCCESS
21 return initialized
22 }
23}
24
25/// Encodes hardware-keyboard combos that UITextField never surfaces through its
26/// text-editing delegate (control combos, Escape, Tab, arrow keys) into the byte
27/// sequences a terminal expects.
28///
29/// Capture uses UIKeyCommand with `wantsPriorityOverSystemBehavior` rather than
30/// `pressesBegan`: while a text field is first responder, iPadOS routes hardware key
31/// events through the text-input system, which can consume presses before they reach
32/// responder press callbacks. Registered key commands are matched deterministically
33/// before that happens.
34private enum TerminalHardwareKeyEncoder {
35 /// Characters that produce a control byte when combined with Ctrl.
36 private static let controlInputs = "abcdefghijklmnopqrstuvwxyz@[\\]^_-? "
37
38 static func makeKeyCommands(action: Selector) -> [UIKeyCommand] {
39 var commands: [UIKeyCommand] = []
40
41 let specialInputs = [
42 UIKeyCommand.inputEscape,
43 UIKeyCommand.inputUpArrow,
44 UIKeyCommand.inputDownArrow,
45 UIKeyCommand.inputLeftArrow,
46 UIKeyCommand.inputRightArrow,
47 "\t",
48 ]
49 for input in specialInputs {
50 commands.append(makeCommand(input: input, modifierFlags: [], action: action))
51 }
52 commands.append(makeCommand(input: "\t", modifierFlags: .shift, action: action))
53
54 for character in controlInputs {
55 commands.append(makeCommand(input: String(character), modifierFlags: .control, action: action))
56 commands.append(
57 makeCommand(input: String(character), modifierFlags: [.control, .shift], action: action)
58 )
59 }
60
61 return commands
62 }
63
64 private static func makeCommand(
65 input: String,
66 modifierFlags: UIKeyModifierFlags,
67 action: Selector
68 ) -> UIKeyCommand {
69 let command = UIKeyCommand(input: input, modifierFlags: modifierFlags, action: action)
70 command.wantsPriorityOverSystemBehavior = true
71 return command
72 }
73
74 static func sequence(input: String, modifiers: UIKeyModifierFlags) -> String? {
75 switch input {
76 case UIKeyCommand.inputEscape:
77 return "\u{1B}"
78 case UIKeyCommand.inputUpArrow:
79 return "\u{1B}[A"
80 case UIKeyCommand.inputDownArrow:
81 return "\u{1B}[B"
82 case UIKeyCommand.inputRightArrow:
83 return "\u{1B}[C"
84 case UIKeyCommand.inputLeftArrow:
85 return "\u{1B}[D"
86 case "\t":
87 return modifiers.contains(.shift) ? "\u{1B}[Z" : "\t"
88 default:
89 break
90 }
91
92 guard modifiers.contains(.control) else { return nil }
93 guard let scalar = input.lowercased().unicodeScalars.first else { return nil }
94 return controlSequence(for: scalar)
95 }
96
97 private static func controlSequence(for scalar: Unicode.Scalar) -> String? {
98 switch scalar {
99 case "a"..."z":
100 // Ctrl+A..Z -> 0x01..0x1A (Ctrl+C = ETX, Ctrl+Z = SUB, ...).
101 return UnicodeScalar(scalar.value - 96).map(String.init)
102 case " ", "@":
103 return "\u{00}"
104 case "[":
105 return "\u{1B}"
106 case "\\":
107 return "\u{1C}"
108 case "]":
109 return "\u{1D}"
110 case "^":
111 return "\u{1E}"
112 case "_", "-":
113 return "\u{1F}"
114 case "?":
115 return "\u{7F}"
116 default:
117 return nil
118 }
119 }
120}
121
122private enum TerminalInputSequence {
123 /// Terminal Enter is carriage return. Sending line feed instead is Ctrl+J,
124 /// which raw-mode TUIs may interpret as the literal J key.
125 static let carriageReturn = "\r"
126
127 static func normalizingReturn(_ input: String) -> String {
128 switch input {
129 case "\n", "\r\n":
130 return carriageReturn
131 default:
132 return input
133 }
134 }
135}
136
137private final class TerminalInputField: UITextField {
138 var onDeleteBackward: (() -> Void)?
139 var onInsert: ((String) -> Void)?
140
141 private static let hardwareKeyCommands = TerminalHardwareKeyEncoder.makeKeyCommands(
142 action: #selector(handleHardwareKeyCommand(_:))
143 )
144
145 override var keyCommands: [UIKeyCommand]? {
146 Self.hardwareKeyCommands
147 }
148
149 override func deleteBackward() {
150 onDeleteBackward?()
151 super.deleteBackward()
152 }
153
154 @objc
155 private func handleHardwareKeyCommand(_ command: UIKeyCommand) {
156 guard let input = command.input else { return }
157 guard let sequence = TerminalHardwareKeyEncoder.sequence(
158 input: input,
159 modifiers: command.modifierFlags
160 ) else { return }
161 onInsert?(sequence)
162 }
163}
164
165private enum TerminalAppearanceScheme: String {
166 case light
167 case dark
168
169 init(value: String) {
170 self = TerminalAppearanceScheme(rawValue: value) ?? .dark
171 }
172
173 var ghosttyColorScheme: ghostty_color_scheme_e {
174 switch self {
175 case .light:
176 return GHOSTTY_COLOR_SCHEME_LIGHT
177 case .dark:
178 return GHOSTTY_COLOR_SCHEME_DARK
179 }
180 }
181}
182
183private extension UIColor {
184 convenience init(hexString: String) {
185 let sanitized = hexString.replacingOccurrences(of: "#", with: "")
186 let value = Int(sanitized, radix: 16) ?? 0
187 self.init(
188 red: CGFloat((value >> 16) & 0xFF) / 255,
189 green: CGFloat((value >> 8) & 0xFF) / 255,
190 blue: CGFloat(value & 0xFF) / 255,
191 alpha: 1
192 )
193 }
194}
195
196public final class T3TerminalView: ExpoView, UITextFieldDelegate {
197 private static let minimumVerticalScrollStepPoints: CGFloat = 18
198 private static let verticalScrollStepMultiplier: CGFloat = 1.15
199
200 private let terminalViewport = UIView()
201 private let inputField = TerminalInputField()
202 private let focusTapGesture = UITapGestureRecognizer()
203 private let scrollPanGesture = UIPanGestureRecognizer()
204 private var lastViewportSize: CGSize = .zero
205 private var lastContentScale: CGFloat = 0
206 private var lastReportedGrid: (cols: Int, rows: Int)?
207 private var lastAppliedBuffer = ""
208 private var pendingVerticalScrollPoints: CGFloat = 0
209 private var app: ghostty_app_t?
210 private var surface: ghostty_surface_t?
211 private var isCreatingSurface = false
212 private var surfaceCreationFailed = false
213 private var appearance = TerminalAppearanceScheme.dark
214 private var backgroundColorValue = UIColor(hexString: "#24292e")
215
216 let onInput = EventDispatcher()
217 let onResize = EventDispatcher()
218
219 var terminalKey: String = "" {
220 didSet {
221 accessibilityIdentifier = "t3-terminal-\(terminalKey)"
222 if oldValue != terminalKey {
223 resetSurface()
224 }
225 }
226 }
227
228 var initialBuffer: String = "" {
229 didSet {
230 applyRemoteBuffer(initialBuffer)
231 }
232 }
233
234 var fontSize: CGFloat = 10 {
235 didSet {
236 guard oldValue != fontSize else { return }
237 inputField.font = UIFont.monospacedSystemFont(ofSize: max(fontSize, 13), weight: .regular)
238 refreshSurface()
239 }
240 }
241
242 var focusRequest: Double = 0 {
243 didSet {
244 guard oldValue != focusRequest else { return }
245 DispatchQueue.main.async { [weak self] in
246 self?.requestKeyboardFocus()
247 }
248 }
249 }
250
251 var autoFocus = true {
252 didSet {
253 guard oldValue != autoFocus else { return }
254 if autoFocus {
255 requestKeyboardFocus()
256 } else {
257 inputField.resignFirstResponder()
258 }
259 }
260 }
261
262 var appearanceScheme: String = TerminalAppearanceScheme.dark.rawValue {
263 didSet {
264 guard oldValue != appearanceScheme else { return }
265 appearance = TerminalAppearanceScheme(value: appearanceScheme)
266 refreshSurface()
267 }
268 }
269
270 var themeConfig: String = "" {
271 didSet {
272 guard oldValue != themeConfig else { return }
273 refreshSurface()
274 }
275 }
276
277 var backgroundColorHex: String = "#24292e" {
278 didSet {
279 backgroundColorValue = UIColor(hexString: backgroundColorHex)
280 applyTheme()
281 }
282 }
283
284 var foregroundColorHex: String = "#d1d5da"
285 var mutedForegroundColorHex: String = "#959da5"
286
287 public required init(appContext: AppContext? = nil) {
288 super.init(appContext: appContext)
289
290 applyTheme()
291 clipsToBounds = true
292 contentScaleFactor = UIScreen.main.scale
293
294 terminalViewport.clipsToBounds = true
295 terminalViewport.contentScaleFactor = contentScaleFactor
296 terminalViewport.translatesAutoresizingMaskIntoConstraints = false
297 terminalViewport.isUserInteractionEnabled = true
298
299 inputField.delegate = self
300 inputField.backgroundColor = UIColor.clear
301 inputField.textColor = UIColor.clear
302 inputField.tintColor = UIColor.clear
303 inputField.font = UIFont.monospacedSystemFont(ofSize: max(fontSize, 13), weight: .regular)
304 inputField.placeholder = ""
305 inputField.autocorrectionType = .no
306 inputField.autocapitalizationType = .none
307 inputField.spellCheckingType = .no
308 inputField.smartDashesType = .no
309 inputField.smartQuotesType = .no
310 inputField.returnKeyType = .send
311 inputField.keyboardType = .asciiCapable
312 inputField.enablesReturnKeyAutomatically = false
313 inputField.translatesAutoresizingMaskIntoConstraints = false
314 inputField.alpha = 0.02
315 inputField.isAccessibilityElement = false
316 inputField.accessibilityElementsHidden = true
317 inputField.addTarget(self, action: #selector(handleInputEditingDidBegin), for: .editingDidBegin)
318 inputField.onDeleteBackward = { [weak self] in
319 self?.emitInput("\u{7F}")
320 }
321 inputField.onInsert = { [weak self] data in
322 self?.emitInput(data)
323 }
324
325 focusTapGesture.addTarget(self, action: #selector(handleViewportTap))
326 terminalViewport.addGestureRecognizer(focusTapGesture)
327 scrollPanGesture.addTarget(self, action: #selector(handleViewportPan(_:)))
328 scrollPanGesture.maximumNumberOfTouches = 1
329 scrollPanGesture.cancelsTouchesInView = false
330 terminalViewport.addGestureRecognizer(scrollPanGesture)
331
332 addSubview(terminalViewport)
333 addSubview(inputField)
334
335 NSLayoutConstraint.activate([
336 terminalViewport.leadingAnchor.constraint(equalTo: leadingAnchor),
337 terminalViewport.trailingAnchor.constraint(equalTo: trailingAnchor),
338 terminalViewport.topAnchor.constraint(equalTo: topAnchor),
339 terminalViewport.bottomAnchor.constraint(equalTo: bottomAnchor),
340
341 inputField.trailingAnchor.constraint(equalTo: trailingAnchor),
342 inputField.topAnchor.constraint(equalTo: bottomAnchor, constant: 8),
343 inputField.widthAnchor.constraint(equalToConstant: 1),
344 inputField.heightAnchor.constraint(equalToConstant: 1),
345 ])
346 }
347
348 deinit {
349 destroySurface()
350 }
351
352 public override func layoutSubviews() {
353 super.layoutSubviews()
354 updateContentScale()
355
356 let viewportSize = terminalViewport.bounds.size
357 if surface == nil {
358 createSurfaceIfPossible()
359 }
360
361 guard viewportSize != lastViewportSize || contentScaleFactor != lastContentScale else {
362 return
363 }
364
365 lastViewportSize = viewportSize
366 lastContentScale = contentScaleFactor
367 resizeSurface()
368 }
369
370 public override func didMoveToWindow() {
371 super.didMoveToWindow()
372
373 guard window != nil, autoFocus else { return }
374 DispatchQueue.main.async { [weak self] in
375 self?.requestKeyboardFocus()
376 }
377 }
378
379 public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
380 if !string.isEmpty {
381 // Some software keyboards deliver Return through this delegate instead of
382 // textFieldShouldReturn, so normalize that path too.
383 emitInput(TerminalInputSequence.normalizingReturn(string))
384 return false
385 }
386
387 return false
388 }
389
390 public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
391 emitInput(TerminalInputSequence.carriageReturn)
392 textField.text = ""
393 return false
394 }
395
396 @objc
397 private func handleViewportTap() {
398 requestKeyboardFocus()
399 }
400
401 @objc
402 private func handleViewportPan(_ gesture: UIPanGestureRecognizer) {
403 guard let surface else { return }
404
405 let location = gesture.location(in: terminalViewport)
406 ghostty_surface_mouse_pos(
407 surface,
408 Double(location.x * contentScaleFactor),
409 Double(location.y * contentScaleFactor),
410 GHOSTTY_MODS_NONE
411 )
412
413 switch gesture.state {
414 case .began:
415 pendingVerticalScrollPoints = 0
416 gesture.setTranslation(.zero, in: terminalViewport)
417 case .changed:
418 let translation = gesture.translation(in: terminalViewport)
419 let stepSize = max(
420 fontSize * Self.verticalScrollStepMultiplier,
421 Self.minimumVerticalScrollStepPoints
422 )
423 let totalVerticalPoints = pendingVerticalScrollPoints + translation.y
424 let verticalSteps = Int(totalVerticalPoints / stepSize)
425 pendingVerticalScrollPoints = totalVerticalPoints - (CGFloat(verticalSteps) * stepSize)
426
427 guard verticalSteps != 0 else {
428 gesture.setTranslation(.zero, in: terminalViewport)
429 return
430 }
431
432 ghostty_surface_mouse_scroll(surface, 0, Double(verticalSteps), 0)
433 redrawSurface()
434 gesture.setTranslation(.zero, in: terminalViewport)
435 default:
436 pendingVerticalScrollPoints = 0
437 gesture.setTranslation(.zero, in: terminalViewport)
438 }
439 }
440
441 @objc
442 private func handleInputEditingDidBegin() {
443 textInputModeDidChange()
444 }
445
446 private func createSurfaceIfPossible() {
447 guard surface == nil, app == nil, !isCreatingSurface, !surfaceCreationFailed else { return }
448 guard terminalViewport.bounds.width > 0, terminalViewport.bounds.height > 0 else { return }
449 guard GhosttyRuntime.ensureInitialized() else {
450 surfaceCreationFailed = true
451 return
452 }
453
454 isCreatingSurface = true
455 defer { isCreatingSurface = false }
456
457 var runtimeConfig = ghostty_runtime_config_s(
458 userdata: Unmanaged.passUnretained(self).toOpaque(),
459 supports_selection_clipboard: false,
460 wakeup_cb: { _ in },
461 action_cb: { _, _, _ in false },
462 read_clipboard_cb: { _, _, _ in false },
463 confirm_read_clipboard_cb: { _, _, _, _ in },
464 write_clipboard_cb: { _, _, _, _, _ in },
465 close_surface_cb: { _, _ in }
466 )
467
468 guard let config = ghostty_config_new() else {
469 surfaceCreationFailed = true
470 return
471 }
472 loadThemeConfig(into: config)
473 ghostty_config_finalize(config)
474 defer { ghostty_config_free(config) }
475
476 guard let createdApp = ghostty_app_new(&runtimeConfig, config) else {
477 surfaceCreationFailed = true
478 return
479 }
480
481 var surfaceConfig = ghostty_surface_config_new()
482 surfaceConfig.platform_tag = GHOSTTY_PLATFORM_IOS
483 surfaceConfig.platform.ios.uiview = Unmanaged.passUnretained(terminalViewport).toOpaque()
484 surfaceConfig.userdata = Unmanaged.passUnretained(self).toOpaque()
485 surfaceConfig.scale_factor = Double(contentScaleFactor)
486 surfaceConfig.font_size = Float(fontSize)
487 surfaceConfig.context = GHOSTTY_SURFACE_CONTEXT_WINDOW
488 surfaceConfig.use_custom_io = true
489
490 guard let createdSurface = ghostty_surface_new(createdApp, &surfaceConfig) else {
491 ghostty_app_free(createdApp)
492 surfaceCreationFailed = true
493 return
494 }
495
496 app = createdApp
497 surface = createdSurface
498 ghostty_app_set_color_scheme(createdApp, appearance.ghosttyColorScheme)
499 ghostty_surface_set_color_scheme(createdSurface, appearance.ghosttyColorScheme)
500 setupWriteCallback()
501 resizeSurface()
502 feedBuffer(initialBuffer)
503 }
504
505 private func resetSurface() {
506 destroySurface()
507 lastAppliedBuffer = ""
508 lastViewportSize = .zero
509 lastContentScale = 0
510 lastReportedGrid = nil
511 surfaceCreationFailed = false
512 setNeedsLayout()
513 }
514
515 private func refreshSurface() {
516 resetSurface()
517 createSurfaceIfPossible()
518 }
519
520 private func destroySurface() {
521 if let surface {
522 ghostty_surface_set_write_callback(surface, nil, nil)
523 ghostty_surface_free(surface)
524 }
525 if let app {
526 ghostty_app_free(app)
527 }
528 surface = nil
529 app = nil
530 }
531
532 private func applyRemoteBuffer(_ buffer: String) {
533 guard surface != nil else {
534 createSurfaceIfPossible()
535 return
536 }
537
538 if buffer.isEmpty {
539 feedData(Data("\u{1B}[3J\u{1B}[H\u{1B}[2J".utf8))
540 lastAppliedBuffer = ""
541 return
542 }
543
544 if buffer.hasPrefix(lastAppliedBuffer) {
545 let suffix = String(buffer.dropFirst(lastAppliedBuffer.count))
546 feedData(Data(suffix.utf8))
547 lastAppliedBuffer = buffer
548 return
549 }
550
551 resetSurface()
552 createSurfaceIfPossible()
553 }
554
555 private func feedBuffer(_ buffer: String) {
556 guard !buffer.isEmpty else { return }
557 feedData(Data(buffer.utf8))
558 lastAppliedBuffer = buffer
559 }
560
561 private func feedData(_ data: Data) {
562 guard let surface, !data.isEmpty else { return }
563
564 data.withUnsafeBytes { buffer in
565 guard let pointer = buffer.baseAddress?.assumingMemoryBound(to: UInt8.self) else {
566 return
567 }
568 ghostty_surface_feed_data(surface, pointer, buffer.count)
569 }
570
571 redrawSurface()
572 }
573
574 private func setupWriteCallback() {
575 guard let surface else { return }
576
577 let userdata = Unmanaged.passUnretained(self).toOpaque()
578 ghostty_surface_set_write_callback(surface, { userdata, data, len in
579 guard let userdata, let data, len > 0 else { return }
580 let view = Unmanaged<T3TerminalView>.fromOpaque(userdata).takeUnretainedValue()
581 let bytes = Data(bytes: data, count: len)
582 guard let input = String(data: bytes, encoding: .utf8), !input.isEmpty else { return }
583
584 DispatchQueue.main.async {
585 view.onInput(["data": input])
586 }
587 }, userdata)
588 }
589
590 private func resizeSurface() {
591 guard let surface else {
592 emitEstimatedResize()
593 return
594 }
595
596 let scale = contentScaleFactor
597 let width = UInt32(max(floor(terminalViewport.bounds.width * scale), 1))
598 let height = UInt32(max(floor(terminalViewport.bounds.height * scale), 1))
599
600 terminalViewport.contentScaleFactor = scale
601 ghostty_surface_set_content_scale(surface, Double(scale), Double(scale))
602 ghostty_surface_set_size(surface, width, height)
603 ghostty_surface_set_occlusion(surface, window != nil)
604 configureIOSurfaceLayers()
605 redrawSurface()
606 emitGhosttyResize()
607 }
608
609 private func redrawSurface() {
610 guard let surface else { return }
611 ghostty_surface_refresh(surface)
612 ghostty_surface_draw(surface)
613 markIOSurfaceLayersForDisplay()
614 emitGhosttyResize()
615 }
616
617 private func emitGhosttyResize() {
618 guard let surface else {
619 emitEstimatedResize()
620 return
621 }
622
623 let size = ghostty_surface_size(surface)
624 let cols = max(1, Int(size.columns))
625 let rows = max(1, Int(size.rows))
626 emitResize(cols: cols, rows: rows)
627 }
628
629 private func emitEstimatedResize() {
630 guard bounds.width > 0, bounds.height > 0 else { return }
631
632 let cellWidth = max(fontSize * 0.62, 1)
633 let cellHeight = max(fontSize * 1.35, 1)
634 let cols = max(20, min(400, Int(bounds.width / cellWidth)))
635 let terminalHeight = max(bounds.height, 0)
636 let rows = max(5, min(200, Int(terminalHeight / cellHeight)))
637 emitResize(cols: cols, rows: rows)
638 }
639
640 private func emitResize(cols: Int, rows: Int) {
641 guard lastReportedGrid?.cols != cols || lastReportedGrid?.rows != rows else {
642 return
643 }
644
645 lastReportedGrid = (cols, rows)
646 onResize([
647 "cols": cols,
648 "rows": rows,
649 ])
650 }
651
652 private func updateContentScale() {
653 let scale = window?.screen.scale ?? UIScreen.main.scale
654 if contentScaleFactor != scale {
655 contentScaleFactor = scale
656 }
657 }
658
659 private func requestKeyboardFocus() {
660 guard window != nil else { return }
661 inputField.becomeFirstResponder()
662 textInputModeDidChange()
663 }
664
665 private func emitInput(_ data: String) {
666 guard !data.isEmpty else { return }
667 onInput(["data": data])
668 }
669
670 private func textInputModeDidChange() {
671 guard let app else { return }
672 ghostty_app_keyboard_changed(app)
673 }
674
675 private func configureIOSurfaceLayers() {
676 let targetBounds = CGRect(origin: .zero, size: terminalViewport.bounds.size)
677 CATransaction.begin()
678 CATransaction.setDisableActions(true)
679 terminalViewport.layer.sublayers?.forEach { sublayer in
680 sublayer.frame = targetBounds
681 sublayer.contentsScale = contentScaleFactor
682 }
683 CATransaction.commit()
684 }
685
686 private func markIOSurfaceLayersForDisplay() {
687 terminalViewport.layer.setNeedsDisplay()
688 terminalViewport.layer.sublayers?.forEach { layer in
689 layer.setNeedsDisplay()
690 }
691 }
692
693 private func applyTheme() {
694 backgroundColor = backgroundColorValue
695 terminalViewport.backgroundColor = backgroundColorValue
696 }
697
698 private func loadThemeConfig(into config: ghostty_config_t) {
699 guard let path = writeThemeConfigFile() else { return }
700 path.withCString { cString in
701 ghostty_config_load_file(config, cString)
702 }
703 }
704
705 private func writeThemeConfigFile() -> String? {
706 guard !themeConfig.isEmpty else { return nil }
707 let configContents = themeConfig
708 let url = URL(fileURLWithPath: NSTemporaryDirectory())
709 .appendingPathComponent("t3-terminal-theme-\(appearance.rawValue).ghostty")
710
711 do {
712 if let existing = try? String(contentsOf: url, encoding: .utf8), existing == configContents {
713 return url.path
714 }
715
716 try configContents.write(to: url, atomically: true, encoding: .utf8)
717 return url.path
718 } catch {
719 return nil
720 }
721 }
722}