Visual Studio Code, rebuilt in Rust
Rust
//! Electron's globalShortcut on macOS: Carbon hot keys on the application event target.
use std::collections::HashMap;
use std::ffi::c_void;
use futures::channel::mpsc::UnboundedSender;
use super::{Candidate, ShortcutRegistry};
use crate::keybindings;
/// Carbon's `controlKey`, `shiftKey`, `optionKey` and `cmdKey`.
const CONTROL_KEY: u32 = 1 << 12;
const SHIFT_KEY: u32 = 1 << 9;
const OPTION_KEY: u32 = 1 << 11;
const CMD_KEY: u32 = 1 << 8;
/// Four-char codes: `kEventClassKeyboard` 'keyb', `kEventParamDirectObject` '----', `typeEventHotKeyID` 'hkid'.
const EVENT_CLASS_KEYBOARD: u32 = u32::from_be_bytes(*b"keyb");
const EVENT_HOT_KEY_PRESSED: u32 = 5;
const EVENT_PARAM_DIRECT_OBJECT: u32 = u32::from_be_bytes(*b"----");
const TYPE_EVENT_HOT_KEY_ID: u32 = u32::from_be_bytes(*b"hkid");
const SIGNATURE: u32 = u32::from_be_bytes(*b"vscd");
#[repr(C)]
#[derive(Default)]
struct EventHotKeyId {
signature: u32,
id: u32,
}
#[repr(C)]
struct EventTypeSpec {
event_class: u32,
event_kind: u32,
}
#[link(name = "Carbon", kind = "framework")]
unsafe extern "C" {
fn GetApplicationEventTarget() -> *mut c_void;
fn InstallEventHandler(target: *mut c_void, handler: extern "C" fn(*mut c_void, *mut c_void, *mut c_void) -> i32, count: usize, types: *const EventTypeSpec, user_data: *mut c_void, handler_ref: *mut *mut c_void) -> i32;
fn RegisterEventHotKey(key_code: u32, modifiers: u32, id: EventHotKeyId, target: *mut c_void, options: u32, hot_key: *mut *mut c_void) -> i32;
fn UnregisterEventHotKey(hot_key: *mut c_void) -> i32;
fn GetEventParameter(event: *mut c_void, name: u32, desired_type: u32, actual_type: *mut u32, size: usize, actual_size: *mut usize, data: *mut c_void) -> i32;
}
/// The hot keys registered with Carbon; a press sends its id to the receiver `HotKeys::new` was given.
pub struct HotKeys {
hot_keys: HashMap<String, (u32, *mut c_void)>,
next_id: u32,
}
impl HotKeys {
/// Installs the application's hot key handler; call it once, the handler lives as long as the process.
pub fn new(presses: UnboundedSender<u32>) -> HotKeys {
let spec = EventTypeSpec { event_class: EVENT_CLASS_KEYBOARD, event_kind: EVENT_HOT_KEY_PRESSED };
let presses = Box::into_raw(Box::new(presses)) as *mut c_void;
// SAFETY: `spec` is read during the call; `presses` is leaked, so the handler can read it for the life of the app.
let status = unsafe { InstallEventHandler(GetApplicationEventTarget(), hot_key_pressed, 1, &spec, presses, std::ptr::null_mut()) };
assert_eq!(status, 0, "InstallEventHandler");
HotKeys { hot_keys: HashMap::new(), next_id: 1 }
}
pub fn accelerator(&self, id: u32) -> Option<&str> {
self.hot_keys.iter().find(|(_, (hot_key_id, _))| *hot_key_id == id).map(|(accelerator, _)| accelerator.as_str())
}
}
impl ShortcutRegistry for HotKeys {
fn register(&mut self, binding: &Candidate) -> bool {
let chord = &binding.chord;
// Electron maps the accelerator's key to the virtual key code of its US position.
let Some(key_code) = keybindings::us_scan_code(chord.key).and_then(crate::keyboard_layout::mac_key_code) else { return false };
let modifiers = [(chord.ctrl, CONTROL_KEY), (chord.shift, SHIFT_KEY), (chord.alt, OPTION_KEY), (chord.meta, CMD_KEY)];
let modifiers = modifiers.iter().filter(|(pressed, _)| *pressed).fold(0, |all, (_, modifier)| all | modifier);
let id = self.next_id;
self.next_id += 1;
let mut hot_key = std::ptr::null_mut();
// SAFETY: `hot_key` is a local the call fills; the other arguments are values.
let status = unsafe { RegisterEventHotKey(key_code as u32, modifiers, EventHotKeyId { signature: SIGNATURE, id }, GetApplicationEventTarget(), 0, &mut hot_key) };
if status != 0 {
return false;
}
self.hot_keys.insert(binding.accelerator.clone(), (id, hot_key));
true
}
fn unregister(&mut self, accelerator: &str) {
if let Some((_, hot_key)) = self.hot_keys.remove(accelerator) {
// SAFETY: `hot_key` came from RegisterEventHotKey and leaves the map here, so it is unregistered once.
unsafe { UnregisterEventHotKey(hot_key) };
}
}
}
extern "C" fn hot_key_pressed(_call: *mut c_void, event: *mut c_void, presses: *mut c_void) -> i32 {
let mut id = EventHotKeyId::default();
// SAFETY: Carbon passes a valid event; `id` is a local of the size given.
let status = unsafe { GetEventParameter(event, EVENT_PARAM_DIRECT_OBJECT, TYPE_EVENT_HOT_KEY_ID, std::ptr::null_mut(), size_of::<EventHotKeyId>(), std::ptr::null_mut(), &mut id as *mut EventHotKeyId as *mut c_void) };
if status == 0 && id.signature == SIGNATURE {
// SAFETY: `presses` is the sender HotKeys::new leaked.
let presses = unsafe { &*(presses as *const UnboundedSender<u32>) };
let _ = presses.unbounded_send(id.id);
}
status
}