The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import ExpoModulesCore |
| 2 | import Foundation |
| 3 | import GhosttyKit |
| 4 | import QuartzCore |
| 5 | import UIKit |
| 6 | |
| 7 | private 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 | /// While a text field is first responder, iPadOS may consume presses before pressesBegan. |
| 26 | /// Priority UIKeyCommands capture terminal shortcuts before the text-input system handles them. |
| 27 | private enum TerminalHardwareKeyEncoder { |
| 28 | private static let controlInputs = "abcdefghijklmnopqrstuvwxyz@[\\]^_-? " |
| 29 | |
| 30 | static func makeKeyCommands(action: Selector) -> [UIKeyCommand] { |
| 31 | var commands: [UIKeyCommand] = [] |
| 32 | |
| 33 | let specialInputs = [ |
| 34 | UIKeyCommand.inputEscape, |
| 35 | UIKeyCommand.inputUpArrow, |
| 36 | UIKeyCommand.inputDownArrow, |
| 37 | UIKeyCommand.inputLeftArrow, |
| 38 | UIKeyCommand.inputRightArrow, |
| 39 | "\t", |
| 40 | ] |
| 41 | for input in specialInputs { |
| 42 | commands.append(makeCommand(input: input, modifierFlags: [], action: action)) |
| 43 | } |
| 44 | commands.append(makeCommand(input: "\t", modifierFlags: .shift, action: action)) |
| 45 | |
| 46 | for character in controlInputs { |
| 47 | commands.append(makeCommand(input: String(character), modifierFlags: .control, action: action)) |
| 48 | commands.append( |
| 49 | makeCommand(input: String(character), modifierFlags: [.control, .shift], action: action) |
| 50 | ) |
| 51 | } |
| 52 | |
| 53 | return commands |
| 54 | } |
| 55 | |
| 56 | private static func makeCommand( |
| 57 | input: String, |
| 58 | modifierFlags: UIKeyModifierFlags, |
| 59 | action: Selector |
| 60 | ) -> UIKeyCommand { |
| 61 | let command = UIKeyCommand(input: input, modifierFlags: modifierFlags, action: action) |
| 62 | command.wantsPriorityOverSystemBehavior = true |
| 63 | return command |
| 64 | } |
| 65 | |
| 66 | static func sequence(input: String, modifiers: UIKeyModifierFlags) -> String? { |
| 67 | switch input { |
| 68 | case UIKeyCommand.inputEscape: |
| 69 | return "\u{1B}" |
| 70 | case UIKeyCommand.inputUpArrow: |
| 71 | return "\u{1B}[A" |
| 72 | case UIKeyCommand.inputDownArrow: |
| 73 | return "\u{1B}[B" |
| 74 | case UIKeyCommand.inputRightArrow: |
| 75 | return "\u{1B}[C" |
| 76 | case UIKeyCommand.inputLeftArrow: |
| 77 | return "\u{1B}[D" |
| 78 | case "\t": |
| 79 | return modifiers.contains(.shift) ? "\u{1B}[Z" : "\t" |
| 80 | default: |
| 81 | break |
| 82 | } |
| 83 | |
| 84 | guard modifiers.contains(.control) else { return nil } |
| 85 | guard let scalar = input.lowercased().unicodeScalars.first else { return nil } |
| 86 | return controlSequence(for: scalar) |
| 87 | } |
| 88 | |
| 89 | private static func controlSequence(for scalar: Unicode.Scalar) -> String? { |
| 90 | switch scalar { |
| 91 | case "a"..."z": |
| 92 | return UnicodeScalar(scalar.value - 96).map(String.init) |
| 93 | case " ", "@": |
| 94 | return "\u{00}" |
| 95 | case "[": |
| 96 | return "\u{1B}" |
| 97 | case "\\": |
| 98 | return "\u{1C}" |
| 99 | case "]": |
| 100 | return "\u{1D}" |
| 101 | case "^": |
| 102 | return "\u{1E}" |
| 103 | case "_", "-": |
| 104 | return "\u{1F}" |
| 105 | case "?": |
| 106 | return "\u{7F}" |
| 107 | default: |
| 108 | return nil |
| 109 | } |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | /// Ghostty callbacks can fire during deinit and hop to main after it, so they must not retain the view. |
| 114 | private final class TerminalViewRef { |
| 115 | weak var view: T3TerminalView? |
| 116 | } |
| 117 | |
| 118 | private enum TerminalInputSequence { |
| 119 | /// Terminal Enter is carriage return. Sending line feed instead is Ctrl+J, |
| 120 | /// which raw-mode TUIs may interpret as the literal J key. |
| 121 | static let carriageReturn = "\r" |
| 122 | |
| 123 | static func normalizingReturn(_ input: String) -> String { |
| 124 | switch input { |
| 125 | case "\n", "\r\n": |
| 126 | return carriageReturn |
| 127 | default: |
| 128 | return input |
| 129 | } |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | private final class TerminalInputField: UITextField { |
| 134 | var onDeleteBackward: (() -> Void)? |
| 135 | var onInsert: ((String) -> Void)? |
| 136 | var onPaste: (() -> Void)? |
| 137 | |
| 138 | private static let hardwareKeyCommands = TerminalHardwareKeyEncoder.makeKeyCommands( |
| 139 | action: #selector(handleHardwareKeyCommand(_:)) |
| 140 | ) |
| 141 | |
| 142 | // While an IME composes, arrows, Tab and Escape pick or cancel candidates instead. |
| 143 | override var keyCommands: [UIKeyCommand]? { |
| 144 | markedTextRange == nil ? Self.hardwareKeyCommands : nil |
| 145 | } |
| 146 | |
| 147 | override func deleteBackward() { |
| 148 | // Backspace edits marked or committed field text first; the field diff sends that DEL. |
| 149 | if markedTextRange == nil, !hasText { |
| 150 | onDeleteBackward?() |
| 151 | } |
| 152 | super.deleteBackward() |
| 153 | } |
| 154 | |
| 155 | // System pastes must bypass typed input to preserve paste encoding and chunking. |
| 156 | override func paste(_ sender: Any?) { |
| 157 | // Commit an in-progress composition first so it reaches the PTY ahead of the paste. |
| 158 | if markedTextRange != nil { |
| 159 | unmarkText() |
| 160 | sendActions(for: .editingChanged) |
| 161 | } |
| 162 | onPaste?() |
| 163 | } |
| 164 | |
| 165 | @objc |
| 166 | private func handleHardwareKeyCommand(_ command: UIKeyCommand) { |
| 167 | guard let input = command.input else { return } |
| 168 | guard let sequence = TerminalHardwareKeyEncoder.sequence( |
| 169 | input: input, |
| 170 | modifiers: command.modifierFlags |
| 171 | ) else { return } |
| 172 | onInsert?(sequence) |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | private enum TerminalAppearanceScheme: String { |
| 177 | case light |
| 178 | case dark |
| 179 | |
| 180 | init(value: String) { |
| 181 | self = TerminalAppearanceScheme(rawValue: value) ?? .dark |
| 182 | } |
| 183 | |
| 184 | var ghosttyColorScheme: ghostty_color_scheme_e { |
| 185 | switch self { |
| 186 | case .light: |
| 187 | return GHOSTTY_COLOR_SCHEME_LIGHT |
| 188 | case .dark: |
| 189 | return GHOSTTY_COLOR_SCHEME_DARK |
| 190 | } |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | private extension UIColor { |
| 195 | convenience init(hexString: String) { |
| 196 | let sanitized = hexString.replacingOccurrences(of: "#", with: "") |
| 197 | let value = Int(sanitized, radix: 16) ?? 0 |
| 198 | self.init( |
| 199 | red: CGFloat((value >> 16) & 0xFF) / 255, |
| 200 | green: CGFloat((value >> 8) & 0xFF) / 255, |
| 201 | blue: CGFloat(value & 0xFF) / 255, |
| 202 | alpha: 1 |
| 203 | ) |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInteractionDelegate { |
| 208 | private static let minimumVerticalScrollStepPoints: CGFloat = 18 |
| 209 | private static let verticalScrollStepMultiplier: CGFloat = 1.15 |
| 210 | |
| 211 | private let terminalViewport = UIView() |
| 212 | private let inputField = TerminalInputField() |
| 213 | private let focusTapGesture = UITapGestureRecognizer() |
| 214 | private let scrollPanGesture = UIPanGestureRecognizer() |
| 215 | private let editMenuGesture = UILongPressGestureRecognizer() |
| 216 | private lazy var editMenuInteraction = UIEditMenuInteraction(delegate: self) |
| 217 | private var lastViewportSize: CGSize = .zero |
| 218 | private var lastContentScale: CGFloat = 0 |
| 219 | private var lastReportedGrid: (cols: Int, rows: Int)? |
| 220 | private var lastAppliedBuffer = "" |
| 221 | private var streamedOutput: TerminalOutputBuffer? |
| 222 | private var pendingVerticalScrollPoints: CGFloat = 0 |
| 223 | private var menuText: String? |
| 224 | private var sentInput = "" |
| 225 | private var app: ghostty_app_t? |
| 226 | private let callbackRef = TerminalViewRef() |
| 227 | private var surface: ghostty_surface_t? |
| 228 | private var isCreatingSurface = false |
| 229 | private var surfaceCreationFailed = false |
| 230 | private var appearance = TerminalAppearanceScheme.dark |
| 231 | private var backgroundColorValue = UIColor(hexString: "#24292e") |
| 232 | |
| 233 | let onInput = EventDispatcher() |
| 234 | let onResize = EventDispatcher() |
| 235 | let onCapture = EventDispatcher() |
| 236 | let onPaste = EventDispatcher() |
| 237 | var captureRequest: Double = 0 { |
| 238 | didSet { |
| 239 | guard captureRequest > 0, captureRequest != oldValue else { return } |
| 240 | let text = readViewportText() ?? "" |
| 241 | // Android joins snapshot rows with "\n" and trims each row's trailing whitespace, so do |
| 242 | // the same here: identical terminal content must capture identically on both platforms. |
| 243 | let normalized = text.split(separator: "\n", omittingEmptySubsequences: false) |
| 244 | .map { row -> String in |
| 245 | var line = String(row) |
| 246 | // Kotlin's trimEnd only strips ASCII whitespace; match it exactly. |
| 247 | while let last = line.last, last.isASCII && last.isWhitespace { line.removeLast() } |
| 248 | return line |
| 249 | } |
| 250 | .joined(separator: "\n") |
| 251 | onCapture(["text": normalized]) |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | var terminalKey: String = "" { |
| 256 | didSet { |
| 257 | accessibilityIdentifier = "t3-terminal-\(terminalKey)" |
| 258 | if oldValue != terminalKey { |
| 259 | resetSurface() |
| 260 | } |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | // Expo sets a batch's props in no fixed order, so the buffer waits for the whole batch: |
| 265 | // output fed before the same batch's sharedGrid lands would be drawn, and clipped, at the |
| 266 | // previous grid. |
| 267 | var initialBuffer: String = "" { |
| 268 | didSet { |
| 269 | hasPendingBuffer = true |
| 270 | } |
| 271 | } |
| 272 | private var hasPendingBuffer = false |
| 273 | |
| 274 | // The PTY grid shared by every attached client, or empty before the server reports one. |
| 275 | // The surface draws this grid so its wrapping and cursor match the PTY; the view's own |
| 276 | // fit still goes out through onResize. |
| 277 | var sharedGrid: [Int] = [] { |
| 278 | didSet { |
| 279 | guard oldValue != sharedGrid else { return } |
| 280 | resizeSurface() |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | var fontSize: CGFloat = 10 { |
| 285 | didSet { |
| 286 | guard oldValue != fontSize else { return } |
| 287 | inputField.font = UIFont.monospacedSystemFont(ofSize: max(fontSize, 13), weight: .regular) |
| 288 | applyConfigInPlace() |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | var focusRequest: Double = 0 { |
| 293 | didSet { |
| 294 | guard oldValue != focusRequest else { return } |
| 295 | DispatchQueue.main.async { [weak self] in |
| 296 | self?.requestKeyboardFocus() |
| 297 | } |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | var readOnly = false { |
| 302 | didSet { |
| 303 | if readOnly { |
| 304 | inputField.resignFirstResponder() |
| 305 | } |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | var autoFocus = true { |
| 310 | didSet { |
| 311 | guard oldValue != autoFocus else { return } |
| 312 | if autoFocus { |
| 313 | requestKeyboardFocus() |
| 314 | } else { |
| 315 | inputField.resignFirstResponder() |
| 316 | } |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | var appearanceScheme: String = TerminalAppearanceScheme.dark.rawValue { |
| 321 | didSet { |
| 322 | guard oldValue != appearanceScheme else { return } |
| 323 | appearance = TerminalAppearanceScheme(value: appearanceScheme) |
| 324 | applyConfigInPlace() |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | var themeConfig: String = "" { |
| 329 | didSet { |
| 330 | guard oldValue != themeConfig else { return } |
| 331 | applyConfigInPlace() |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | var backgroundColorHex: String = "#24292e" { |
| 336 | didSet { |
| 337 | backgroundColorValue = UIColor(hexString: backgroundColorHex) |
| 338 | applyTheme() |
| 339 | } |
| 340 | } |
| 341 | |
| 342 | var foregroundColorHex: String = "#d1d5da" |
| 343 | var mutedForegroundColorHex: String = "#959da5" |
| 344 | |
| 345 | public required init(appContext: AppContext? = nil) { |
| 346 | super.init(appContext: appContext) |
| 347 | callbackRef.view = self |
| 348 | |
| 349 | applyTheme() |
| 350 | clipsToBounds = true |
| 351 | // The real scale arrives with the window; layoutSubviews corrects it. |
| 352 | contentScaleFactor = traitCollection.displayScale |
| 353 | |
| 354 | terminalViewport.clipsToBounds = true |
| 355 | terminalViewport.contentScaleFactor = contentScaleFactor |
| 356 | terminalViewport.translatesAutoresizingMaskIntoConstraints = false |
| 357 | terminalViewport.isUserInteractionEnabled = true |
| 358 | |
| 359 | inputField.delegate = self |
| 360 | inputField.backgroundColor = UIColor.clear |
| 361 | inputField.textColor = UIColor.clear |
| 362 | inputField.tintColor = UIColor.clear |
| 363 | inputField.font = UIFont.monospacedSystemFont(ofSize: max(fontSize, 13), weight: .regular) |
| 364 | inputField.placeholder = "" |
| 365 | inputField.autocorrectionType = .no |
| 366 | inputField.autocapitalizationType = .none |
| 367 | inputField.spellCheckingType = .no |
| 368 | inputField.smartDashesType = .no |
| 369 | inputField.smartQuotesType = .no |
| 370 | inputField.smartInsertDeleteType = .no |
| 371 | inputField.returnKeyType = .send |
| 372 | inputField.keyboardType = .default |
| 373 | inputField.enablesReturnKeyAutomatically = false |
| 374 | inputField.translatesAutoresizingMaskIntoConstraints = false |
| 375 | inputField.alpha = 0.02 |
| 376 | inputField.isAccessibilityElement = false |
| 377 | inputField.accessibilityElementsHidden = true |
| 378 | inputField.addTarget(self, action: #selector(handleInputEditingDidBegin), for: .editingDidBegin) |
| 379 | inputField.addTarget(self, action: #selector(handleInputEditingChanged), for: .editingChanged) |
| 380 | inputField.onDeleteBackward = { [weak self] in |
| 381 | self?.emitInput("\u{7F}") |
| 382 | } |
| 383 | inputField.onInsert = { [weak self] data in |
| 384 | self?.emitInput(data) |
| 385 | self?.resetInputField() |
| 386 | } |
| 387 | inputField.onPaste = { [weak self] in |
| 388 | self?.emitPaste() |
| 389 | } |
| 390 | |
| 391 | focusTapGesture.addTarget(self, action: #selector(handleViewportTap)) |
| 392 | terminalViewport.addGestureRecognizer(focusTapGesture) |
| 393 | scrollPanGesture.addTarget(self, action: #selector(handleViewportPan(_:))) |
| 394 | scrollPanGesture.maximumNumberOfTouches = 1 |
| 395 | scrollPanGesture.cancelsTouchesInView = false |
| 396 | terminalViewport.addGestureRecognizer(scrollPanGesture) |
| 397 | editMenuGesture.addTarget(self, action: #selector(handleViewportLongPress(_:))) |
| 398 | terminalViewport.addGestureRecognizer(editMenuGesture) |
| 399 | terminalViewport.addInteraction(editMenuInteraction) |
| 400 | focusTapGesture.require(toFail: editMenuGesture) |
| 401 | |
| 402 | addSubview(terminalViewport) |
| 403 | addSubview(inputField) |
| 404 | |
| 405 | NSLayoutConstraint.activate([ |
| 406 | terminalViewport.leadingAnchor.constraint(equalTo: leadingAnchor), |
| 407 | terminalViewport.trailingAnchor.constraint(equalTo: trailingAnchor), |
| 408 | terminalViewport.topAnchor.constraint(equalTo: topAnchor), |
| 409 | terminalViewport.bottomAnchor.constraint(equalTo: bottomAnchor), |
| 410 | |
| 411 | inputField.trailingAnchor.constraint(equalTo: trailingAnchor), |
| 412 | inputField.topAnchor.constraint(equalTo: bottomAnchor, constant: 8), |
| 413 | inputField.widthAnchor.constraint(equalToConstant: 1), |
| 414 | inputField.heightAnchor.constraint(equalToConstant: 1), |
| 415 | ]) |
| 416 | } |
| 417 | |
| 418 | deinit { |
| 419 | destroySurface() |
| 420 | } |
| 421 | |
| 422 | public override func layoutSubviews() { |
| 423 | super.layoutSubviews() |
| 424 | updateContentScale() |
| 425 | |
| 426 | let viewportSize = terminalViewport.bounds.size |
| 427 | if surface == nil { |
| 428 | createSurfaceIfPossible() |
| 429 | } |
| 430 | |
| 431 | guard viewportSize != lastViewportSize || contentScaleFactor != lastContentScale else { |
| 432 | return |
| 433 | } |
| 434 | |
| 435 | lastViewportSize = viewportSize |
| 436 | lastContentScale = contentScaleFactor |
| 437 | resizeSurface() |
| 438 | } |
| 439 | |
| 440 | public override func didMoveToWindow() { |
| 441 | super.didMoveToWindow() |
| 442 | |
| 443 | guard window != nil, autoFocus else { return } |
| 444 | DispatchQueue.main.async { [weak self] in |
| 445 | self?.requestKeyboardFocus() |
| 446 | } |
| 447 | } |
| 448 | |
| 449 | public func textFieldShouldReturn(_ textField: UITextField) -> Bool { |
| 450 | // Return during a composition commits it; that is not Enter. |
| 451 | guard textField.markedTextRange == nil else { return false } |
| 452 | emitInput(TerminalInputSequence.carriageReturn) |
| 453 | resetInputField() |
| 454 | return false |
| 455 | } |
| 456 | |
| 457 | @objc |
| 458 | private func handleViewportTap() { |
| 459 | requestKeyboardFocus() |
| 460 | } |
| 461 | |
| 462 | private func readViewportText() -> String? { |
| 463 | guard let surface else { return nil } |
| 464 | let selection = ghostty_selection_s( |
| 465 | top_left: ghostty_point_s(tag: GHOSTTY_POINT_VIEWPORT, coord: GHOSTTY_POINT_COORD_TOP_LEFT, x: 0, y: 0), |
| 466 | bottom_right: ghostty_point_s(tag: GHOSTTY_POINT_VIEWPORT, coord: GHOSTTY_POINT_COORD_BOTTOM_RIGHT, x: 0, y: 0), |
| 467 | rectangle: false) |
| 468 | var captured = ghostty_text_s() |
| 469 | guard ghostty_surface_read_text(surface, selection, &captured) else { return nil } |
| 470 | defer { ghostty_surface_free_text(surface, &captured) } |
| 471 | guard let text = captured.text else { return nil } |
| 472 | return String( |
| 473 | bytes: UnsafeBufferPointer( |
| 474 | start: UnsafeRawPointer(text).assumingMemoryBound(to: UInt8.self), |
| 475 | count: Int(captured.text_len)), |
| 476 | encoding: .utf8) |
| 477 | } |
| 478 | |
| 479 | @objc |
| 480 | private func handleViewportPan(_ gesture: UIPanGestureRecognizer) { |
| 481 | guard let surface else { return } |
| 482 | |
| 483 | let location = gesture.location(in: terminalViewport) |
| 484 | ghostty_surface_mouse_pos( |
| 485 | surface, |
| 486 | Double(location.x * contentScaleFactor), |
| 487 | Double(location.y * contentScaleFactor), |
| 488 | GHOSTTY_MODS_NONE |
| 489 | ) |
| 490 | |
| 491 | switch gesture.state { |
| 492 | case .began: |
| 493 | pendingVerticalScrollPoints = 0 |
| 494 | gesture.setTranslation(.zero, in: terminalViewport) |
| 495 | case .changed: |
| 496 | let translation = gesture.translation(in: terminalViewport) |
| 497 | let stepSize = max( |
| 498 | fontSize * Self.verticalScrollStepMultiplier, |
| 499 | Self.minimumVerticalScrollStepPoints |
| 500 | ) |
| 501 | let totalVerticalPoints = pendingVerticalScrollPoints + translation.y |
| 502 | let verticalSteps = Int(totalVerticalPoints / stepSize) |
| 503 | pendingVerticalScrollPoints = totalVerticalPoints - (CGFloat(verticalSteps) * stepSize) |
| 504 | |
| 505 | guard verticalSteps != 0 else { |
| 506 | gesture.setTranslation(.zero, in: terminalViewport) |
| 507 | return |
| 508 | } |
| 509 | |
| 510 | ghostty_surface_mouse_scroll(surface, 0, Double(verticalSteps), 0) |
| 511 | redrawSurface() |
| 512 | gesture.setTranslation(.zero, in: terminalViewport) |
| 513 | default: |
| 514 | pendingVerticalScrollPoints = 0 |
| 515 | gesture.setTranslation(.zero, in: terminalViewport) |
| 516 | } |
| 517 | } |
| 518 | |
| 519 | // Korean keyboards build a syllable by replacing the committed character before the cursor, |
| 520 | // so the field keeps what was sent and each change goes out as DELs plus the new suffix. |
| 521 | // Scalars, not Characters: a Thai or Indic mark joins the previous grapheme, and resending |
| 522 | // that grapheme after one DEL would leave its base twice in a code-point line editor. |
| 523 | @objc |
| 524 | private func handleInputEditingChanged() { |
| 525 | guard inputField.markedTextRange == nil else { return } |
| 526 | let text = inputField.text ?? "" |
| 527 | let fieldScalars = text.unicodeScalars |
| 528 | let sentScalars = sentInput.unicodeScalars |
| 529 | let commonCount = zip(fieldScalars, sentScalars).prefix { $0.0 == $0.1 }.count |
| 530 | let unsent = String(String.UnicodeScalarView(sentScalars.dropFirst(commonCount))) |
| 531 | let added = String(String.UnicodeScalarView(fieldScalars.dropFirst(commonCount))) |
| 532 | // Some software keyboards deliver Return as an inserted newline instead of textFieldShouldReturn. |
| 533 | emitInput(String(repeating: "\u{7F}", count: unsent.count) + TerminalInputSequence.normalizingReturn(added)) |
| 534 | sentInput = text |
| 535 | // A Hangul syllable never spans whitespace; past the cap, keep the last character to compose onto. |
| 536 | if text.last?.isWhitespace == true { |
| 537 | resetInputField() |
| 538 | } else if text.count > 64 { |
| 539 | let last = String(text.suffix(1)) |
| 540 | inputField.text = last |
| 541 | sentInput = last |
| 542 | } |
| 543 | } |
| 544 | |
| 545 | @objc |
| 546 | private func handleViewportLongPress(_ gesture: UILongPressGestureRecognizer) { |
| 547 | guard gesture.state == .began else { return } |
| 548 | // Freeze the text the user pressed on; output keeps streaming while the menu is open. |
| 549 | menuText = readViewportText().flatMap { $0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? nil : $0 } |
| 550 | guard menuText != nil || canPaste else { return } |
| 551 | editMenuInteraction.presentEditMenu( |
| 552 | with: UIEditMenuConfiguration(identifier: nil, sourcePoint: gesture.location(in: terminalViewport)) |
| 553 | ) |
| 554 | } |
| 555 | |
| 556 | public func editMenuInteraction( |
| 557 | _ interaction: UIEditMenuInteraction, |
| 558 | menuFor configuration: UIEditMenuConfiguration, |
| 559 | suggestedActions: [UIMenuElement] |
| 560 | ) -> UIMenu? { |
| 561 | // The hidden input field would otherwise add actions such as Scan Text or Writing Tools. |
| 562 | // Keep the system Paste command: unlike a custom action, it reads without a paste prompt. |
| 563 | var children: [UIMenuElement] = Self.pasteCommand(in: suggestedActions).map { [$0] } ?? [] |
| 564 | if let text = menuText { |
| 565 | children.append( |
| 566 | UIAction(title: "Select Text", image: UIImage(systemName: "text.cursor")) { [weak self] _ in |
| 567 | self?.presentTextSelection(text) |
| 568 | }) |
| 569 | } |
| 570 | return children.isEmpty ? nil : UIMenu(children: children) |
| 571 | } |
| 572 | |
| 573 | private func presentTextSelection(_ text: String) { |
| 574 | guard let window else { return } |
| 575 | var responder: UIResponder? = self |
| 576 | while let current = responder, !(current is UIViewController) { |
| 577 | responder = current.next |
| 578 | } |
| 579 | guard let presenter = responder as? UIViewController, |
| 580 | presenter.viewIfLoaded?.window === window, |
| 581 | presenter.presentedViewController == nil, |
| 582 | !presenter.isBeingPresented, |
| 583 | !presenter.isBeingDismissed, |
| 584 | presenter.transitionCoordinator == nil |
| 585 | else { return } |
| 586 | |
| 587 | inputField.resignFirstResponder() |
| 588 | let controller = TerminalTextSelectionViewController(text: text, fontSize: fontSize) |
| 589 | let navigation = UINavigationController(rootViewController: controller) |
| 590 | navigation.modalPresentationStyle = .pageSheet |
| 591 | presenter.present(navigation, animated: !UIAccessibility.isReduceMotionEnabled) |
| 592 | } |
| 593 | |
| 594 | private static func pasteCommand(in elements: [UIMenuElement]) -> UIMenuElement? { |
| 595 | for element in elements { |
| 596 | if let command = element as? UICommand, |
| 597 | command.action == #selector(UIResponderStandardEditActions.paste(_:)) { |
| 598 | return command |
| 599 | } |
| 600 | if let menu = element as? UIMenu, let command = pasteCommand(in: menu.children) { |
| 601 | return command |
| 602 | } |
| 603 | } |
| 604 | return nil |
| 605 | } |
| 606 | |
| 607 | public override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { |
| 608 | if action == #selector(UIResponderStandardEditActions.paste(_:)) { |
| 609 | return canPaste |
| 610 | } |
| 611 | return super.canPerformAction(action, withSender: sender) |
| 612 | } |
| 613 | |
| 614 | public override func paste(_ sender: Any?) { |
| 615 | emitPaste() |
| 616 | } |
| 617 | |
| 618 | private var canPaste: Bool { |
| 619 | !readOnly && UIPasteboard.general.hasStrings |
| 620 | } |
| 621 | |
| 622 | @objc |
| 623 | private func handleInputEditingDidBegin() { |
| 624 | // A composition abandoned by losing focus must not reach the PTY with the next keystroke. |
| 625 | resetInputField() |
| 626 | textInputModeDidChange() |
| 627 | } |
| 628 | |
| 629 | func resetInputField() { |
| 630 | inputField.text = "" |
| 631 | sentInput = "" |
| 632 | } |
| 633 | |
| 634 | private func createSurfaceIfPossible() { |
| 635 | guard surface == nil, app == nil, !isCreatingSurface, !surfaceCreationFailed else { return } |
| 636 | guard terminalViewport.bounds.width > 0, terminalViewport.bounds.height > 0 else { return } |
| 637 | guard GhosttyRuntime.ensureInitialized() else { |
| 638 | surfaceCreationFailed = true |
| 639 | return |
| 640 | } |
| 641 | |
| 642 | isCreatingSurface = true |
| 643 | defer { isCreatingSurface = false } |
| 644 | |
| 645 | var runtimeConfig = ghostty_runtime_config_s( |
| 646 | userdata: Unmanaged.passUnretained(callbackRef).toOpaque(), |
| 647 | supports_selection_clipboard: false, |
| 648 | // The io thread queues app messages (titles, bells) in a bounded mailbox. Unless the main |
| 649 | // thread drains it, the io thread blocks and the next feed or surface free hangs the app. |
| 650 | wakeup_cb: { userdata in |
| 651 | guard let userdata else { return } |
| 652 | let ref = Unmanaged<TerminalViewRef>.fromOpaque(userdata).takeUnretainedValue() |
| 653 | DispatchQueue.main.async { ref.view?.tickApp() } |
| 654 | }, |
| 655 | action_cb: { _, _, _ in false }, |
| 656 | read_clipboard_cb: { _, _, _, _, _, _ in GHOSTTY_CLIPBOARD_READ_UNSUPPORTED }, |
| 657 | confirm_read_clipboard_cb: { _, _, _, _ in }, |
| 658 | write_clipboard_cb: { _, _, _, _, _ in }, |
| 659 | close_surface_cb: { _, _ in } |
| 660 | ) |
| 661 | |
| 662 | guard let config = ghostty_config_new() else { |
| 663 | surfaceCreationFailed = true |
| 664 | return |
| 665 | } |
| 666 | // Creation proceeds without the file, as before; font_size is also set on the surface config. |
| 667 | _ = loadThemeConfig(into: config) |
| 668 | ghostty_config_finalize(config) |
| 669 | defer { ghostty_config_free(config) } |
| 670 | |
| 671 | guard let createdApp = ghostty_app_new(&runtimeConfig, config) else { |
| 672 | surfaceCreationFailed = true |
| 673 | return |
| 674 | } |
| 675 | |
| 676 | var surfaceConfig = ghostty_surface_config_new() |
| 677 | surfaceConfig.platform_tag = GHOSTTY_PLATFORM_IOS |
| 678 | surfaceConfig.platform.ios.uiview = Unmanaged.passUnretained(terminalViewport).toOpaque() |
| 679 | surfaceConfig.userdata = Unmanaged.passUnretained(self).toOpaque() |
| 680 | surfaceConfig.scale_factor = Double(contentScaleFactor) |
| 681 | surfaceConfig.font_size = Float(fontSize) |
| 682 | surfaceConfig.context = GHOSTTY_SURFACE_CONTEXT_WINDOW |
| 683 | surfaceConfig.use_custom_io = true |
| 684 | |
| 685 | guard let createdSurface = ghostty_surface_new(createdApp, &surfaceConfig) else { |
| 686 | ghostty_app_free(createdApp) |
| 687 | surfaceCreationFailed = true |
| 688 | return |
| 689 | } |
| 690 | |
| 691 | app = createdApp |
| 692 | surface = createdSurface |
| 693 | ghostty_app_set_color_scheme(createdApp, appearance.ghosttyColorScheme) |
| 694 | ghostty_surface_set_color_scheme(createdSurface, appearance.ghosttyColorScheme) |
| 695 | setupWriteCallback() |
| 696 | resizeSurface() |
| 697 | if let streamedOutput { |
| 698 | feedData(streamedOutput.data) |
| 699 | } else if !hasPendingBuffer { |
| 700 | feedBuffer(initialBuffer) |
| 701 | } |
| 702 | } |
| 703 | |
| 704 | private func resetSurface() { |
| 705 | destroySurface() |
| 706 | lastAppliedBuffer = "" |
| 707 | lastViewportSize = .zero |
| 708 | lastContentScale = 0 |
| 709 | lastReportedGrid = nil |
| 710 | surfaceCreationFailed = false |
| 711 | setNeedsLayout() |
| 712 | } |
| 713 | |
| 714 | // Font and theme change in place: a new surface would replay output and re-answer its queries. |
| 715 | private func applyConfigInPlace() { |
| 716 | guard let app, let surface else { |
| 717 | resetSurface() |
| 718 | return |
| 719 | } |
| 720 | guard let config = ghostty_config_new() else { return } |
| 721 | defer { ghostty_config_free(config) } |
| 722 | let loaded = loadThemeConfig(into: config) |
| 723 | ghostty_config_finalize(config) |
| 724 | ghostty_app_set_color_scheme(app, appearance.ghosttyColorScheme) |
| 725 | ghostty_surface_set_color_scheme(surface, appearance.ghosttyColorScheme) |
| 726 | tickApp() |
| 727 | // Without the file, the config lacks font-size and would reset the surface to defaults. |
| 728 | if loaded { |
| 729 | ghostty_surface_update_config(surface, config) |
| 730 | } |
| 731 | resizeSurface() |
| 732 | setNeedsLayout() |
| 733 | } |
| 734 | |
| 735 | private func destroySurface() { |
| 736 | // Unblock the io thread before ghostty_surface_free joins it. |
| 737 | tickApp() |
| 738 | if let surface { |
| 739 | ghostty_surface_set_write_callback(surface, nil, nil) |
| 740 | ghostty_surface_free(surface) |
| 741 | } |
| 742 | if let app { |
| 743 | ghostty_app_free(app) |
| 744 | } |
| 745 | surface = nil |
| 746 | app = nil |
| 747 | // Ghostty adds its IOSurface layer to the viewport on iOS but never removes it on |
| 748 | // free, leaving the last frame on screen under the next surface's layer. The |
| 749 | // viewport has no subviews, so every sublayer belongs to a freed surface. |
| 750 | CATransaction.begin() |
| 751 | CATransaction.setDisableActions(true) |
| 752 | terminalViewport.layer.sublayers?.forEach { $0.removeFromSuperlayer() } |
| 753 | CATransaction.commit() |
| 754 | } |
| 755 | |
| 756 | func applyPendingBuffer() { |
| 757 | guard hasPendingBuffer else { return } |
| 758 | hasPendingBuffer = false |
| 759 | applyRemoteBuffer(initialBuffer) |
| 760 | } |
| 761 | |
| 762 | private func tickApp() { |
| 763 | guard let app else { return } |
| 764 | ghostty_app_tick(app) |
| 765 | } |
| 766 | |
| 767 | private func applyRemoteBuffer(_ buffer: String) { |
| 768 | guard streamedOutput == nil else { return } |
| 769 | guard surface != nil else { |
| 770 | createSurfaceIfPossible() |
| 771 | return |
| 772 | } |
| 773 | |
| 774 | if buffer.isEmpty { |
| 775 | feedData(Data("\u{1B}[3J\u{1B}[H\u{1B}[2J".utf8)) |
| 776 | lastAppliedBuffer = "" |
| 777 | return |
| 778 | } |
| 779 | |
| 780 | if buffer.hasPrefix(lastAppliedBuffer) { |
| 781 | let suffix = String(buffer.dropFirst(lastAppliedBuffer.count)) |
| 782 | feedData(Data(suffix.utf8)) |
| 783 | lastAppliedBuffer = buffer |
| 784 | return |
| 785 | } |
| 786 | |
| 787 | resetSurface() |
| 788 | createSurfaceIfPossible() |
| 789 | } |
| 790 | |
| 791 | func writeOutput(_ data: String, reset: Bool) { |
| 792 | let output = streamedOutput ?? TerminalOutputBuffer() |
| 793 | let bytes = Data(data.utf8) |
| 794 | output.write(bytes, reset: reset) |
| 795 | streamedOutput = output |
| 796 | if reset { |
| 797 | resetSurface() |
| 798 | } else if surface == nil { |
| 799 | createSurfaceIfPossible() |
| 800 | } else { |
| 801 | feedData(bytes) |
| 802 | } |
| 803 | } |
| 804 | |
| 805 | private func feedBuffer(_ buffer: String) { |
| 806 | guard !buffer.isEmpty else { return } |
| 807 | feedData(Data(buffer.utf8)) |
| 808 | lastAppliedBuffer = buffer |
| 809 | } |
| 810 | |
| 811 | private func feedData(_ data: Data) { |
| 812 | guard let surface, !data.isEmpty else { return } |
| 813 | |
| 814 | tickApp() |
| 815 | data.withUnsafeBytes { buffer in |
| 816 | guard let pointer = buffer.baseAddress?.assumingMemoryBound(to: UInt8.self) else { |
| 817 | return |
| 818 | } |
| 819 | ghostty_surface_feed_data(surface, pointer, buffer.count) |
| 820 | } |
| 821 | |
| 822 | redrawSurface() |
| 823 | } |
| 824 | |
| 825 | private func setupWriteCallback() { |
| 826 | guard let surface else { return } |
| 827 | |
| 828 | let userdata = Unmanaged.passUnretained(callbackRef).toOpaque() |
| 829 | ghostty_surface_set_write_callback(surface, { userdata, data, len in |
| 830 | guard let userdata, let data, len > 0 else { return } |
| 831 | let ref = Unmanaged<TerminalViewRef>.fromOpaque(userdata).takeUnretainedValue() |
| 832 | let bytes = Data(bytes: data, count: len) |
| 833 | guard let input = String(data: bytes, encoding: .utf8), !input.isEmpty else { return } |
| 834 | |
| 835 | DispatchQueue.main.async { |
| 836 | ref.view?.emitInput(input) |
| 837 | } |
| 838 | }, userdata) |
| 839 | } |
| 840 | |
| 841 | private func resizeSurface() { |
| 842 | guard let surface else { |
| 843 | emitEstimatedResize() |
| 844 | return |
| 845 | } |
| 846 | |
| 847 | let scale = contentScaleFactor |
| 848 | let width = UInt32(max(floor(terminalViewport.bounds.width * scale), 1)) |
| 849 | let height = UInt32(max(floor(terminalViewport.bounds.height * scale), 1)) |
| 850 | |
| 851 | terminalViewport.contentScaleFactor = scale |
| 852 | ghostty_surface_set_content_scale(surface, Double(scale), Double(scale)) |
| 853 | ghostty_surface_set_size(surface, width, height) |
| 854 | let fitted = ghostty_surface_size(surface) |
| 855 | let fittedCols = max(1, Int(fitted.columns)) |
| 856 | let fittedRows = max(1, Int(fitted.rows)) |
| 857 | // Trimming whole cells keeps ghostty's padding, and the surface can only shrink |
| 858 | // within the view, so a stale larger grid falls back to the fitted one. |
| 859 | var surfaceWidth = width |
| 860 | var surfaceHeight = height |
| 861 | if sharedGrid.count == 2, sharedGrid[0] > 0, sharedGrid[1] > 0 { |
| 862 | surfaceWidth -= UInt32(max(fittedCols - sharedGrid[0], 0)) * fitted.cell_width_px |
| 863 | surfaceHeight -= UInt32(max(fittedRows - sharedGrid[1], 0)) * fitted.cell_height_px |
| 864 | if surfaceWidth != width || surfaceHeight != height { |
| 865 | ghostty_surface_set_size(surface, surfaceWidth, surfaceHeight) |
| 866 | } |
| 867 | } |
| 868 | ghostty_surface_set_occlusion(surface, window != nil) |
| 869 | configureIOSurfaceLayers( |
| 870 | size: CGSize(width: CGFloat(surfaceWidth) / scale, height: CGFloat(surfaceHeight) / scale)) |
| 871 | redrawSurface() |
| 872 | emitResize(cols: fittedCols, rows: fittedRows) |
| 873 | } |
| 874 | |
| 875 | private func redrawSurface() { |
| 876 | guard let surface else { return } |
| 877 | ghostty_surface_refresh(surface) |
| 878 | ghostty_surface_draw(surface) |
| 879 | markIOSurfaceLayersForDisplay() |
| 880 | } |
| 881 | |
| 882 | private func emitEstimatedResize() { |
| 883 | guard bounds.width > 0, bounds.height > 0 else { return } |
| 884 | |
| 885 | let cellWidth = max(fontSize * 0.62, 1) |
| 886 | let cellHeight = max(fontSize * 1.35, 1) |
| 887 | let cols = max(20, min(400, Int(bounds.width / cellWidth))) |
| 888 | let terminalHeight = max(bounds.height, 0) |
| 889 | let rows = max(5, min(200, Int(terminalHeight / cellHeight))) |
| 890 | emitResize(cols: cols, rows: rows) |
| 891 | } |
| 892 | |
| 893 | private func emitResize(cols: Int, rows: Int) { |
| 894 | guard lastReportedGrid?.cols != cols || lastReportedGrid?.rows != rows else { |
| 895 | return |
| 896 | } |
| 897 | |
| 898 | lastReportedGrid = (cols, rows) |
| 899 | onResize([ |
| 900 | "cols": cols, |
| 901 | "rows": rows, |
| 902 | ]) |
| 903 | } |
| 904 | |
| 905 | private func updateContentScale() { |
| 906 | // The trait collection follows the scene the view is in, which matters once |
| 907 | // iPhone apps run resizable and on external displays; UIScreen.main does not. |
| 908 | let scale = traitCollection.displayScale |
| 909 | if contentScaleFactor != scale { |
| 910 | contentScaleFactor = scale |
| 911 | } |
| 912 | } |
| 913 | |
| 914 | private func requestKeyboardFocus() { |
| 915 | guard window != nil, !readOnly else { return } |
| 916 | inputField.becomeFirstResponder() |
| 917 | textInputModeDidChange() |
| 918 | } |
| 919 | |
| 920 | private func emitInput(_ data: String) { |
| 921 | guard !readOnly, !data.isEmpty else { return } |
| 922 | onInput(["data": data]) |
| 923 | } |
| 924 | |
| 925 | private func emitPaste() { |
| 926 | guard let text = UIPasteboard.general.string, !text.isEmpty else { return } |
| 927 | onPaste(["text": text]) |
| 928 | } |
| 929 | |
| 930 | private func textInputModeDidChange() { |
| 931 | guard let app else { return } |
| 932 | ghostty_app_keyboard_changed(app) |
| 933 | } |
| 934 | |
| 935 | private func configureIOSurfaceLayers(size: CGSize) { |
| 936 | let targetBounds = CGRect(origin: .zero, size: size) |
| 937 | CATransaction.begin() |
| 938 | CATransaction.setDisableActions(true) |
| 939 | terminalViewport.layer.sublayers?.forEach { sublayer in |
| 940 | sublayer.frame = targetBounds |
| 941 | sublayer.contentsScale = contentScaleFactor |
| 942 | } |
| 943 | CATransaction.commit() |
| 944 | } |
| 945 | |
| 946 | private func markIOSurfaceLayersForDisplay() { |
| 947 | terminalViewport.layer.setNeedsDisplay() |
| 948 | terminalViewport.layer.sublayers?.forEach { layer in |
| 949 | layer.setNeedsDisplay() |
| 950 | } |
| 951 | } |
| 952 | |
| 953 | private func applyTheme() { |
| 954 | backgroundColor = backgroundColorValue |
| 955 | terminalViewport.backgroundColor = backgroundColorValue |
| 956 | } |
| 957 | |
| 958 | private func loadThemeConfig(into config: ghostty_config_t) -> Bool { |
| 959 | guard let path = writeThemeConfigFile() else { return false } |
| 960 | path.withCString { cString in |
| 961 | ghostty_config_load_file(config, cString) |
| 962 | } |
| 963 | return true |
| 964 | } |
| 965 | |
| 966 | private func writeThemeConfigFile() -> String? { |
| 967 | let configContents = "\(themeConfig)\nfont-size = \(String(format: "%g", Double(fontSize)))\n" |
| 968 | let url = URL(fileURLWithPath: NSTemporaryDirectory()) |
| 969 | .appendingPathComponent("t3-terminal-theme-\(appearance.rawValue).ghostty") |
| 970 | |
| 971 | do { |
| 972 | if let existing = try? String(contentsOf: url, encoding: .utf8), existing == configContents { |
| 973 | return url.path |
| 974 | } |
| 975 | |
| 976 | try configContents.write(to: url, atomically: true, encoding: .utf8) |
| 977 | return url.path |
| 978 | } catch { |
| 979 | return nil |
| 980 | } |
| 981 | } |
| 982 | } |