Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
8 changes: 8 additions & 0 deletions Sources/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5971,6 +5971,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
return true
}

if matchShortcut(event: event, shortcut: KeyboardShortcutSettings.shortcut(for: .toggleTerminalCopyMode)) {
let handled = tabManager?.toggleFocusedTerminalCopyMode() ?? false
if !handled {
NSSound.beep()
}
return true

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Don't consume copy-mode shortcut outside terminal focus

This handler always returns true once the shortcut matches, even when toggleFocusedTerminalCopyMode() fails (for example, when a browser panel or another non-terminal responder is focused), so the local shortcut monitor swallows Cmd+Shift+M and the focused control never receives it. In practice this breaks browser/web-app shortcuts in those contexts and only plays a beep; returning false when no terminal panel is actionable would preserve expected responder behavior.

Useful? React with 👍 / 👎.

}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// Workspace navigation: Cmd+Ctrl+] / Cmd+Ctrl+[
if matchShortcut(event: event, shortcut: KeyboardShortcutSettings.shortcut(for: .nextSidebarTab)) {
#if DEBUG
Expand Down
259 changes: 259 additions & 0 deletions Sources/GhosttyTerminalView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,109 @@ func resolveTerminalOpenURLTarget(_ rawValue: String) -> TerminalOpenURLTarget?
return .external(fallback)
}

enum TerminalKeyboardCopyModeSelectionMove: String, Equatable {
case left
case right
case up
case down
case pageUp = "page_up"
case pageDown = "page_down"
case home
case end
}

enum TerminalKeyboardCopyModeAction: Equatable {
case exit
case startSelection
case clearSelection
case copyAndExit
case scrollLines(Int)
case scrollPage(Int)
case scrollToTop
case scrollToBottom
case adjustSelection(TerminalKeyboardCopyModeSelectionMove)
}

func terminalKeyboardCopyModeShouldBypassForShortcut(modifierFlags: NSEvent.ModifierFlags) -> Bool {
let normalized = modifierFlags
.intersection(.deviceIndependentFlagsMask)
.subtracting([.numericPad, .function, .capsLock])
return normalized.contains(.command)
}

func terminalKeyboardCopyModeAction(
keyCode: UInt16,
charactersIgnoringModifiers: String?,
modifierFlags: NSEvent.ModifierFlags,
hasSelection: Bool
) -> TerminalKeyboardCopyModeAction? {
let normalized = modifierFlags
.intersection(.deviceIndependentFlagsMask)
.subtracting([.numericPad, .function, .capsLock])
let chars = (charactersIgnoringModifiers ?? "").lowercased()

if keyCode == 53 { // Escape
return .exit
}

switch keyCode {
case 126: // Up
return hasSelection ? .adjustSelection(.up) : .scrollLines(-1)
case 125: // Down
return hasSelection ? .adjustSelection(.down) : .scrollLines(1)
case 123: // Left
return hasSelection ? .adjustSelection(.left) : nil
case 124: // Right
return hasSelection ? .adjustSelection(.right) : nil
case 116: // Page Up
return hasSelection ? .adjustSelection(.pageUp) : .scrollPage(-1)
case 121: // Page Down
return hasSelection ? .adjustSelection(.pageDown) : .scrollPage(1)
case 115: // Home
return hasSelection ? .adjustSelection(.home) : .scrollToTop
case 119: // End
return hasSelection ? .adjustSelection(.end) : .scrollToBottom
default:
break
}

if normalized == [.control] {
if chars == "u" || chars == "\u{15}" {
return hasSelection ? .adjustSelection(.pageUp) : .scrollPage(-1)
}
if chars == "d" || chars == "\u{04}" {
return hasSelection ? .adjustSelection(.pageDown) : .scrollPage(1)
}
return nil
}

guard normalized.isEmpty || normalized == [.shift] else { return nil }

switch chars {
case "q":
return .exit
case "v":
return hasSelection ? .clearSelection : .startSelection
case "y":
return hasSelection ? .copyAndExit : nil
case "j":
return hasSelection ? .adjustSelection(.down) : .scrollLines(1)
case "k":
return hasSelection ? .adjustSelection(.up) : .scrollLines(-1)
case "h":
return hasSelection ? .adjustSelection(.left) : nil
case "l":
return hasSelection ? .adjustSelection(.right) : nil
case "g":
if normalized == [.shift] {
return hasSelection ? .adjustSelection(.end) : .scrollToBottom
}
return hasSelection ? .adjustSelection(.home) : .scrollToTop
default:
return nil
}
}

private final class GhosttySurfaceCallbackContext {
weak var surfaceView: GhosttyNSView?
weak var terminalSurface: TerminalSurface?
Expand Down Expand Up @@ -1641,6 +1744,7 @@ final class TerminalSurface: Identifiable, ObservableObject {
}
}
}
@Published private(set) var keyboardCopyModeActive: Bool = false
private var searchNeedleCancellable: AnyCancellable?

init(
Expand Down Expand Up @@ -2264,6 +2368,29 @@ final class TerminalSurface: Identifiable, ObservableObject {
}
}

@discardableResult
func toggleKeyboardCopyMode() -> Bool {
let handled = surfaceView.toggleKeyboardCopyMode()
if handled {
setKeyboardCopyModeActive(surfaceView.isKeyboardCopyModeActive)
}
return handled
}

func setKeyboardCopyModeActive(_ active: Bool) {
if !Thread.isMainThread {
DispatchQueue.main.async { [weak self] in
self?.setKeyboardCopyModeActive(active)
}
return
}

if keyboardCopyModeActive != active {
keyboardCopyModeActive = active
}
hostedView.setKeyboardCopyModeIndicator(visible: active)
}

func hasSelection() -> Bool {
guard let surface = surface else { return false }
return ghostty_surface_has_selection(surface)
Expand Down Expand Up @@ -2349,6 +2476,8 @@ class GhosttyNSView: NSView, NSUserInterfaceValidations {
private var lastLoggedWindowBackgroundSignature: String?
private var keySequence: [ghostty_input_trigger_s] = []
private var keyTables: [String] = []
fileprivate private(set) var keyboardCopyModeActive = false
fileprivate var isKeyboardCopyModeActive: Bool { keyboardCopyModeActive }
#if DEBUG
private static let keyLatencyProbeEnabled: Bool = {
if ProcessInfo.processInfo.environment["CMUX_KEY_LATENCY_PROBE"] == "1" {
Expand Down Expand Up @@ -2511,6 +2640,7 @@ class GhosttyNSView: NSView, NSUserInterfaceValidations {
terminalSurface = surface
tabId = surface.tabId
surface.attachToView(self)
surface.setKeyboardCopyModeActive(keyboardCopyModeActive)
updateSurfaceSize()
applySurfaceBackground()
applySurfaceColorScheme(force: true)
Expand Down Expand Up @@ -2779,6 +2909,64 @@ class GhosttyNSView: NSView, NSUserInterfaceValidations {
}
}

@discardableResult
func toggleKeyboardCopyMode() -> Bool {
guard surface != nil else { return false }
setKeyboardCopyModeActive(!keyboardCopyModeActive)
if !keyboardCopyModeActive, let surface {
_ = ghostty_surface_clear_selection(surface)
}
return true
}

private func setKeyboardCopyModeActive(_ active: Bool) {
keyboardCopyModeActive = active
terminalSurface?.setKeyboardCopyModeActive(active)
}

private func handleKeyboardCopyModeIfNeeded(_ event: NSEvent, surface: ghostty_surface_t) -> Bool {
guard keyboardCopyModeActive else { return false }

if terminalKeyboardCopyModeShouldBypassForShortcut(modifierFlags: event.modifierFlags) {
return false
}

let hasSelection = ghostty_surface_has_selection(surface)
guard let action = terminalKeyboardCopyModeAction(
keyCode: event.keyCode,
charactersIgnoringModifiers: event.charactersIgnoringModifiers,
modifierFlags: event.modifierFlags,
hasSelection: hasSelection
) else {
return true
}

switch action {
case .exit:
_ = ghostty_surface_clear_selection(surface)
setKeyboardCopyModeActive(false)
case .startSelection:
_ = ghostty_surface_select_cursor_cell(surface)
case .clearSelection:
_ = ghostty_surface_clear_selection(surface)
case .copyAndExit:
_ = performBindingAction("copy_to_clipboard")
_ = ghostty_surface_clear_selection(surface)
setKeyboardCopyModeActive(false)
case let .scrollLines(delta):
_ = performBindingAction("scroll_page_lines:\(delta)")
case let .scrollPage(delta):
_ = performBindingAction(delta > 0 ? "scroll_page_down" : "scroll_page_up")
case .scrollToTop:
_ = performBindingAction("scroll_to_top")
case .scrollToBottom:
_ = performBindingAction("scroll_to_bottom")
case let .adjustSelection(direction):
_ = performBindingAction("adjust_selection:\(direction.rawValue)")
}
return true
}

// MARK: - Input Handling

@IBAction func copy(_ sender: Any?) {
Expand Down Expand Up @@ -3141,6 +3329,9 @@ class GhosttyNSView: NSView, NSUserInterfaceValidations {
super.keyDown(with: event)
return
}
if handleKeyboardCopyModeIfNeeded(event, surface: surface) {
return
Comment thread
lawrencecchen marked this conversation as resolved.
Resolved
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
#if DEBUG
recordKeyLatency(path: "keyDown", event: event)
#endif
Expand Down Expand Up @@ -3975,6 +4166,14 @@ private final class GhosttyFlashOverlayView: NSView {
}
}

private final class GhosttyPassthroughVisualEffectView: NSVisualEffectView {
override var acceptsFirstResponder: Bool { false }

override func hitTest(_ point: NSPoint) -> NSView? {
nil
}
}

final class GhosttySurfaceScrollView: NSView {
private let backgroundView: NSView
private let scrollView: GhosttyScrollView
Expand All @@ -3986,6 +4185,8 @@ final class GhosttySurfaceScrollView: NSView {
private let notificationRingLayer: CAShapeLayer
private let flashOverlayView: GhosttyFlashOverlayView
private let flashLayer: CAShapeLayer
private let keyboardCopyModeBadgeView: GhosttyPassthroughVisualEffectView
private let keyboardCopyModeBadgeLabel: NSTextField
private var searchOverlayHostingView: NSHostingView<SurfaceSearchOverlay>?
private var observers: [NSObjectProtocol] = []
private var windowObservers: [NSObjectProtocol] = []
Expand Down Expand Up @@ -4121,6 +4322,8 @@ final class GhosttySurfaceScrollView: NSView {
notificationRingLayer = CAShapeLayer()
flashOverlayView = GhosttyFlashOverlayView(frame: .zero)
flashLayer = CAShapeLayer()
keyboardCopyModeBadgeView = GhosttyPassthroughVisualEffectView(frame: .zero)
keyboardCopyModeBadgeLabel = NSTextField(labelWithString: "VIM COPY")
scrollView.hasVerticalScroller = true
scrollView.hasHorizontalScroller = false
scrollView.autohidesScrollers = false
Expand Down Expand Up @@ -4193,6 +4396,33 @@ final class GhosttySurfaceScrollView: NSView {
flashLayer.opacity = 0
flashOverlayView.layer?.addSublayer(flashLayer)
addSubview(flashOverlayView)
keyboardCopyModeBadgeView.translatesAutoresizingMaskIntoConstraints = false
keyboardCopyModeBadgeView.wantsLayer = true
keyboardCopyModeBadgeView.material = .hudWindow
keyboardCopyModeBadgeView.blendingMode = .withinWindow
keyboardCopyModeBadgeView.state = .active
keyboardCopyModeBadgeView.layer?.cornerRadius = 7
keyboardCopyModeBadgeView.layer?.masksToBounds = true
keyboardCopyModeBadgeView.layer?.borderWidth = 1
keyboardCopyModeBadgeView.layer?.borderColor = cmuxAccentNSColor().withAlphaComponent(0.45).cgColor
keyboardCopyModeBadgeView.alphaValue = 0.97
keyboardCopyModeBadgeLabel.translatesAutoresizingMaskIntoConstraints = false
keyboardCopyModeBadgeLabel.font = NSFont.monospacedSystemFont(ofSize: 11, weight: .semibold)
keyboardCopyModeBadgeLabel.textColor = NSColor.labelColor
keyboardCopyModeBadgeLabel.lineBreakMode = .byClipping
keyboardCopyModeBadgeView.addSubview(keyboardCopyModeBadgeLabel)
NSLayoutConstraint.activate([
keyboardCopyModeBadgeLabel.leadingAnchor.constraint(equalTo: keyboardCopyModeBadgeView.leadingAnchor, constant: 8),
keyboardCopyModeBadgeLabel.trailingAnchor.constraint(equalTo: keyboardCopyModeBadgeView.trailingAnchor, constant: -8),
keyboardCopyModeBadgeLabel.topAnchor.constraint(equalTo: keyboardCopyModeBadgeView.topAnchor, constant: 4),
keyboardCopyModeBadgeLabel.bottomAnchor.constraint(equalTo: keyboardCopyModeBadgeView.bottomAnchor, constant: -4),
])
keyboardCopyModeBadgeView.isHidden = true
addSubview(keyboardCopyModeBadgeView)
NSLayoutConstraint.activate([
keyboardCopyModeBadgeView.topAnchor.constraint(equalTo: topAnchor, constant: 8),
keyboardCopyModeBadgeView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8),
])

scrollView.contentView.postsBoundsChangedNotifications = true
observers.append(NotificationCenter.default.addObserver(
Expand Down Expand Up @@ -4440,6 +4670,9 @@ final class GhosttySurfaceScrollView: NSView {
overlay.trailingAnchor.constraint(equalTo: trailingAnchor),
])
}
if !keyboardCopyModeBadgeView.isHidden {
addSubview(keyboardCopyModeBadgeView, positioned: .above, relativeTo: overlay)
}
return
}

Expand All @@ -4452,9 +4685,30 @@ final class GhosttySurfaceScrollView: NSView {
overlay.leadingAnchor.constraint(equalTo: leadingAnchor),
overlay.trailingAnchor.constraint(equalTo: trailingAnchor),
])
if !keyboardCopyModeBadgeView.isHidden {
addSubview(keyboardCopyModeBadgeView, positioned: .above, relativeTo: overlay)
}
searchOverlayHostingView = overlay
}

func setKeyboardCopyModeIndicator(visible: Bool) {
if !Thread.isMainThread {
DispatchQueue.main.async { [weak self] in
self?.setKeyboardCopyModeIndicator(visible: visible)
}
return
}

keyboardCopyModeBadgeView.isHidden = !visible
if visible {
if let overlay = searchOverlayHostingView {
addSubview(keyboardCopyModeBadgeView, positioned: .above, relativeTo: overlay)
} else {
addSubview(keyboardCopyModeBadgeView, positioned: .above, relativeTo: nil)
}
}
}

private func dropZoneOverlayFrame(for zone: DropZone, in size: CGSize) -> CGRect {
let padding: CGFloat = 4
switch zone {
Expand Down Expand Up @@ -4777,6 +5031,10 @@ final class GhosttySurfaceScrollView: NSView {
return overlay.superview === self && !overlay.isHidden
}

func debugHasKeyboardCopyModeIndicator() -> Bool {
keyboardCopyModeBadgeView.superview === self && !keyboardCopyModeBadgeView.isHidden
}

#endif

/// Handle file/URL drops, forwarding to the terminal as shell-escaped paths.
Expand Down Expand Up @@ -5658,6 +5916,7 @@ struct GhosttyTerminalView: NSViewRepresentable {
)
hostedView.setNotificationRing(visible: showsUnreadNotificationRing)
hostedView.setSearchOverlay(searchState: searchState)
hostedView.setKeyboardCopyModeIndicator(visible: terminalSurface.keyboardCopyModeActive)
hostedView.setFocusHandler { onFocus?(terminalSurface.id) }
hostedView.setTriggerFlashHandler(onTriggerFlash)
let forwardedDropZone = isVisibleInUI ? paneDropZone : nil
Expand Down
Loading