diff --git a/Sources/GhosttyTerminalView.swift b/Sources/GhosttyTerminalView.swift index 4ea30a20638b..765d888cd263 100644 --- a/Sources/GhosttyTerminalView.swift +++ b/Sources/GhosttyTerminalView.swift @@ -5370,7 +5370,9 @@ class GhosttyNSView: NSView, NSUserInterfaceValidations { #endif let inject = { - self.insertText(content, replacementRange: NSRange(location: NSNotFound, length: 0)) + self.withExternalCommittedText { + self.insertText(content, replacementRange: NSRange(location: NSNotFound, length: 0)) + } } if Thread.isMainThread { inject() @@ -5379,6 +5381,12 @@ class GhosttyNSView: NSView, NSUserInterfaceValidations { } } + private func withExternalCommittedText(_ body: () -> T) -> T { + externalCommittedTextDepth += 1 + defer { externalCommittedTextDepth -= 1 } + return body() + } + override func accessibilitySelectedTextRange() -> NSRange { selectedRange() } @@ -5527,6 +5535,7 @@ class GhosttyNSView: NSView, NSUserInterfaceValidations { private var keyTextAccumulator: [String]? = nil private var markedText = NSMutableAttributedString() private var lastPerformKeyEvent: TimeInterval? + private var externalCommittedTextDepth = 0 private struct SelectionSnapshot { let range: NSRange let string: String @@ -5573,7 +5582,9 @@ class GhosttyNSView: NSView, NSUserInterfaceValidations { /// responder-chain `insertText:` action (single-argument form). /// Route that into our NSTextInputClient path so text lands in the terminal. override func insertText(_ insertString: Any) { - insertText(insertString, replacementRange: NSRange(location: NSNotFound, length: 0)) + withExternalCommittedText { + insertText(insertString, replacementRange: NSRange(location: NSNotFound, length: 0)) + } } override func performKeyEquivalent(with event: NSEvent) -> Bool { @@ -9855,7 +9866,11 @@ final class GhosttySurfaceScrollView: NSView { // MARK: - NSTextInputClient extension GhosttyNSView: NSTextInputClient { - fileprivate func sendTextToSurface(_ chars: String) { + /// Deliver committed text using typed-input semantics so shells and editors + /// keep their normal interactive behaviors (autosuggestions, Return + /// execution, etc.). Programmatic callers can preserve literal ESC bytes so + /// automation payloads remain byte-for-byte stable. + fileprivate func sendTextToSurface(_ chars: String, preserveLiteralEscape: Bool) { guard let surface = surface else { return } #if DEBUG let typingTimingStart = CmuxTypingTiming.start() @@ -9869,16 +9884,68 @@ extension GhosttyNSView: NSTextInputClient { increments: ["probeInsertTextCount": 1] ) #endif - chars.withCString { ptr in + + var bufferedText = "" + var previousWasCR = false + + func flushBufferedText() { + guard !bufferedText.isEmpty else { return } var keyEvent = ghostty_input_key_s() keyEvent.action = GHOSTTY_ACTION_PRESS keyEvent.keycode = 0 keyEvent.mods = GHOSTTY_MODS_NONE keyEvent.consumed_mods = GHOSTTY_MODS_NONE - keyEvent.text = ptr + keyEvent.unshifted_codepoint = 0 keyEvent.composing = false - _ = ghostty_surface_key(surface, keyEvent) + bufferedText.withCString { ptr in + keyEvent.text = ptr + _ = sendGhosttyKey(surface, keyEvent) + } + bufferedText.removeAll(keepingCapacity: true) + } + + func sendControlKey(_ keycode: UInt32) { + var keyEvent = ghostty_input_key_s() + keyEvent.action = GHOSTTY_ACTION_PRESS + keyEvent.keycode = keycode + keyEvent.mods = GHOSTTY_MODS_NONE + keyEvent.consumed_mods = GHOSTTY_MODS_NONE + keyEvent.unshifted_codepoint = 0 + keyEvent.composing = false + keyEvent.text = nil + _ = sendGhosttyKey(surface, keyEvent) + } + + for scalar in chars.unicodeScalars { + switch scalar.value { + case 0x0A: + if !previousWasCR { + flushBufferedText() + sendControlKey(0x24) // kVK_Return + } + previousWasCR = false + case 0x0D: + flushBufferedText() + sendControlKey(0x24) // kVK_Return + previousWasCR = true + case 0x09: + flushBufferedText() + sendControlKey(0x30) // kVK_Tab + previousWasCR = false + case 0x1B: + if preserveLiteralEscape { + bufferedText.unicodeScalars.append(scalar) + } else { + flushBufferedText() + sendControlKey(0x35) // kVK_Escape + } + previousWasCR = false + default: + bufferedText.unicodeScalars.append(scalar) + previousWasCR = false + } } + flushBufferedText() #if DEBUG CmuxTypingTiming.logDuration( path: "terminal.sendTextToSurface", @@ -9888,6 +9955,115 @@ extension GhosttyNSView: NSTextInputClient { #endif } + /// External accessibility/dictation tools should commit plain text, but + /// some inject a leading escape sequence first. Strip those bytes on the + /// committed-text path so they can't leak into the PTY as literals. + static func sanitizeExternalCommittedText(_ text: String) -> String { + let bytes = Array(text.utf8) + guard !bytes.isEmpty else { return text } + + var index = 0 + while index < bytes.count { + let byte = bytes[index] + if byte == 0x1B { + index = consumeLeadingEscapeSequence(in: bytes, from: index) + continue + } + + if byte == 0xC2 { + let next = index + 1 + if next < bytes.count, bytes[next] == 0x9B { + // U+009B (C1 CSI) is encoded as the UTF-8 byte pair C2 9B. + index = consumeLeadingCSISequence(in: bytes, from: next + 1) + continue + } + } + + break + } + + if index == 0 { + return text + } + + guard index < bytes.count else { return "" } + return String(decoding: bytes[index...], as: UTF8.self) + } + + private static func consumeLeadingEscapeSequence( + in bytes: [UInt8], + from start: Int + ) -> Int { + let next = start + 1 + guard next < bytes.count else { return bytes.count } + + switch bytes[next] { + case 0x5B: + // CSI: ESC [ ... final + return consumeLeadingCSISequence(in: bytes, from: next + 1) + case 0x4F: + // SS3: ESC O final + return min(bytes.count, next + 2) + case 0x50, 0x5D, 0x5E, 0x5F: + // DCS/OSC/PM/APC: consume until BEL/ST or EOF. + return consumeLeadingEscapedStringSequence(in: bytes, from: next + 1) + default: + // Single-character escape. + return min(bytes.count, next + 1) + } + } + + private static func consumeLeadingCSISequence( + in bytes: [UInt8], + from start: Int + ) -> Int { + var index = start + while index < bytes.count { + let byte = bytes[index] + if (0x20...0x3F).contains(byte) { + index += 1 + continue + } + + if (0x40...0x7E).contains(byte) { + return index + 1 + } + + break + } + + return index + } + + private static func consumeLeadingEscapedStringSequence( + in bytes: [UInt8], + from start: Int + ) -> Int { + var index = start + while index < bytes.count { + let byte = bytes[index] + if byte == 0x07 { + return index + 1 + } + + if byte == 0x1B { + let next = index + 1 + if next < bytes.count, bytes[next] == 0x5C { + return next + 1 + } + return index + } + + if byte < 0x20 || byte == 0x7F { + return index + 1 + } + + index += 1 + } + + return bytes.count + } + func hasMarkedText() -> Bool { return markedText.length > 0 } @@ -10113,8 +10289,32 @@ extension GhosttyNSView: NSTextInputClient { return } + let isExternalCommittedText = externalCommittedTextDepth > 0 + let sanitizedChars = if isExternalCommittedText { + // Only sanitize explicit external committed-text paths used by + // AX/dictation integrations. Programmatic NSTextInputClient callers + // may intentionally start with ESC/CSI bytes. + Self.sanitizeExternalCommittedText(chars) + } else { + chars + } + +#if DEBUG + if sanitizedChars != chars { + dlog( + "ime.insertText.sanitized originalBytes=\(chars.utf8.count) " + + "sanitizedBytes=\(sanitizedChars.utf8.count)" + ) + } +#endif + + guard !sanitizedChars.isEmpty else { return } + // Otherwise send directly to the terminal - sendTextToSurface(chars) + sendTextToSurface( + sanitizedChars, + preserveLiteralEscape: !isExternalCommittedText + ) } } diff --git a/cmuxTests/CJKIMEInputTests.swift b/cmuxTests/CJKIMEInputTests.swift index af1000b00039..ae53c47002bc 100644 --- a/cmuxTests/CJKIMEInputTests.swift +++ b/cmuxTests/CJKIMEInputTests.swift @@ -870,6 +870,49 @@ final class CJKIMEKeyTextAccumulatorTests: XCTestCase { } } +// MARK: - External committed-text sanitization + +final class ExternalCommittedTextSanitizationTests: XCTestCase { + func testStripsLeadingCSISequenceFromExternalCommittedText() { + XCTAssertEqual( + GhosttyNSView.sanitizeExternalCommittedText("\u{1B}[Chello"), + "hello" + ) + } + + func testStripsLeadingC1CSISequenceFromExternalCommittedText() { + XCTAssertEqual( + GhosttyNSView.sanitizeExternalCommittedText("\u{009B}1;5Chello"), + "hello" + ) + } + + func testStripsMultipleLeadingControlAndEscapeSequences() { + XCTAssertEqual( + GhosttyNSView.sanitizeExternalCommittedText("\u{1B}[1;5C\u{1B}OChello"), + "hello" + ) + } + + func testLeavesLiteralBracketPrefixedTextUntouched() { + XCTAssertEqual( + GhosttyNSView.sanitizeExternalCommittedText("[Code] review"), + "[Code] review" + ) + } + + func testPreservesLeadingControlBytesUsedByAutomation() { + XCTAssertEqual( + GhosttyNSView.sanitizeExternalCommittedText("\n"), + "\n" + ) + XCTAssertEqual( + GhosttyNSView.sanitizeExternalCommittedText("\tfoo"), + "\tfoo" + ) + } +} + // MARK: - Shift+Space fallback suppression (IME source-switch shortcut) final class CJKIMEShiftSpaceFallbackTests: XCTestCase { @@ -1083,6 +1126,189 @@ final class KoreanIMEReturnCommitRegressionTests: XCTestCase { } } +@MainActor +final class AccessibilityInsertTextRegressionTests: XCTestCase { + func testDirectInsertTextUsesTypedInputSemantics() { + _ = NSApplication.shared + + let surface = TerminalSurface( + tabId: UUID(), + context: GHOSTTY_SURFACE_CONTEXT_SPLIT, + configTemplate: nil, + workingDirectory: nil + ) + let hostedView = surface.hostedView + + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 360, height: 240), + styleMask: [.titled, .closable], + backing: .buffered, + defer: false + ) + defer { + GhosttyNSView.debugGhosttySurfaceKeyEventObserver = nil + window.orderOut(nil) + } + + guard let contentView = window.contentView else { + XCTFail("Expected content view") + return + } + + hostedView.frame = contentView.bounds + hostedView.autoresizingMask = [.width, .height] + contentView.addSubview(hostedView) + + window.makeKeyAndOrderFront(nil) + window.displayIfNeeded() + contentView.layoutSubtreeIfNeeded() + hostedView.setVisibleInUI(true) + hostedView.setActive(true) + RunLoop.current.run(until: Date().addingTimeInterval(0.05)) + + guard let view = findGhosttyNSView(in: hostedView) else { + XCTFail("Expected hosted GhosttyNSView") + return + } + + var pressedText: [String] = [] + var pressedKeycodes: [UInt32] = [] + GhosttyNSView.debugGhosttySurfaceKeyEventObserver = { keyEvent in + guard keyEvent.action == GHOSTTY_ACTION_PRESS else { return } + if let text = keyEvent.text { + pressedText.append(String(cString: text)) + } else { + pressedKeycodes.append(keyEvent.keycode) + } + } + + view.insertText("dictated line\n", replacementRange: NSRange(location: NSNotFound, length: 0)) + + XCTAssertEqual(pressedText, ["dictated line"]) + XCTAssertEqual(pressedKeycodes, [36], "Trailing newline should be delivered as Return, not pasted text") + } + + func testDirectInsertTextPreservesLeadingEscapeForAutomation() { + _ = NSApplication.shared + + let surface = TerminalSurface( + tabId: UUID(), + context: GHOSTTY_SURFACE_CONTEXT_SPLIT, + configTemplate: nil, + workingDirectory: nil + ) + let hostedView = surface.hostedView + + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 360, height: 240), + styleMask: [.titled, .closable], + backing: .buffered, + defer: false + ) + defer { + GhosttyNSView.debugGhosttySurfaceKeyEventObserver = nil + window.orderOut(nil) + } + + guard let contentView = window.contentView else { + XCTFail("Expected content view") + return + } + + hostedView.frame = contentView.bounds + hostedView.autoresizingMask = [.width, .height] + contentView.addSubview(hostedView) + + window.makeKeyAndOrderFront(nil) + window.displayIfNeeded() + contentView.layoutSubtreeIfNeeded() + hostedView.setVisibleInUI(true) + hostedView.setActive(true) + RunLoop.current.run(until: Date().addingTimeInterval(0.05)) + + guard let view = findGhosttyNSView(in: hostedView) else { + XCTFail("Expected hosted GhosttyNSView") + return + } + + var pressedText: [String] = [] + var pressedKeycodes: [UInt32] = [] + GhosttyNSView.debugGhosttySurfaceKeyEventObserver = { keyEvent in + guard keyEvent.action == GHOSTTY_ACTION_PRESS else { return } + if let text = keyEvent.text { + pressedText.append(String(cString: text)) + } else { + pressedKeycodes.append(keyEvent.keycode) + } + } + + view.insertText("\u{1B}[A", replacementRange: NSRange(location: NSNotFound, length: 0)) + + XCTAssertEqual(pressedText, ["\u{1B}[A"]) + XCTAssertEqual(pressedKeycodes, [], "Direct NSTextInputClient insertText should preserve raw ESC bytes") + } + + func testAccessibilityValueSanitizesLeadingEscapeSequence() { + _ = NSApplication.shared + + let surface = TerminalSurface( + tabId: UUID(), + context: GHOSTTY_SURFACE_CONTEXT_SPLIT, + configTemplate: nil, + workingDirectory: nil + ) + let hostedView = surface.hostedView + + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 360, height: 240), + styleMask: [.titled, .closable], + backing: .buffered, + defer: false + ) + defer { + GhosttyNSView.debugGhosttySurfaceKeyEventObserver = nil + window.orderOut(nil) + } + + guard let contentView = window.contentView else { + XCTFail("Expected content view") + return + } + + hostedView.frame = contentView.bounds + hostedView.autoresizingMask = [.width, .height] + contentView.addSubview(hostedView) + + window.makeKeyAndOrderFront(nil) + window.displayIfNeeded() + contentView.layoutSubtreeIfNeeded() + hostedView.setVisibleInUI(true) + hostedView.setActive(true) + RunLoop.current.run(until: Date().addingTimeInterval(0.05)) + + guard let view = findGhosttyNSView(in: hostedView) else { + XCTFail("Expected hosted GhosttyNSView") + return + } + + var pressedText: [String] = [] + var pressedKeycodes: [UInt32] = [] + GhosttyNSView.debugGhosttySurfaceKeyEventObserver = { keyEvent in + guard keyEvent.action == GHOSTTY_ACTION_PRESS else { return } + if let text = keyEvent.text { + pressedText.append(String(cString: text)) + } else { + pressedKeycodes.append(keyEvent.keycode) + } + } + + view.setAccessibilityValue("\u{1B}[Adictated line\n") + + XCTAssertEqual(pressedText, ["dictated line"]) + XCTAssertEqual(pressedKeycodes, [36], "AX value insertion should sanitize injected ESC prefixes before sending text") + } +} + final class GhosttyBackquoteRegressionTests: XCTestCase { func testShiftBackquoteEscFallbackSendsLiteralTilde() { _ = NSApplication.shared