From 6bfadfac0ad5b08d8278971ffd361ce10925ca6f Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sun, 31 Jan 2021 17:06:30 -0800 Subject: [PATCH] macos: handle dead keys without IME Dead key processing respects the `send_composed_key_when_left_alt_is_pressed` and `send_composed_key_when_right_alt_is_pressed` options. See doc changes included in this commit for more info. refs: https://github.com/wez/wezterm/issues/410 --- docs/changelog.md | 1 + docs/config/keys.md | 10 ++ wezterm-gui/src/window_config.rs | 8 ++ window/build.rs | 60 ++++----- window/src/configuration.rs | 10 ++ window/src/os/macos/window.rs | 206 ++++++++++++++++++++++++++++++- 6 files changed, 263 insertions(+), 32 deletions(-) diff --git a/docs/changelog.md b/docs/changelog.md index 5c6fa5b4e..e2158870b 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -56,6 +56,7 @@ brief notes about them may accumulate here. * macOS: Windows now have drop-shadows when they are opaque. These were disabled due transparency support was added. Thanks to [Rice](https://github.com/fanzeyi)! [#445](https://github.com/wez/wezterm/pull/445) * Unix: adjust font-config patterns to also match "dual spacing" fonts such as [Iosevka Term](https://typeof.net/Iosevka/). Thanks to [Leiser](https://github.com/leiserfg)! [#446](https://github.com/wez/wezterm/pull/446) * New: Added [alternate_buffer_wheel_scroll_speed](config/lua/config/alternate_buffer_wheel_scroll_speed.md) option to control how many cursor key presses are generated by the mouse wheel when the alternate screen is active. The new default for this is a faster-than-previous-releases 3 lines per wheel tick. [#432](https://github.com/wez/wezterm/issues/432) +* macOS: Dead Keys are now processed even when `use_ime=false`. [More details in the docs](config/keys.md#macos-left-and-right-option-key). [#410](https://github.com/wez/wezterm/issues/410). ### 20201101-103216-403d002d diff --git a/docs/config/keys.md b/docs/config/keys.md index ea379b5d0..d5043884b 100644 --- a/docs/config/keys.md +++ b/docs/config/keys.md @@ -48,6 +48,16 @@ both left and right `Option` keys behave identically and composition behavior was influenced for both of them via the `send_composed_key_when_alt_is_pressed` configuration option. +*since: nightly* + +WezTerm is now able to perform dead-key expansion when `use_ime = false`. Dead +keys are treated as composition effects, so with the default settings of +`send_composed_key_when_left_alt_is_pressed` and +`send_composed_key_when_right_alt_is_pressed` above, in a US layout, `Left-Opt +n` will produce `Alt N` and `Right-Opt n` will will for a subsequent key press +before generating an event; `Right-Opt n SPACE` will `~` whereas `Right-Opt n +n` will emit `ñ`. + ### macOS and the Input Method Editor (IME) WezTerm has support for using the operating system Input Method Editor (IME) on diff --git a/wezterm-gui/src/window_config.rs b/wezterm-gui/src/window_config.rs index 58f287665..40453c1d6 100644 --- a/wezterm-gui/src/window_config.rs +++ b/wezterm-gui/src/window_config.rs @@ -12,6 +12,14 @@ impl WindowConfiguration for ConfigBridge { configuration().use_dead_keys } + fn send_composed_key_when_left_alt_is_pressed(&self) -> bool { + configuration().send_composed_key_when_left_alt_is_pressed + } + + fn send_composed_key_when_right_alt_is_pressed(&self) -> bool { + configuration().send_composed_key_when_right_alt_is_pressed + } + fn enable_wayland(&self) -> bool { configuration().enable_wayland } diff --git a/window/build.rs b/window/build.rs index 0a14509e3..ed754edba 100644 --- a/window/build.rs +++ b/window/build.rs @@ -8,36 +8,38 @@ fn main() { let dest = PathBuf::from(&env::var("OUT_DIR").unwrap()); let target = env::var("TARGET").unwrap(); - if !target.contains("macos") { - let mut file = File::create(&dest.join("egl_bindings.rs")).unwrap(); - let reg = Registry::new( - Api::Egl, - (1, 5), - Profile::Core, - Fallbacks::All, - [ - "EGL_KHR_create_context", - "EGL_EXT_create_context_robustness", - "EGL_KHR_create_context_no_error", - "EGL_KHR_platform_x11", - "EGL_KHR_platform_android", - "EGL_KHR_platform_wayland", - "EGL_KHR_platform_gbm", - "EGL_EXT_platform_base", - "EGL_EXT_platform_x11", - "EGL_MESA_platform_gbm", - "EGL_EXT_platform_wayland", - "EGL_EXT_platform_device", - "EGL_KHR_swap_buffers_with_damage", - ], - ); + let mut file = File::create(&dest.join("egl_bindings.rs")).unwrap(); + let reg = Registry::new( + Api::Egl, + (1, 5), + Profile::Core, + Fallbacks::All, + [ + "EGL_KHR_create_context", + "EGL_EXT_create_context_robustness", + "EGL_KHR_create_context_no_error", + "EGL_KHR_platform_x11", + "EGL_KHR_platform_android", + "EGL_KHR_platform_wayland", + "EGL_KHR_platform_gbm", + "EGL_EXT_platform_base", + "EGL_EXT_platform_x11", + "EGL_MESA_platform_gbm", + "EGL_EXT_platform_wayland", + "EGL_EXT_platform_device", + "EGL_KHR_swap_buffers_with_damage", + ], + ); - if target.contains("android") || target.contains("ios") { - reg.write_bindings(gl_generator::StaticStructGenerator, &mut file) - } else { - reg.write_bindings(gl_generator::StructGenerator, &mut file) - } - .unwrap() + if target.contains("android") || target.contains("ios") { + reg.write_bindings(gl_generator::StaticStructGenerator, &mut file) + } else { + reg.write_bindings(gl_generator::StructGenerator, &mut file) + } + .unwrap(); + + if target.contains("apple") { + println!("cargo:rustc-link-lib=framework=Carbon"); } if target.contains("windows") { diff --git a/window/src/configuration.rs b/window/src/configuration.rs index 18858b606..42cf47eb8 100644 --- a/window/src/configuration.rs +++ b/window/src/configuration.rs @@ -5,6 +5,16 @@ pub trait WindowConfiguration { false } + fn send_composed_key_when_left_alt_is_pressed(&self) -> bool { + false + } + + fn send_composed_key_when_right_alt_is_pressed(&self) -> bool { + true + } + + // Applies to Windows only. + // For macos, see send_composed_key_when_XXX_alt_is_pressed fn use_dead_keys(&self) -> bool { true } diff --git a/window/src/os/macos/window.rs b/window/src/os/macos/window.rs index 4438ac011..bde9447c6 100644 --- a/window/src/os/macos/window.rs +++ b/window/src/os/macos/window.rs @@ -18,9 +18,11 @@ use cocoa::appkit::{ use cocoa::base::*; use cocoa::foundation::NSAutoreleasePool; use cocoa::foundation::{NSArray, NSNotFound, NSPoint, NSRect, NSSize, NSUInteger}; -use core_foundation::base::TCFType; +use core_foundation::base::{CFTypeID, TCFType}; use core_foundation::bundle::{CFBundleGetBundleWithIdentifier, CFBundleGetFunctionPointerForName}; -use core_foundation::string::CFString; +use core_foundation::data::{CFData, CFDataGetBytePtr, CFDataRef}; +use core_foundation::string::{CFString, CFStringRef, UniChar}; +use core_foundation::{declare_TCFType, impl_TCFType}; use objc::declare::ClassDecl; use objc::rc::{StrongPtr, WeakPtr}; use objc::runtime::{Class, Object, Protocol, Sel}; @@ -380,6 +382,7 @@ impl Window { vscroll_remainder: 0., last_wheel: Instant::now(), key_is_down: None, + dead_pending: None, fullscreen: None, })); @@ -847,11 +850,66 @@ struct Inner { /// procesing key-up events. key_is_down: Option, + /// First in a dead-key sequence + dead_pending: Option<(u16, u32)>, + /// When using simple fullscreen mode, this tracks /// the window dimensions that need to be restored fullscreen: Option, } +#[repr(C)] +pub struct __InputSource { + _dummy: i32, +} +pub type InputSourceRef = *const __InputSource; + +declare_TCFType!(InputSource, InputSourceRef); +impl_TCFType!(InputSource, InputSourceRef, TISInputSourceGetTypeID); + +#[repr(C)] +struct UCKeyboardLayout { + _dummy: i32, +} + +type UniCharCount = std::os::raw::c_ulong; + +/// key is going down +#[allow(non_upper_case_globals)] +const kUCKeyActionDown: u16 = 0; +/// key is going up +#[allow(non_upper_case_globals, dead_code)] +const kUCKeyActionUp: u16 = 1; +/// auto-key down +#[allow(non_upper_case_globals, dead_code)] +const kUCKeyActionAutoKey: u16 = 2; +/// get information for key display (as in Key Caps) +#[allow(non_upper_case_globals)] +const kUCKeyActionDisplay: u16 = 3; + +extern "C" { + fn TISInputSourceGetTypeID() -> CFTypeID; + fn TISCopyCurrentKeyboardInputSource() -> InputSourceRef; + fn TISGetInputSourceProperty(source: InputSourceRef, propertyKey: CFStringRef) -> CFDataRef; + + static kTISPropertyUnicodeKeyLayoutData: CFStringRef; + + fn UCKeyTranslate( + layout: *const UCKeyboardLayout, + virtualKeyCode: u16, + keyAction: u16, + modifierKeyState: u32, + keyboardType: u32, + keyTranslateOptions: u32, + deadKeyState: *mut u32, + maxStringLength: UniCharCount, + actualStringLength: *mut UniCharCount, + unicodeString: *mut UniChar, + ) -> u32; + + fn LMGetKbdType() -> u8; +} + impl Inner { fn enable_opengl(&mut self) -> anyhow::Result<()> { let window = Window(self.window_id); @@ -863,6 +921,116 @@ impl Inner { self.callbacks.created(&window, glium_context.context) } + + /// + /// + /// + /// + fn translate_key_event( + &mut self, + virtual_key_code: u16, + modifier_flags: NSEventModifierFlags, + ) -> Option> { + let kbd = + unsafe { InputSource::wrap_under_create_rule(TISCopyCurrentKeyboardInputSource()) }; + + let layout_data = unsafe { + CFData::wrap_under_get_rule(TISGetInputSourceProperty( + kbd.as_concrete_TypeRef(), + kTISPropertyUnicodeKeyLayoutData, + )) + }; + + let layout_data = unsafe { + CFDataGetBytePtr(layout_data.as_concrete_TypeRef()) as *const UCKeyboardLayout + }; + + let modifier_key_state: u32 = (modifier_flags.bits() >> 16) as u32 & 0xFF; + + let kbd_type = unsafe { LMGetKbdType() } as _; + + let mut unicode_buffer = [0u16; 8]; + let mut length = 0; + + let mut dead_state = 0; + + let mods = key_modifiers(modifier_flags); + + let use_dead_keys = if mods.contains(Modifiers::LEFT_ALT) { + config().send_composed_key_when_left_alt_is_pressed() + } else if mods.contains(Modifiers::RIGHT_ALT) { + config().send_composed_key_when_right_alt_is_pressed() + } else { + true + }; + + if let Some((code, flags)) = self.dead_pending.take() { + unsafe { + UCKeyTranslate( + layout_data, + code, + kUCKeyActionDown, + flags, + kbd_type, + 0, + &mut dead_state, + unicode_buffer.len() as _, + &mut length, + unicode_buffer.as_mut_ptr(), + ); + } + } else if use_dead_keys { + self.dead_pending + .replace((virtual_key_code, modifier_key_state)); + return None; + } + length = 0; + unsafe { + UCKeyTranslate( + layout_data, + virtual_key_code, + kUCKeyActionDisplay, + /* + if key_is_down { + kUCKeyActionDown + } else { + kUCKeyActionUp + }, + */ + modifier_key_state, + kbd_type, + 0, + &mut dead_state, + unicode_buffer.len() as _, + &mut length, + unicode_buffer.as_mut_ptr(), + ); + }; + + if !use_dead_keys { + length = 0; + // Ignore dead key sequences; synthesize a SPACE press to + // elicit the underlying key code + unsafe { + UCKeyTranslate( + layout_data, + super::keycodes::kVK_Space, + kUCKeyActionDown, + 0, + kbd_type, + 0, + &mut dead_state, + unicode_buffer.len() as _, + &mut length, + unicode_buffer.as_mut_ptr(), + ); + } + } + + Some(String::from_utf16(unsafe { + std::slice::from_raw_parts(unicode_buffer.as_mut_ptr(), length as _) + })) + } } const VIEW_CLS_NAME: &str = "WezTermWindowView"; @@ -1330,8 +1498,10 @@ impl WindowView { // let is_a_repeat = unsafe { nsevent.isARepeat() == YES }; let chars = unsafe { nsstring_to_str(nsevent.characters()) }; let unmod = unsafe { nsstring_to_str(nsevent.charactersIgnoringModifiers()) }; - let modifiers = unsafe { key_modifiers(nsevent.modifierFlags()) }; + let modifier_flags = unsafe { nsevent.modifierFlags() }; + let modifiers = key_modifiers(modifier_flags); let virtual_key = unsafe { nsevent.keyCode() }; + let translated; log::debug!( "key_common: chars=`{}` unmod=`{}` modifiers=`{:?}` virtual_key={:?} key_is_down:{}", @@ -1342,6 +1512,36 @@ impl WindowView { key_is_down ); + let chars = if let Some(myself) = Self::get_this(this) { + let mut inner = myself.inner.borrow_mut(); + + if chars.is_empty() || inner.dead_pending.is_some() { + // Dead key! + if !key_is_down { + return; + } + + match inner.translate_key_event(virtual_key, modifier_flags) { + None => { + // Next key press in dead key sequence is pending. + return; + } + Some(Ok(s)) => { + translated = s; + &translated + } + Some(Err(e)) => { + log::error!("Failed to translate dead key: {}", e); + return; + } + } + } else { + chars + } + } else { + return; + }; + let use_ime = config().use_ime(); // `Delete` on macos is really Backspace and emits BS.