Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions Sources/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1938,6 +1938,26 @@ func shouldRouteCommandEquivalentDirectlyToMainMenu(_ event: NSEvent) -> Bool {
return true
}

private enum TerminalPasteCommandEquivalent {
case paste
case pasteAsPlainText
}

private func terminalPasteCommandEquivalent(for event: NSEvent) -> TerminalPasteCommandEquivalent? {
guard event.keyCode == 9 else { return nil } // V key (hardware position, layout-independent)

let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask)
let normalizedFlags = flags.subtracting([.numericPad, .function, .capsLock])
switch normalizedFlags {
case [.command]:
return .paste
case [.command, .shift]:
return .pasteAsPlainText
default:
return nil
}
}

private enum BrowserFindCommandEquivalent {
case find
case findNext
Expand Down Expand Up @@ -14506,6 +14526,37 @@ private extension NSWindow {
}
}

if let ghosttyView = firstResponderGhosttyView,
let pasteCommand = terminalPasteCommandEquivalent(for: event),
GhosttyPasteboardHelper.hasString(for: GHOSTTY_CLIPBOARD_STANDARD) {
// If the window-level direct-to-menu path misses Cmd+V, do not let the
// event fall through to generic keyDown routing. Bracketed-paste TUIs
// such as OpenCode need the dedicated terminal paste action.
let handledDirectPaste: Bool
switch pasteCommand {
case .paste:
handledDirectPaste = ghosttyView.prepareSurfaceForPaste(
reason: "window.performKeyEquivalent.paste.missingSurface"
)
if handledDirectPaste {
Comment thread
lawrencecchen marked this conversation as resolved.
Resolved
ghosttyView.paste(nil)
}
case .pasteAsPlainText:
handledDirectPaste = ghosttyView.prepareSurfaceForPaste(
reason: "window.performKeyEquivalent.pasteAsPlainText.missingSurface"
)
if handledDirectPaste {
ghosttyView.pasteAsPlainText(nil)
}
}
if handledDirectPaste {
#if DEBUG
dlog(" → consumed by direct terminal paste fallback")
#endif
return true
}
}

let result = cmux_performKeyEquivalent(with: event)
#if DEBUG
if result { dlog(" → consumed by original performKeyEquivalent") }
Expand Down
11 changes: 11 additions & 0 deletions Sources/GhosttyTerminalView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5927,6 +5927,15 @@ class GhosttyNSView: NSView, NSUserInterfaceValidations {
#endif
}

@discardableResult
func prepareSurfaceForPaste(reason: String) -> Bool {
guard ensureSurfaceReadyForInput() != nil else {
requestInputRecoveryAfterSurfaceMiss(reason: reason)
return false
}
return true
}

func performBindingAction(_ action: String) -> Bool {
guard let surface = surface else { return false }
return action.withCString { cString in
Expand Down Expand Up @@ -6149,11 +6158,13 @@ class GhosttyNSView: NSView, NSUserInterfaceValidations {
// MARK: - Clipboard paste

@IBAction func paste(_ sender: Any?) {
guard prepareSurfaceForPaste(reason: "paste.missingSurface") else { return }
_ = performBindingAction("paste_from_clipboard")
}

/// Pastes clipboard text as plain text, stripping any rich formatting.
@IBAction func pasteAsPlainText(_ sender: Any?) {
guard prepareSurfaceForPaste(reason: "pasteAsPlainText.missingSurface") else { return }
_ = performBindingAction("paste_from_clipboard")
}

Expand Down
216 changes: 216 additions & 0 deletions cmuxTests/CJKIMEInputTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import ObjectiveC.runtime

private var cjkIMEInterpretKeyEventsSwizzled = false
private var cjkIMEInterpretKeyEventsHook: ((GhosttyNSView, [NSEvent]) -> Bool)?
private var ghosttyPasteActionSwizzled = false
private var ghosttyPasteActionHook: ((GhosttyNSView, Any?) -> Void)?
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

private extension GhosttyNSView {
@objc func cmuxUnitTest_interpretKeyEvents(_ eventArray: [NSEvent]) {
Expand All @@ -18,6 +20,11 @@ private extension GhosttyNSView {
}
cmuxUnitTest_interpretKeyEvents(eventArray)
}

@objc func cmuxUnitTest_paste(_ sender: Any?) {
ghosttyPasteActionHook?(self, sender)
cmuxUnitTest_paste(sender)
}
}

private func installCJKIMEInterpretKeyEventsSwizzle() {
Expand Down Expand Up @@ -52,6 +59,38 @@ private func installCJKIMEInterpretKeyEventsSwizzle() {
cjkIMEInterpretKeyEventsSwizzled = true
}

private func installGhosttyPasteActionSwizzle() {
guard !ghosttyPasteActionSwizzled else { return }

let originalSelector = #selector(GhosttyNSView.paste(_:))
let swizzledSelector = #selector(GhosttyNSView.cmuxUnitTest_paste(_:))

guard let originalMethod = class_getInstanceMethod(GhosttyNSView.self, originalSelector),
let swizzledMethod = class_getInstanceMethod(GhosttyNSView.self, swizzledSelector) else {
fatalError("Unable to locate GhosttyNSView paste methods for swizzling")
}

let didAddMethod = class_addMethod(
GhosttyNSView.self,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod)
)

if didAddMethod {
class_replaceMethod(
GhosttyNSView.self,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod)
)
} else {
method_exchangeImplementations(originalMethod, swizzledMethod)
}

ghosttyPasteActionSwizzled = true
}

private func findGhosttyNSView(in view: NSView) -> GhosttyNSView? {
if let view = view as? GhosttyNSView {
return view
Expand Down Expand Up @@ -1470,6 +1509,10 @@ final class GhosttyBackquoteRegressionTests: XCTestCase {

@MainActor
final class GhosttyPrintableShiftKeyEquivalentRegressionTests: XCTestCase {
private struct PasteboardItemSnapshot {
let representations: [(type: NSPasteboard.PasteboardType, data: Data)]
}

private struct HostedTerminalWindow {
let surface: TerminalSurface
let window: NSWindow
Expand Down Expand Up @@ -1516,6 +1559,48 @@ final class GhosttyPrintableShiftKeyEquivalentRegressionTests: XCTestCase {
)
}

private func snapshotPasteboardItems(_ pasteboard: NSPasteboard) -> [PasteboardItemSnapshot] {
guard let items = pasteboard.pasteboardItems else { return [] }
return items.map { item in
let representations = item.types.compactMap { type -> (NSPasteboard.PasteboardType, Data)? in
guard let data = item.data(forType: type) else { return nil }
return (type, data)
}
return PasteboardItemSnapshot(representations: representations)
}
}

private func restorePasteboardItems(
_ snapshots: [PasteboardItemSnapshot],
to pasteboard: NSPasteboard
) {
pasteboard.clearContents()
guard !snapshots.isEmpty else { return }
let items = snapshots.compactMap { snapshot -> NSPasteboardItem? in
let item = NSPasteboardItem()
guard !snapshot.representations.isEmpty else { return nil }
for representation in snapshot.representations {
item.setData(representation.data, forType: representation.type)
}
return item
}
if !items.isEmpty {
_ = pasteboard.writeObjects(items)
}
}

private func installUnrelatedMainMenu() -> NSMenu {
let mainMenu = NSMenu()
let fileItem = NSMenuItem(title: "File", action: nil, keyEquivalent: "")
let fileMenu = NSMenu(title: "File")
let item = NSMenuItem(title: "New", action: nil, keyEquivalent: "n")
item.keyEquivalentModifierMask = [.command]
fileMenu.addItem(item)
mainMenu.addItem(fileItem)
mainMenu.setSubmenu(fileMenu, for: fileItem)
return mainMenu
}

func testShiftSlashPrintableKeyEquivalentBypassesShortcutPath() throws {
let hostedTerminal = try makeHostedTerminalWindow()
let window = hostedTerminal.window
Expand Down Expand Up @@ -1581,6 +1666,137 @@ final class GhosttyPrintableShiftKeyEquivalentRegressionTests: XCTestCase {
)
}
}

func testCommandVPasteStillInvokesTerminalPasteWhenMainMenuMisses() throws {
installGhosttyPasteActionSwizzle()

let hostedTerminal = try makeHostedTerminalWindow()
let window = hostedTerminal.window
let surfaceView = hostedTerminal.surfaceView
defer { window.orderOut(nil) }

window.makeFirstResponder(surfaceView)
XCTAssertNotNil(surfaceView.terminalSurface)

let previousMainMenu = NSApp.mainMenu
NSApp.mainMenu = installUnrelatedMainMenu()
defer { NSApp.mainMenu = previousMainMenu }

let pasteboard = NSPasteboard.general
let pasteboardSnapshot = snapshotPasteboardItems(pasteboard)
defer { restorePasteboardItems(pasteboardSnapshot, to: pasteboard) }
pasteboard.clearContents()
pasteboard.setString("opencode paste", forType: .string)

var pasteInvocationCount = 0
let previousPasteHook = ghosttyPasteActionHook
ghosttyPasteActionHook = { _, _ in
pasteInvocationCount += 1
}
defer { ghosttyPasteActionHook = previousPasteHook }
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

var forwardedCommandVCount = 0
let previousKeyEventObserver = GhosttyNSView.debugGhosttySurfaceKeyEventObserver
GhosttyNSView.debugGhosttySurfaceKeyEventObserver = { keyEvent in
previousKeyEventObserver?(keyEvent)
guard keyEvent.action == GHOSTTY_ACTION_PRESS, keyEvent.keycode == 9 else { return }
forwardedCommandVCount += 1
}
defer {
GhosttyNSView.debugGhosttySurfaceKeyEventObserver = previousKeyEventObserver
}

guard let event = NSEvent.keyEvent(
with: .keyDown,
location: .zero,
modifierFlags: [.command],
timestamp: ProcessInfo.processInfo.systemUptime,
windowNumber: window.windowNumber,
context: nil,
characters: "v",
charactersIgnoringModifiers: "v",
isARepeat: false,
keyCode: 9
) else {
XCTFail("Failed to construct Cmd+V event")
return
}

XCTAssertTrue(window.performKeyEquivalent(with: event))
XCTAssertEqual(
pasteInvocationCount,
1,
"Cmd+V should still invoke the terminal paste action even if the window main-menu fast path misses"
)
XCTAssertEqual(
forwardedCommandVCount,
0,
"Cmd+V should not fall back to Ghostty keyDown when the terminal paste action is available"
)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

func testCommandVPasteRecreatesReleasedSurfaceBeforeConsumption() throws {
installGhosttyPasteActionSwizzle()

let hostedTerminal = try makeHostedTerminalWindow()
let window = hostedTerminal.window
let surfaceView = hostedTerminal.surfaceView
defer { window.orderOut(nil) }

window.makeFirstResponder(surfaceView)
XCTAssertNotNil(surfaceView.terminalSurface)
XCTAssertNotNil(hostedTerminal.surface.surface)

let previousMainMenu = NSApp.mainMenu
NSApp.mainMenu = installUnrelatedMainMenu()
defer { NSApp.mainMenu = previousMainMenu }

let pasteboard = NSPasteboard.general
let pasteboardSnapshot = snapshotPasteboardItems(pasteboard)
defer { restorePasteboardItems(pasteboardSnapshot, to: pasteboard) }
pasteboard.clearContents()
pasteboard.setString("surface recovery paste", forType: .string)

var pasteInvocationCount = 0
let previousPasteHook = ghosttyPasteActionHook
ghosttyPasteActionHook = { _, _ in
pasteInvocationCount += 1
}
defer { ghosttyPasteActionHook = previousPasteHook }

hostedTerminal.surface.releaseSurfaceForTesting()
XCTAssertNil(
hostedTerminal.surface.surface,
"Expected the runtime Ghostty surface to be released before simulating Cmd+V"
)

guard let event = NSEvent.keyEvent(
with: .keyDown,
location: .zero,
modifierFlags: [.command],
timestamp: ProcessInfo.processInfo.systemUptime,
windowNumber: window.windowNumber,
context: nil,
characters: "v",
charactersIgnoringModifiers: "v",
isARepeat: false,
keyCode: 9
) else {
XCTFail("Failed to construct Cmd+V event")
return
}

XCTAssertTrue(window.performKeyEquivalent(with: event))
XCTAssertEqual(
pasteInvocationCount,
1,
"Cmd+V should still invoke the terminal paste action after a transient surface release"
)
XCTAssertNotNil(
hostedTerminal.surface.surface,
"Cmd+V should recreate the Ghostty surface before the direct terminal paste fallback consumes the shortcut"
)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}
Comment thread
lawrencecchen marked this conversation as resolved.
Resolved

@MainActor
Expand Down
Loading