Visual Studio Code, rebuilt in Rust
Rust
//! native-keymap's keyboard_mac.mm: Carbon's current input source and UCKeyTranslate, and AppKit's current event.
use std::ffi::c_void;
use std::sync::Mutex;
use objc2_foundation::{NSArray, NSString};
use serde_json::{Map, Value};
use super::{KeyEvent, MAC_KEY_CODES, is_control};
/// UCKeyTranslate's modifier key state: Carbon's `shiftKey` (1 << 9) and `optionKey` (1 << 11), shifted right by 8.
const SHIFT: u32 = 2;
const OPTION: u32 = 8;
#[link(name = "Carbon", kind = "framework")]
unsafe extern "C" {
fn TISCopyCurrentKeyboardInputSource() -> *const c_void;
fn TISCopyCurrentKeyboardLayoutInputSource() -> *const c_void;
fn TISGetInputSourceProperty(source: *const c_void, key: *const c_void) -> *const c_void;
fn UCKeyTranslate(
layout: *const c_void,
virtual_key_code: u16,
key_action: u16,
modifier_key_state: u32,
keyboard_type: u32,
options: u32,
dead_key_state: *mut u32,
max_length: usize,
actual_length: *mut usize,
unicode: *mut u16,
) -> i32;
fn LMGetKbdLast() -> u8;
static kTISPropertyUnicodeKeyLayoutData: *const c_void;
static kTISPropertyInputSourceID: *const c_void;
static kTISPropertyLocalizedName: *const c_void;
static kTISPropertyInputSourceLanguages: *const c_void;
}
#[link(name = "CoreFoundation", kind = "framework")]
unsafe extern "C" {
fn CFDataGetBytePtr(data: *const c_void) -> *const u8;
fn CFRelease(object: *const c_void);
}
/// Concurrent first TIS calls of a process abort it with no message (macOS 26 and 27); tests read the layout on
/// libtest's threads.
static TIS: Mutex<()> = Mutex::new(());
/// `getCurrentKeyboardLayout()`: `{ id, localizedName, lang }` of the current input source (IMacKeyboardLayoutInfo).
pub fn current_layout_info() -> Value {
let mut info = Map::new();
let _tis = TIS.lock().unwrap();
// SAFETY: TIS calls on the copied input source, released once below; each property is null or the type it is cast to (TextInputSources.h).
unsafe {
let source = TISCopyCurrentKeyboardInputSource();
let string = |key| (TISGetInputSourceProperty(source, key) as *const NSString).as_ref().map(|value| Value::from(value.to_string()));
if let Some(id) = string(kTISPropertyInputSourceID) {
info.insert("id".into(), id);
}
if let Some(name) = string(kTISPropertyLocalizedName) {
info.insert("localizedName".into(), name);
}
let languages = (TISGetInputSourceProperty(source, kTISPropertyInputSourceLanguages) as *const NSArray<NSString>).as_ref();
if let Some(lang) = languages.and_then(|languages| languages.firstObject()) {
info.insert("lang".into(), Value::from(lang.to_string()));
}
CFRelease(source);
}
Value::Object(info)
}
/// `getKeyMap()`: per DOM code, the four characters and whether each is a dead key; `{}` when the input source
/// has no Unicode layout data.
pub fn current_raw_mapping() -> Value {
let mut mapping = Map::new();
let _tis = TIS.lock().unwrap();
// SAFETY: as above; `layout` points into the layout data, which `source` keeps alive until its release below.
unsafe {
let mut source = TISCopyCurrentKeyboardInputSource();
let mut data = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData);
// Japanese input sources have no layout data; their keyboard layout source has (native-keymap does the same).
if data.is_null() {
CFRelease(source);
source = TISCopyCurrentKeyboardLayoutInputSource();
data = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData);
}
if !data.is_null() {
let layout = CFDataGetBytePtr(data) as *const c_void;
for (code, key_code) in MAC_KEY_CODES {
let mut entry = Map::new();
for (name, modifiers) in [("value", 0), ("withShift", SHIFT), ("withAltGr", OPTION), ("withShiftAltGr", SHIFT | OPTION)] {
let (is_dead_key, text) = key_code_to_text(layout, key_code, modifiers);
entry.insert(name.into(), Value::from(text));
entry.insert(format!("{name}IsDeadKey"), Value::from(is_dead_key));
}
mapping.insert(code.into(), Value::Object(entry));
}
}
CFRelease(source);
}
Value::Object(mapping)
}
/// `ConvertKeyCodeToText`: a dead key gives the character of pressing it twice. native-keymap passes
/// `kUCKeyTranslateNoDeadKeysBit` (0) as the options, so dead keys are processed.
unsafe fn key_code_to_text(layout: *const c_void, key_code: u16, modifiers: u32) -> (bool, String) {
// SAFETY: LMGetKbdLast reads a system global and takes no arguments.
let keyboard_type = unsafe { LMGetKbdLast() } as u32;
let mut dead_key_state = 0;
let mut length = 0;
let mut unit = 0u16;
// SAFETY: `layout` is the caller's UCKeyboardLayout; the out pointers are locals, and `unit` holds the 1 unit asked for.
let mut status = unsafe { UCKeyTranslate(layout, key_code, 0, modifiers, keyboard_type, 0, &mut dead_key_state, 1, &mut length, &mut unit) };
let mut is_dead_key = false;
if status == 0 && length == 0 && dead_key_state != 0 {
is_dead_key = true;
// SAFETY: as the call above.
status = unsafe { UCKeyTranslate(layout, key_code, 0, modifiers, keyboard_type, 0, &mut dead_key_state, 1, &mut length, &mut unit) };
}
match char::from_u32(unit as u32) {
Some(character) if status == 0 && length == 1 && !is_control(character) => (is_dead_key, character.to_string()),
_ => (false, String::new()),
}
}
/// The key down AppKit is dispatching (`NSApp.currentEvent`), which GPUI's `Keystroke` reports without its key
/// code; none for a synthesized keystroke.
pub fn current_key_event() -> Option<KeyEvent> {
use objc2_app_kit::{NSApplication, NSEventModifierFlags, NSEventType};
let mtm = objc2::MainThreadMarker::new()?;
let event = NSApplication::sharedApplication(mtm).currentEvent()?;
if event.r#type() != NSEventType::KeyDown {
return None;
}
let key_code = event.keyCode();
let code = MAC_KEY_CODES.iter().find(|(_, code)| *code == key_code)?.0;
let flags = event.modifierFlags();
Some(KeyEvent {
code,
ctrl: flags.contains(NSEventModifierFlags::Control),
shift: flags.contains(NSEventModifierFlags::Shift),
alt: flags.contains(NSEventModifierFlags::Option),
meta: flags.contains(NSEventModifierFlags::Command),
})
}