hex/src/keyboard.rs
Luke Parker 8efd9909bd
feat: Windows beta with streaming dictation, Hold/Toggle shortcut mode, and x64 + ARM64 release (#141)
* feat: Windows beta with streaming dictation, Hold/Toggle shortcut mode, and release pipeline

Ports the windows-shell branch onto main, adds a GPU streaming finish for Parakeet Unified English with a whole-clip fallback, a cross-platform Hold/Toggle shortcut mode, x64 and ARM64 Windows CI and release feeds, and the website Windows download.

* copy: Enabled/Disabled status on Linux and in the shared Activity labels

* ci: install SPIRV-Headers for the x64 Vulkan build and gate the Windows-only device query

* refactor: one implementation per concept across macOS, Linux, and Windows

The Windows port carried its own copies of modules main already has. Each
concept now has one implementation:

- UI: Windows uses main's design system (design_tokens, desktop_ui,
  text_input, desktop_transcription_picker types) instead of a Fluent copy.
  Windows-only bits are small cfg additions: Segoe Fluent Icons for Icon,
  Windows text-editing key bindings, fixed-height and read-only text inputs,
  and the shared slider_track component. windows_ui keeps the window chrome
  and the anchored dropdowns, now drawn with menu/menu_item.
- Windows chrome: the sidebar runs the full window height as on macOS. The
  caption row is split: the brand sits over the sidebar, the window buttons
  over the content, and both halves stay OS drag regions.
- Commands: Windows uses main's commands, command_grammar, context, keys,
  and personal_commands. The SDK provisioner accepts the embedded TypeScript
  src layout; Windows execute() opens URLs and paths with ShellExecuteW.
- OpenCode: dictation_processor is the one client and ordered policy
  (corrections, rewrite, transformations) on macOS and Windows. Windows keeps
  its opencode2 api CLI transport in a cfg'd submodule; the ranked catalog,
  prompts, Voice Action generation, and the transformation stage are shared.
- desktop_activity is shared; the Windows Settings contract is
  windows_desktop_host, without #[path] aliases.
- self_update is the signed-feed core for both the Linux and Windows
  updaters.
- Windows copy follows the design system: sentence case and "Hex".

* chore(windows): flat app icon that stays crisp at taskbar sizes

* chore: mark the Windows-only screens to consolidate with app_window after #138

* fix(linux): wait for partial X11 grabs to be released before reporting a conflict
2026-10-19 11:00:46 +10:00

467 lines
16 KiB
Rust
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

use std::collections::HashMap;
use std::ffi::c_void;
use std::sync::{Mutex, OnceLock};
use color_eyre::eyre::{Result, eyre};
pub use crate::keys::{Key, Modifiers};
type InputSourceRef = *const c_void;
type EventRef = *mut c_void;
const KEY_ACTION_DISPLAY: u16 = 3;
const NO_DEAD_KEYS: isize = 0;
const NO_MODIFIER_STATE: u32 = 0;
/// Carbon `cmdKey >> 8`, the UCKeyTranslate modifier state for the Command layer.
const COMMAND_MODIFIER_STATE: u32 = 1;
const HID_EVENT_TAP: u32 = 0;
const COMMAND_KEY_CODE: u16 = 55;
const COMMAND_FLAG: u64 = 1 << 20;
const SHIFT_KEY_CODE: u16 = 56;
const SHIFT_FLAG: u64 = 1 << 17;
const OPTION_KEY_CODE: u16 = 58;
const OPTION_FLAG: u64 = 1 << 19;
const CONTROL_KEY_CODE: u16 = 59;
const CONTROL_FLAG: u64 = 1 << 18;
const EVENT_SOURCE_USER_DATA: u32 = 42;
pub const SYNTHETIC_EVENT_MARKER: i64 = 0x0056_4f49_4345;
static KEY_CODES: OnceLock<LayoutCodes> = OnceLock::new();
static LAYOUT_ACCESS: Mutex<()> = Mutex::new(());
#[cfg(test)]
pub(crate) static INPUT_SOURCE_QUERIES: std::sync::atomic::AtomicUsize =
std::sync::atomic::AtomicUsize::new(0);
#[link(name = "Carbon", kind = "framework")]
unsafe extern "C" {
fn TISCopyCurrentKeyboardLayoutInputSource() -> InputSourceRef;
fn TISCopyCurrentASCIICapableKeyboardLayoutInputSource() -> InputSourceRef;
static kTISPropertyUnicodeKeyLayoutData: *const c_void;
fn TISGetInputSourceProperty(
input_source: InputSourceRef,
property_key: *const c_void,
) -> *const c_void;
fn UCKeyTranslate(
layout: *const u8,
key_code: u16,
key_action: u16,
modifier_state: u32,
keyboard_type: u32,
options: isize,
dead_key_state: *mut u32,
max_length: isize,
actual_length: *mut isize,
output: *mut u16,
) -> i32;
fn LMGetKbdType() -> u8;
}
#[link(name = "CoreFoundation", kind = "framework")]
unsafe extern "C" {
fn CFDataGetBytePtr(data: *const c_void) -> *const u8;
fn CFRelease(value: *const c_void);
}
#[link(name = "ApplicationServices", kind = "framework")]
unsafe extern "C" {
fn CGEventCreateKeyboardEvent(source: *mut c_void, key: u16, down: bool) -> EventRef;
fn CGEventSetFlags(event: EventRef, flags: u64);
fn CGEventKeyboardSetUnicodeString(event: EventRef, length: usize, text: *const u16);
fn CGEventSetIntegerValueField(event: EventRef, field: u32, value: i64);
fn CGEventPost(tap: u32, event: EventRef);
}
/// Character key codes for the active layout's plain and Command layers.
/// Layouts such as "Dvorak – QWERTY ⌘" switch to a different arrangement while
/// Command is held, so Command shortcuts must resolve against that layer.
struct LayoutCodes {
plain: HashMap<char, u16>,
command: HashMap<char, u16>,
}
impl LayoutCodes {
fn key_code(&self, character: char, command: bool) -> Option<u16> {
let character = character.to_ascii_lowercase();
command
.then(|| self.command.get(&character))
.flatten()
.or_else(|| self.plain.get(&character))
.copied()
}
}
/// The key that produces `character` on the active layout's plain layer.
pub fn key_code_for(character: char) -> Result<u16> {
resolve_key_code(character, false)
}
fn resolve_key_code(character: char, command: bool) -> Result<u16> {
let cached = || {
KEY_CODES.get().map(|codes| {
codes
.key_code(character, command)
.ok_or_else(|| eyre!("current keyboard layout has no key for {character:?}"))
})
};
if let Some(result) = cached() {
return result;
}
// Headless callers retain live-layout resolution. GUI callers must prewarm
// on the main thread; even a cache miss then returns without entering TIS.
let _access = LAYOUT_ACCESS
.lock()
.unwrap_or_else(|error| error.into_inner());
if let Some(result) = cached() {
return result;
}
let source = LayoutSource::current()?;
let layout = source.layout_bytes()?;
let mut target = [0; 4];
let target = character.encode_utf8(&mut target);
let find = |modifier_state| {
(0..128).find(|&key_code| {
translate(layout, key_code, modifier_state)
.is_some_and(|translated| translated.eq_ignore_ascii_case(target))
})
};
let result = command
.then(|| find(COMMAND_MODIFIER_STATE))
.flatten()
.or_else(|| find(NO_MODIFIER_STATE));
drop(source);
// Non-Latin layouts produce no ASCII letters with an empty modifier state;
// resolve those against the ASCII-capable layout like AppKit does.
result
.or_else(|| ascii_capable_key_code(character))
.ok_or_else(|| eyre!("current keyboard layout has no key for {character:?}"))
}
/// GUI startup must build this snapshot on the main thread before starting workers.
/// Later lookups, including misses, never re-enter TIS/TSM from a worker thread.
pub fn initialize_layout() -> Result<()> {
if KEY_CODES.get().is_some() {
return Ok(());
}
let _access = LAYOUT_ACCESS
.lock()
.unwrap_or_else(|error| error.into_inner());
if KEY_CODES.get().is_some() {
return Ok(());
}
let source = LayoutSource::current()?;
let mut codes = collect_layout_codes(&source, NO_MODIFIER_STATE)?;
let command = collect_layout_codes(&source, COMMAND_MODIFIER_STATE).unwrap_or_default();
drop(source);
// Non-Latin layouts (Russian, Hebrew, …) produce no ASCII letters with an
// empty modifier state, so shortcuts like Cmd+V would miss. Appkit resolves
// those against the ASCII-capable layout; mirror that here by filling the
// missing letters from the ASCII-capable input source.
if ('a'..='z').any(|character| !codes.contains_key(&character))
&& let Some(ascii_codes) = ascii_capable_key_codes()
{
fill_missing_ascii_letters(&mut codes, ascii_codes);
}
let _ = KEY_CODES.set(LayoutCodes {
plain: codes,
command,
});
Ok(())
}
fn ascii_capable_key_codes() -> Option<HashMap<char, u16>> {
// Called only while LAYOUT_ACCESS is held, before the GUI snapshot is published.
collect_layout_codes(&LayoutSource::ascii_capable()?, NO_MODIFIER_STATE).ok()
}
fn fill_missing_ascii_letters(codes: &mut HashMap<char, u16>, fallback: HashMap<char, u16>) {
for (character, key_code) in fallback {
if character.is_ascii_alphabetic() {
codes.entry(character).or_insert(key_code);
}
}
}
/// Resolves a character against the ASCII-capable layout for non-Latin
/// active layouts, mirroring how AppKit resolves shortcuts such as Cmd+V.
fn ascii_capable_key_code(character: char) -> Option<u16> {
if !character.is_ascii_alphabetic() {
return None;
}
ascii_capable_key_codes()?
.get(&character.to_ascii_lowercase())
.copied()
}
fn collect_layout_codes(source: &LayoutSource, modifier_state: u32) -> Result<HashMap<char, u16>> {
let layout = source.layout_bytes()?;
Ok(collect_key_codes((0..128).filter_map(|key_code| {
let translated = translate(layout, key_code, modifier_state)?;
let character = translated.chars().next()?.to_ascii_lowercase();
Some((character, key_code))
})))
}
fn collect_key_codes(entries: impl IntoIterator<Item = (char, u16)>) -> HashMap<char, u16> {
entries
.into_iter()
.fold(HashMap::new(), |mut codes, (character, key_code)| {
codes.entry(character).or_insert(key_code);
codes
})
}
pub fn post_command(character: char) -> Result<()> {
post_shortcut(Key::Character(character), Modifiers::COMMAND)
}
pub fn post_enter() -> Result<()> {
post_shortcut(Key::Enter, Modifiers::NONE)
}
pub fn type_text(text: &str) -> Result<()> {
for character in text.chars() {
let mut encoded = [0; 2];
let encoded = character.encode_utf16(&mut encoded);
let down = KeyboardEvent::new((0, true, 0))?;
let up = KeyboardEvent::new((0, false, 0))?;
down.set_unicode(encoded);
up.set_unicode(encoded);
down.post();
up.post();
}
Ok(())
}
pub fn post_shortcut(key: Key, modifiers: Modifiers) -> Result<()> {
post_repeated_shortcut(key, modifiers, 1)
}
pub fn post_repeated_shortcut(key: Key, modifiers: Modifiers, count: u8) -> Result<()> {
if count == 0 {
return Ok(());
}
let key_code = match key {
Key::Character(character) => {
resolve_key_code(character, modifiers.contains(Modifiers::COMMAND))?
}
Key::Home => 115,
Key::End => 119,
Key::Up => 126,
Key::Down => 125,
Key::Left => 123,
Key::Right => 124,
Key::Enter => 36,
Key::Escape => 53,
};
let modifiers = [
(Modifiers::COMMAND, COMMAND_FLAG, COMMAND_KEY_CODE),
(Modifiers::SHIFT, SHIFT_FLAG, SHIFT_KEY_CODE),
(Modifiers::OPTION, OPTION_FLAG, OPTION_KEY_CODE),
(Modifiers::CONTROL, CONTROL_FLAG, CONTROL_KEY_CODE),
]
.into_iter()
.filter_map(|(modifier, flag, key)| modifiers.contains(modifier).then_some((flag, key)))
.collect::<Vec<_>>();
post_key_code(key_code, &modifiers, count)
}
fn post_key_code(key_code: u16, modifiers: &[(u64, u16)], count: u8) -> Result<()> {
let specs = shortcut_event_specs(key_code, modifiers, count);
let events = specs.map(KeyboardEvent::new).collect::<Result<Vec<_>>>()?;
for event in events {
event.post();
}
Ok(())
}
fn shortcut_event_specs(
key_code: u16,
modifiers: &[(u64, u16)],
count: u8,
) -> impl Iterator<Item = (u16, bool, u64)> {
let flags = modifiers.iter().fold(0, |flags, (flag, _)| flags | flag);
let mut active_flags = 0;
let mut remaining_flags = flags;
modifiers
.iter()
.map(move |(flag, key)| {
active_flags |= flag;
(*key, true, active_flags)
})
.chain((0..count).flat_map(move |_| [(key_code, true, flags), (key_code, false, flags)]))
.chain(modifiers.iter().rev().map(move |(flag, key)| {
remaining_flags &= !flag;
(*key, false, remaining_flags)
}))
}
struct KeyboardEvent(EventRef);
impl KeyboardEvent {
fn new((key, down, flags): (u16, bool, u64)) -> Result<Self> {
// SAFETY: Null selects the default event source. The owned event is released in Drop.
let event = unsafe { CGEventCreateKeyboardEvent(std::ptr::null_mut(), key, down) };
if event.is_null() {
return Err(eyre!("could not create keyboard event"));
}
unsafe {
CGEventSetFlags(event, flags);
CGEventSetIntegerValueField(event, EVENT_SOURCE_USER_DATA, SYNTHETIC_EVENT_MARKER);
}
Ok(Self(event))
}
fn post(&self) {
// SAFETY: This value owns a valid CoreGraphics keyboard event.
unsafe { CGEventPost(HID_EVENT_TAP, self.0) };
}
fn set_unicode(&self, text: &[u16]) {
// SAFETY: The event is valid and Quartz copies the provided UTF-16 buffer.
unsafe { CGEventKeyboardSetUnicodeString(self.0, text.len(), text.as_ptr()) };
}
}
impl Drop for KeyboardEvent {
fn drop(&mut self) {
// SAFETY: This is the final owner of the retained CoreGraphics event.
unsafe { CFRelease(self.0.cast_const()) };
}
}
/// A retained TIS keyboard-layout input source, released on drop.
struct LayoutSource(InputSourceRef);
impl LayoutSource {
/// The active layout, falling back to the ASCII-capable layout.
fn current() -> Result<Self> {
#[cfg(test)]
INPUT_SOURCE_QUERIES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
// SAFETY: TIS copy functions return retained immutable input-source objects.
let source = unsafe { TISCopyCurrentKeyboardLayoutInputSource() };
if !source.is_null() {
return Ok(Self(source));
}
Self::ascii_capable().ok_or_else(|| eyre!("no keyboard layout input source is available"))
}
fn ascii_capable() -> Option<Self> {
// SAFETY: TIS copy functions return retained immutable input-source objects.
let source = unsafe { TISCopyCurrentASCIICapableKeyboardLayoutInputSource() };
(!source.is_null()).then_some(Self(source))
}
/// The UCKeyboardLayout bytes, valid while this source is alive.
fn layout_bytes(&self) -> Result<*const u8> {
// SAFETY: The retained source remains alive for every property read.
let layout_data =
unsafe { TISGetInputSourceProperty(self.0, kTISPropertyUnicodeKeyLayoutData) };
if layout_data.is_null() {
return Err(eyre!("active keyboard layout has no Unicode mapping"));
}
// SAFETY: The property is CFData containing a UCKeyboardLayout for this source.
Ok(unsafe { CFDataGetBytePtr(layout_data) })
}
}
impl Drop for LayoutSource {
fn drop(&mut self) {
// SAFETY: TIS copy functions return a retained source that we own.
unsafe { CFRelease(self.0) };
}
}
fn translate(layout: *const u8, key_code: u16, modifier_state: u32) -> Option<String> {
let mut dead_key_state = 0;
let mut output = [0_u16; 4];
let mut length = 0;
// SAFETY: `layout` points into retained TIS layout data and output buffers are valid.
let status = unsafe {
UCKeyTranslate(
layout,
key_code,
KEY_ACTION_DISPLAY,
modifier_state,
LMGetKbdType().into(),
NO_DEAD_KEYS,
&mut dead_key_state,
output.len() as isize,
&mut length,
output.as_mut_ptr(),
)
};
(status == 0 && length > 0)
.then(|| String::from_utf16(&output[..length as usize]).ok())
.flatten()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn non_latin_snapshot_gets_shortcut_letters_without_replacing_active_keys() {
let mut codes = collect_key_codes([('ж', 41), ('v', 12)]);
let fallback = collect_key_codes([('v', 9), ('c', 8), ('c', 88), ('1', 18)]);
fill_missing_ascii_letters(&mut codes, fallback);
assert_eq!(codes.get(&'ж'), Some(&41));
assert_eq!(codes.get(&'v'), Some(&12));
assert_eq!(codes.get(&'c'), Some(&8));
assert!(!codes.contains_key(&'1'));
let mut non_latin = collect_key_codes([('מ', 9)]);
fill_missing_ascii_letters(&mut non_latin, collect_key_codes([('v', 9)]));
assert_eq!(non_latin.get(&'v'), Some(&9));
assert_eq!(non_latin.get(&'מ'), Some(&9));
}
#[test]
fn command_shortcuts_resolve_against_the_command_layer() {
// "Dvorak – QWERTY ⌘": V is keycode 47 normally but keycode 9 with Command.
let dvorak_qwerty_command = LayoutCodes {
plain: collect_key_codes([('v', 47), ('.', 9)]),
command: collect_key_codes([('v', 9), ('.', 47)]),
};
assert_eq!(dvorak_qwerty_command.key_code('v', true), Some(9));
assert_eq!(dvorak_qwerty_command.key_code('V', true), Some(9));
assert_eq!(dvorak_qwerty_command.key_code('v', false), Some(47));
let qwerty = LayoutCodes {
plain: collect_key_codes([('v', 9)]),
command: collect_key_codes([('v', 9)]),
};
assert_eq!(qwerty.key_code('v', true), Some(9));
assert_eq!(qwerty.key_code('v', false), Some(9));
// A Command layer without Latin letters falls back to the plain snapshot,
// which non-Latin layouts fill from the ASCII-capable layout.
let non_latin = LayoutCodes {
plain: collect_key_codes([('м', 9), ('v', 9)]),
command: collect_key_codes([('м', 9)]),
};
assert_eq!(non_latin.key_code('v', true), Some(9));
assert_eq!(non_latin.key_code('x', true), None);
}
#[test]
fn layout_cache_prefers_the_first_key_that_produces_a_character() {
let codes = collect_key_codes([('2', 19), ('2', 84)]);
assert_eq!(codes.get(&'2'), Some(&19));
}
#[test]
fn shortcut_modifier_events_track_physical_flag_transitions() {
let events =
shortcut_event_specs(19, &[(CONTROL_FLAG, CONTROL_KEY_CODE)], 1).collect::<Vec<_>>();
assert_eq!(
events,
vec![
(CONTROL_KEY_CODE, true, CONTROL_FLAG),
(19, true, CONTROL_FLAG),
(19, false, CONTROL_FLAG),
(CONTROL_KEY_CODE, false, 0),
]
);
}
}