Files
ghostty/macos/Sources/Helpers/KeyboardLayout.swift
Jon Parise f5ad3a0a4a macos: use AppKit for shortcut translation
Translate synthetic physical-key events with characters(byApplyingModifiers:).
This preserves current-layout and Command-table behavior while avoiding a
duplicate direct UCKeyTranslate implementation in Swift.
2026-08-19 14:14:12 -04:00

42 lines
1.3 KiB
Swift

import AppKit
import Carbon
class KeyboardLayout {
/// Return a string ID of the current keyboard input source.
static var id: String? {
if let source = TISCopyCurrentKeyboardInputSource()?.takeRetainedValue(),
let sourceIdPointer = TISGetInputSourceProperty(source, kTISPropertyInputSourceID) {
let sourceId = unsafeBitCast(sourceIdPointer, to: CFString.self)
return sourceId as String
}
return nil
}
/// Translate a physical keycode for use as a menu key equivalent.
///
/// AppKit retranslates against the current input source without changing its dead key state.
@MainActor static func character(
for keyCode: UInt16,
modifiers: NSEvent.ModifierFlags
) -> Character? {
guard
let event = NSEvent.keyEvent(
with: .keyDown,
location: .zero,
modifierFlags: [],
timestamp: 0,
windowNumber: 0,
context: nil,
characters: "",
charactersIgnoringModifiers: "",
isARepeat: false,
keyCode: keyCode),
let result = event.characters(byApplyingModifiers: modifiers.intersection(.command)),
result.count == 1
else { return nil }
return result.first
}
}