diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 6c75377..7b1eb7b 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -12,7 +12,7 @@ android:theme="@style/Theme.EzDisplay"> diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt index 57b2fdd..ae9eeb6 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt @@ -6,6 +6,7 @@ import android.graphics.Color import android.graphics.Rect import android.graphics.Typeface import android.content.Intent +import android.content.res.Configuration import android.os.Build import android.os.Bundle import android.os.Handler @@ -16,6 +17,7 @@ import android.util.TypedValue import android.view.Choreographer import android.view.Gravity import android.view.InputDevice +import android.view.KeyEvent import android.view.MotionEvent import android.view.PointerIcon import android.view.SurfaceHolder @@ -85,6 +87,8 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall private var telemetryOn = false private var lastInputNote = "" private var keysHintShown = false + private var hostLacksKeys = false // the host reported input_caps without the KEYS bit + private val keysDown = LinkedHashSet() // hardware key codes currently down on the host private var airHintShown = false private var barrelDown = false private var barrelPressAt = 0L @@ -215,6 +219,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall override fun onWindowFocusChanged(hasFocus: Boolean) { super.onWindowFocusChanged(hasFocus) + if (!hasFocus) releaseAllKeys() if (hasFocus) { hideSystemBars() if (Build.VERSION.SDK_INT >= 31) root.requestUnbufferedDispatch(InputDevice.SOURCE_CLASS_POINTER) @@ -228,6 +233,19 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall } } + override fun onConfigurationChanged(newConfig: Configuration) { + super.onConfigurationChanged(newConfig) + pushKeyboardState(newConfig) + } + + /** Tells the native side (and through it the host) whether a hardware keyboard is attached. */ + private fun pushKeyboardState(config: Configuration = resources.configuration) { + NativeBridge.setKeyboardAttached( + config.keyboard == Configuration.KEYBOARD_QWERTY && + config.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO, + ) + } + override fun onResume() { super.onResume() applyInputConfig() @@ -246,6 +264,11 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall scheduleConnect(0) } + override fun onPause() { + releaseAllKeys() + super.onPause() + } + override fun onStop() { started = false handler.removeCallbacks(connectRunnable) @@ -283,6 +306,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall if (!started || sessionActive) return if (!surfaceReady) return // surfaceCreated reschedules val caps = capsJson ?: Capabilities.toJson(this, chosenMode).also { capsJson = it } + pushKeyboardState() val err = NativeBridge.start(surfaceView.holder.surface, HOST, PORT, caps) if (err != null) { Log.w(TAG, "start failed: $err") @@ -296,6 +320,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall wasStreaming = false lastInputNote = "" keysHintShown = false + hostLacksKeys = false airHintShown = false streamW = 0 streamH = 0 @@ -307,6 +332,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall } private fun stopSession() { + releaseAllKeys() if (sessionActive) { NativeBridge.stop() sessionActive = false @@ -490,6 +516,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall telemetryOn = (flags and 1) != 0 telemetryView.visibility = if (telemetryOn) View.VISIBLE else View.GONE if (telemetryOn) showTelemetry(j) + hostLacksKeys = !j.isNull("input_caps") && (j.optInt("input_caps") and 8) == 0 val note = if (j.isNull("input_note")) "" else j.optString("input_note") if (note != lastInputNote) { lastInputNote = note @@ -575,6 +602,50 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall return super.dispatchGenericMotionEvent(ev) } + override fun dispatchKeyEvent(event: KeyEvent): Boolean { + if (inputActive() && isHardwareKey(event)) { + val code = event.keyCode + val nanos = event.eventTime * 1_000_000L + when (event.action) { + // repeatCount > 0 is an autorepeat: the host treats a press of a key already down as one. + KeyEvent.ACTION_DOWN -> if (NativeBridge.keyEvent(code, true, nanos)) { + keysDown.add(code) + if (hostLacksKeys && !keysHintShown) { + keysHintShown = true + showTransient(getString(R.string.status_keys_unsupported), NOTE_SHOW_MS) + } + return true + } + KeyEvent.ACTION_UP -> if (keysDown.remove(code)) { + NativeBridge.keyEvent(code, false, nanos) + return true + } + } + } + return super.dispatchKeyEvent(event) + } + + /** A key from a physical keyboard that Android does not need for itself. */ + private fun isHardwareKey(event: KeyEvent): Boolean { + if (event.source and InputDevice.SOURCE_KEYBOARD != InputDevice.SOURCE_KEYBOARD) return false + val device = event.device ?: return false + if (device.isVirtual || device.keyboardType != InputDevice.KEYBOARD_TYPE_ALPHABETIC) return false + return when (event.keyCode) { + KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE, + KeyEvent.KEYCODE_POWER, KeyEvent.KEYCODE_HOME, KeyEvent.KEYCODE_APP_SWITCH, + KeyEvent.KEYCODE_BRIGHTNESS_UP, KeyEvent.KEYCODE_BRIGHTNESS_DOWN -> false + else -> true // media keys have no HID usage, so they fall through to Android + } + } + + /** Releases every forwarded key so none stays stuck on the PC. */ + private fun releaseAllKeys() { + if (keysDown.isEmpty()) return + val nanos = SystemClock.uptimeMillis() * 1_000_000L + keysDown.toList().asReversed().forEach { NativeBridge.keyEvent(it, false, nanos) } + keysDown.clear() + } + /** Packs [ev] (with its history) for [NativeBridge.inputEvent]; buffers are reused. */ private fun forward(ev: MotionEvent) { val n = ev.pointerCount diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/NativeBridge.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/NativeBridge.kt index b6112ed..90417ef 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/NativeBridge.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/NativeBridge.kt @@ -51,6 +51,19 @@ object NativeBridge { */ @JvmStatic external fun inputEvent(ints: IntArray, floats: FloatArray, timesNs: LongArray) + /** + * Forwards one hardware key transition. [timeNs] is on the `SystemClock.uptimeMillis` base. + * A press of a key already down is an autorepeat. Returns false when the key code has no HID + * usage (nothing was sent). + */ + @JvmStatic external fun keyEvent(keyCode: Int, pressed: Boolean, timeNs: Long): Boolean + + /** + * Reports whether a hardware keyboard is attached. Kept across sessions: a session started + * later tells the host about the last value. + */ + @JvmStatic external fun setKeyboardAttached(attached: Boolean) + /** Fires the engine timers that are due; call once per frame. */ @JvmStatic external fun inputTick() diff --git a/crates/ezd-android/src/bridge.rs b/crates/ezd-android/src/bridge.rs index c0effb1..ba41b7d 100644 --- a/crates/ezd-android/src/bridge.rs +++ b/crates/ezd-android/src/bridge.rs @@ -5,10 +5,11 @@ use crate::caps::parse_caps; use crate::decoder::SendWindow; use crate::input::{mono_to_now_us, unpack_motion}; +use crate::keys::keycode_to_hid; use crate::session::Session; use ezd_client_core::now_us; use ezd_input::{InputConfig, InputEngine, ViewTransform}; -use ezd_proto::Message; +use ezd_proto::{Key, Message}; use jni::EnvUnowned; use jni::errors::ThrowRuntimeExAndDefault; use jni::objects::{JByteArray, JClass, JFloatArray, JIntArray, JLongArray, JObject, JString}; @@ -17,7 +18,7 @@ use ndk::native_window::NativeWindow; use std::cell::RefCell; use std::sync::Mutex; use std::sync::Once; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; static SESSION: Mutex> = Mutex::new(None); @@ -34,6 +35,8 @@ static INPUT: Mutex = Mutex::new(InputState { config: None, view: (1.0, 1.0), }); +/// Last hardware keyboard state from Kotlin; a new session starts with it. +static KEYBOARD_ATTACHED: AtomicBool = AtomicBool::new(false); static LAST_INPUT_ERR_S: AtomicU64 = AtomicU64::new(0); #[derive(Default)] @@ -145,7 +148,9 @@ pub extern "system" fn start<'local>( old.stop(); } log::info!("start {host}:{port} surface={}", window.is_some()); - *guard = Some(Session::start(window, host, port, caps)); + let s = Session::start(window, host, port, caps); + s.set_keyboard_attached(KEYBOARD_ATTACHED.load(Ordering::Relaxed)); + *guard = Some(s); Ok(JString::null()) }) .resolve::() @@ -324,6 +329,50 @@ pub extern "system" fn input_event<'local>( .resolve::() } +/// `external fun keyEvent(keyCode: Int, pressed: Boolean, timeNs: Long): Boolean`: one hardware +/// key transition (`timeNs` is uptime-based). Returns whether the key code maps to a HID usage +/// and was sent (a press of a key already down is an autorepeat). +#[jni::jni_mangle("com.librestatic.ezdisplay.NativeBridge")] +pub extern "system" fn key_event<'local>( + mut env: EnvUnowned<'local>, + _class: JClass<'local>, + key_code: jint, + pressed: jni::sys::jboolean, + time_ns: jni::sys::jlong, +) -> jni::sys::jboolean { + env.with_env(|_env| -> jni::errors::Result { + let Some(usage) = keycode_to_hid(key_code) else { + return Ok(false); + }; + let mut out = vec![Message::Key(Key { + t_us: mono_to_now_us(time_ns, mono_ns(), now_us()), + usage, + pressed, + })]; + send_all(&mut out); + Ok(true) + }) + .resolve::() +} + +/// `external fun setKeyboardAttached(attached: Boolean)`: whether a hardware keyboard is attached. +/// Stored also while there is no session, so the next `start` reports it to the host. +#[jni::jni_mangle("com.librestatic.ezdisplay.NativeBridge")] +pub extern "system" fn set_keyboard_attached<'local>( + mut env: EnvUnowned<'local>, + _class: JClass<'local>, + attached: jni::sys::jboolean, +) { + env.with_env(|_env| -> jni::errors::Result<()> { + KEYBOARD_ATTACHED.store(attached, Ordering::Relaxed); + if let Some(s) = session().as_ref() { + s.set_keyboard_attached(attached); + } + Ok(()) + }) + .resolve::() +} + /// `external fun inputTick()`: fires due gesture/pen timers. #[jni::jni_mangle("com.librestatic.ezdisplay.NativeBridge")] pub extern "system" fn input_tick<'local>(mut env: EnvUnowned<'local>, _class: JClass<'local>) { diff --git a/crates/ezd-android/src/keys.rs b/crates/ezd-android/src/keys.rs new file mode 100644 index 0000000..2c3f80c --- /dev/null +++ b/crates/ezd-android/src/keys.rs @@ -0,0 +1,183 @@ +//! Android `KeyEvent` key codes to USB HID keyboard-page (0x07) usages. +//! +//! The mapping is by key code (a physical key position); the PC applies its own layout. + +/// The HID usage for an Android key code, `None` for keys we do not forward. +pub fn keycode_to_hid(code: i32) -> Option { + let usage = match code { + // KEYCODE_0..9 -> 1..9 then 0. + 7 => 0x27, + 8..=16 => 0x1E + (code - 8) as u16, + // KEYCODE_DPAD_UP, DOWN, LEFT, RIGHT. + 19 => 0x52, + 20 => 0x51, + 21 => 0x50, + 22 => 0x4F, + // KEYCODE_A..Z. + 29..=54 => 0x04 + (code - 29) as u16, + 55 => 0x36, // COMMA + 56 => 0x37, // PERIOD + 57 => 0xE2, // ALT_LEFT + 58 => 0xE6, // ALT_RIGHT + 59 => 0xE1, // SHIFT_LEFT + 60 => 0xE5, // SHIFT_RIGHT + 61 => 0x2B, // TAB + 62 => 0x2C, // SPACE + 66 => 0x28, // ENTER + 67 => 0x2A, // DEL (backspace) + 68 => 0x35, // GRAVE + 69 => 0x2D, // MINUS + 70 => 0x2E, // EQUALS + 71 => 0x2F, // LEFT_BRACKET + 72 => 0x30, // RIGHT_BRACKET + 73 => 0x31, // BACKSLASH + 74 => 0x33, // SEMICOLON + 75 => 0x34, // APOSTROPHE + 76 => 0x38, // SLASH + 82 => 0x65, // MENU (Application) + 92 => 0x4B, // PAGE_UP + 93 => 0x4E, // PAGE_DOWN + 111 => 0x29, // ESCAPE + 112 => 0x4C, // FORWARD_DEL + 113 => 0xE0, // CTRL_LEFT + 114 => 0xE4, // CTRL_RIGHT + 115 => 0x39, // CAPS_LOCK + 116 => 0x47, // SCROLL_LOCK + 117 => 0xE3, // META_LEFT + 118 => 0xE7, // META_RIGHT + 120 => 0x46, // SYSRQ (Print Screen) + 121 => 0x48, // BREAK (Pause) + 122 => 0x4A, // MOVE_HOME + 123 => 0x4D, // MOVE_END + 124 => 0x49, // INSERT + // KEYCODE_F1..F12. + 131..=142 => 0x3A + (code - 131) as u16, + 143 => 0x53, // NUM_LOCK + // KEYCODE_NUMPAD_0..9: 0 is 0x62, 1..9 are 0x59..0x61. + 144 => 0x62, + 145..=153 => 0x59 + (code - 145) as u16, + 154 => 0x54, // NUMPAD_DIVIDE + 155 => 0x55, // NUMPAD_MULTIPLY + 156 => 0x56, // NUMPAD_SUBTRACT + 157 => 0x57, // NUMPAD_ADD + 158 => 0x63, // NUMPAD_DOT + 159 => 0x85, // NUMPAD_COMMA + 160 => 0x58, // NUMPAD_ENTER + 161 => 0x67, // NUMPAD_EQUALS + _ => return None, + }; + Some(usage) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn letters_and_digits() { + assert_eq!(keycode_to_hid(29), Some(0x04)); // A + assert_eq!(keycode_to_hid(54), Some(0x1D)); // Z + assert_eq!(keycode_to_hid(8), Some(0x1E)); // 1 + assert_eq!(keycode_to_hid(16), Some(0x26)); // 9 + assert_eq!(keycode_to_hid(7), Some(0x27)); // 0 + } + + #[test] + fn editing_and_navigation() { + assert_eq!(keycode_to_hid(66), Some(0x28)); // Enter + assert_eq!(keycode_to_hid(111), Some(0x29)); // Escape + assert_eq!(keycode_to_hid(67), Some(0x2A)); // Backspace + assert_eq!(keycode_to_hid(112), Some(0x4C)); // Delete + assert_eq!(keycode_to_hid(124), Some(0x49)); // Insert + assert_eq!(keycode_to_hid(122), Some(0x4A)); // Home + assert_eq!(keycode_to_hid(123), Some(0x4D)); // End + assert_eq!(keycode_to_hid(92), Some(0x4B)); + assert_eq!(keycode_to_hid(93), Some(0x4E)); + assert_eq!(keycode_to_hid(19), Some(0x52)); // Up + assert_eq!(keycode_to_hid(20), Some(0x51)); // Down + assert_eq!(keycode_to_hid(21), Some(0x50)); // Left + assert_eq!(keycode_to_hid(22), Some(0x4F)); // Right + assert_eq!(keycode_to_hid(82), Some(0x65)); // Menu + } + + #[test] + fn function_and_system_keys() { + assert_eq!(keycode_to_hid(131), Some(0x3A)); // F1 + assert_eq!(keycode_to_hid(142), Some(0x45)); // F12 + assert_eq!(keycode_to_hid(120), Some(0x46)); // Print Screen + assert_eq!(keycode_to_hid(116), Some(0x47)); + assert_eq!(keycode_to_hid(121), Some(0x48)); + assert_eq!(keycode_to_hid(115), Some(0x39)); // Caps Lock + } + + #[test] + fn punctuation() { + let pairs = [ + (69, 0x2D), + (70, 0x2E), + (71, 0x2F), + (72, 0x30), + (73, 0x31), + (74, 0x33), + (75, 0x34), + (68, 0x35), + (55, 0x36), + (56, 0x37), + (76, 0x38), + (61, 0x2B), + (62, 0x2C), + ]; + for (code, usage) in pairs { + assert_eq!(keycode_to_hid(code), Some(usage), "code {code}"); + } + } + + #[test] + fn modifiers() { + let pairs = [ + (113, 0xE0), + (59, 0xE1), + (57, 0xE2), + (117, 0xE3), + (114, 0xE4), + (60, 0xE5), + (58, 0xE6), + (118, 0xE7), + ]; + for (code, usage) in pairs { + assert_eq!(keycode_to_hid(code), Some(usage), "code {code}"); + } + } + + #[test] + fn numpad() { + assert_eq!(keycode_to_hid(143), Some(0x53)); // Num Lock + assert_eq!(keycode_to_hid(144), Some(0x62)); // 0 + assert_eq!(keycode_to_hid(145), Some(0x59)); // 1 + assert_eq!(keycode_to_hid(153), Some(0x61)); // 9 + assert_eq!(keycode_to_hid(154), Some(0x54)); + assert_eq!(keycode_to_hid(155), Some(0x55)); + assert_eq!(keycode_to_hid(156), Some(0x56)); + assert_eq!(keycode_to_hid(157), Some(0x57)); + assert_eq!(keycode_to_hid(158), Some(0x63)); + assert_eq!(keycode_to_hid(160), Some(0x58)); + } + + #[test] + fn unknown_codes_are_none() { + // UNKNOWN, SOFT_LEFT, HOME, BACK, volume up, power, media play, app switch, negative. + for code in [0, 1, 3, 4, 24, 26, 85, 187, -1, 100_000] { + assert_eq!(keycode_to_hid(code), None, "code {code}"); + } + } + + #[test] + fn usages_are_unique() { + let mut seen = std::collections::HashSet::new(); + for code in 0..400 { + if let Some(u) = keycode_to_hid(code) { + assert!(seen.insert(u), "usage {u:#x} mapped twice (code {code})"); + } + } + } +} diff --git a/crates/ezd-android/src/lib.rs b/crates/ezd-android/src/lib.rs index a4b4120..d49ee46 100644 --- a/crates/ezd-android/src/lib.rs +++ b/crates/ezd-android/src/lib.rs @@ -1,6 +1,6 @@ //! ezdisplay Android client native library. //! -//! The portable parts ([`caps`], [`input`], [`tracker`], [`status`]) build and test on the host. The JNI +//! The portable parts ([`caps`], [`input`], [`keys`], [`tracker`], [`status`]) build and test on the host. The JNI //! bridge, session and MediaCodec decoder only exist for `target_os = "android"`. //! //! Kotlin class: `com.librestatic.ezdisplay.NativeBridge` (see `bridge.rs`). @@ -11,6 +11,7 @@ pub mod caps; pub mod color; pub mod input; +pub mod keys; pub mod status; pub mod tracker; diff --git a/crates/ezd-android/src/session.rs b/crates/ezd-android/src/session.rs index 4ae57df..73ae222 100644 --- a/crates/ezd-android/src/session.rs +++ b/crates/ezd-android/src/session.rs @@ -149,6 +149,11 @@ impl Session { self.handle.send_input(msg) } + /// Reports the hardware keyboard state to the host (kept for the whole session). + pub fn set_keyboard_attached(&self, attached: bool) { + self.handle.set_keyboard_attached(attached); + } + /// Latest cursor state. pub fn cursor(&self) -> Option { self.handle.cursor() diff --git a/crates/ezd-client-core/src/handle.rs b/crates/ezd-client-core/src/handle.rs index 565a435..ea869c2 100644 --- a/crates/ezd-client-core/src/handle.rs +++ b/crates/ezd-client-core/src/handle.rs @@ -3,8 +3,8 @@ use crate::percentile; use ezd_link::MuxSender; use ezd_proto::{ - ClientOptions, ClientStats, ClockSync, CursorShape, CursorState, InputStatus, Message, - StreamColor, + ClientKeyboard, ClientOptions, ClientStats, ClockSync, CursorShape, CursorState, InputStatus, + Message, StreamColor, }; use std::collections::HashMap; use std::sync::atomic::{AtomicBool, Ordering}; @@ -80,12 +80,39 @@ pub(crate) struct Inner { snapshot: Mutex, /// Set while connected to a host that understands input. input_tx: Mutex>, + keyboard: Mutex, +} + +/// Hardware keyboard state reported by the application. +#[derive(Default)] +struct KeyboardState { + /// Latest state set by the application (survives reconnects). + attached: bool, + /// Set while connected to a host that understands `ClientKeyboard`. + tx: Option, + /// What the host was last told in this connection. + sent: Option, } fn lock(m: &Mutex) -> MutexGuard<'_, T> { m.lock().unwrap_or_else(|e| e.into_inner()) } +impl KeyboardState { + fn send_if_changed(&mut self) { + let Some(tx) = &self.tx else { return }; + if self.sent == Some(self.attached) { + return; + } + let msg = Message::ClientKeyboard(ClientKeyboard { + attached: self.attached, + }); + if tx.send_control(msg).is_ok() { + self.sent = Some(self.attached); + } + } +} + /// Cheaply cloneable handle to a running (or about to run) client session. /// /// Create it before [`run_client`](crate::run_client) and pass a clone to the @@ -117,6 +144,7 @@ impl ClientHandle { cursor: Mutex::new(Cursor::default()), snapshot: Mutex::new(ClientSnapshot::default()), input_tx: Mutex::new(None), + keyboard: Mutex::new(KeyboardState::default()), })) } @@ -239,6 +267,25 @@ impl ClientHandle { lock(&self.0.snapshot).stream_color } + /// Tells the host whether a hardware keyboard is attached (`ClientKeyboard`, protocol 0.6). + /// + /// The latest state is kept, also while not connected, and sent right after every handshake. + /// While connected, a call that does not change what the host knows sends nothing. Callable + /// from any thread; never blocks. + pub fn set_keyboard_attached(&self, attached: bool) { + let mut k = lock(&self.0.keyboard); + k.attached = attached; + k.send_if_changed(); + } + + /// Sets (or clears) the link used for `ClientKeyboard` and, when set, sends the current state. + pub(crate) fn set_keyboard_sender(&self, tx: Option) { + let mut k = lock(&self.0.keyboard); + k.tx = tx; + k.sent = None; + k.send_if_changed(); + } + pub(crate) fn set_input_sender(&self, tx: Option) { *lock(&self.0.input_tx) = tx; } @@ -361,4 +408,48 @@ mod tests { assert!(h.send_input(&pen)); assert_eq!(h.snapshot().inputs_sent, 3); } + + async fn read_keyboard_messages( + h: &ClientHandle, + act: impl FnOnce(&ClientHandle), + ) -> Vec { + let (a, b) = tokio::io::duplex(1 << 16); + let (tx, _task) = ezd_link::mux::spawn_mux(Box::new(a), MuxOptions::default()); + h.set_keyboard_sender(Some(tx)); + act(h); + h.set_keyboard_sender(None); + let mut rx = ezd_link::mux::MuxReceiver::new(Box::new(b)); + let mut got = Vec::new(); + while let Ok(Ok(Some(m))) = + tokio::time::timeout(std::time::Duration::from_millis(200), rx.recv()).await + { + if let Message::ClientKeyboard(k) = m { + got.push(k.attached); + } + } + got + } + + #[tokio::test] + async fn keyboard_state_is_sent_on_connect_and_only_on_change() { + let h = ClientHandle::new(); + h.set_keyboard_attached(true); // not connected: stored only + let got = read_keyboard_messages(&h, |h| { + h.set_keyboard_attached(true); // unchanged + h.set_keyboard_attached(false); + h.set_keyboard_attached(false); // unchanged + h.set_keyboard_attached(true); + }) + .await; + assert_eq!(got, vec![true, false, true]); + } + + #[tokio::test] + async fn keyboard_state_survives_reconnects() { + let h = ClientHandle::new(); + h.set_keyboard_attached(true); + assert_eq!(read_keyboard_messages(&h, |_| {}).await, vec![true]); + // A new connection is told again even though the state did not change. + assert_eq!(read_keyboard_messages(&h, |_| {}).await, vec![true]); + } } diff --git a/crates/ezd-client-core/src/session.rs b/crates/ezd-client-core/src/session.rs index 41d4ce2..54dc5c3 100644 --- a/crates/ezd-client-core/src/session.rs +++ b/crates/ezd-client-core/src/session.rs @@ -212,6 +212,7 @@ pub async fn run_client( my_hello.proto_minor = minor; } let my_minor_supports_hdr = my_hello.supports_hdr(); + let my_minor_supports_keyboard = my_hello.supports_keyboard(); tx.send_control(Message::Hello(my_hello))?; tx.send_control(Message::ClientCaps(cfg.caps.clone()))?; let hello = wait_for(&mut rx, &tx, "Hello", wait, |m| match m { @@ -262,6 +263,9 @@ pub async fn run_client( if hello.supports_input() { handle.set_input_sender(Some(tx.clone())); } + if hello.supports_keyboard() && my_minor_supports_keyboard { + handle.set_keyboard_sender(Some(tx.clone())); + } // Streaming. let mut ping_seq = 0u32; @@ -320,6 +324,7 @@ pub async fn run_client( }; handle.set_input_sender(None); + handle.set_keyboard_sender(None); let outcome = ClientOutcome { stream, color, diff --git a/crates/ezd-fake-client/src/lib.rs b/crates/ezd-fake-client/src/lib.rs index 55f64ce..35428a8 100644 --- a/crates/ezd-fake-client/src/lib.rs +++ b/crates/ezd-fake-client/src/lib.rs @@ -59,6 +59,8 @@ pub struct FakeClientConfig { pub stop_after_script: bool, /// Protocol minor to advertise in `Hello` instead of ours (to test older clients). pub proto_minor: Option, + /// Hardware keyboard state to report with `ClientKeyboard` (`None` = never set). + pub keyboard_attached: Option, } impl Default for FakeClientConfig { @@ -79,6 +81,7 @@ impl Default for FakeClientConfig { input_script: None, stop_after_script: false, proto_minor: None, + keyboard_attached: None, } } } @@ -417,6 +420,9 @@ pub async fn run_fake_client( core_cfg.proto_minor = cfg.proto_minor; let handle = ClientHandle::new(); + if let Some(a) = cfg.keyboard_attached { + handle.set_keyboard_attached(a); + } let (start_script, script_task) = match cfg.input_script { Some(script) => { let (tx, rx) = tokio::sync::oneshot::channel(); diff --git a/crates/ezd-fake-client/tests/input.rs b/crates/ezd-fake-client/tests/input.rs index b6206ea..63b5ed5 100644 --- a/crates/ezd-fake-client/tests/input.rs +++ b/crates/ezd-fake-client/tests/input.rs @@ -101,7 +101,7 @@ fn injected(rec: &Mutex) -> (Vec, bool) { } InputCall::Scroll(s) => Message::Scroll(ezd_proto::Scroll { t_us: 0, ..*s }), InputCall::Key(k) => Message::Key(Key { t_us: 0, ..*k }), - InputCall::ReleaseAll => return None, + InputCall::Keyboard(_) | InputCall::ReleaseAll => return None, }) }) .collect(); @@ -162,6 +162,36 @@ async fn touch_and_scroll_scripts_arrive_intact() { } } +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn keyboard_state_reaches_the_sink() { + let backend = RecordingBackend::new(status()); + let client = FakeClientConfig { + keyboard_attached: Some(true), + ..client_cfg(InputScript::Tap) + }; + run(client, opts_with(&backend)).await; + let rec = backend.recording.lock().unwrap(); + assert!(rec.calls.contains(&InputCall::Keyboard(true))); + assert_eq!(rec.calls.last(), Some(&InputCall::ReleaseAll)); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn keyboard_state_is_not_sent_by_an_older_client_minor() { + let backend = RecordingBackend::new(status()); + let client = FakeClientConfig { + keyboard_attached: Some(true), + proto_minor: Some(ezd_proto::MINOR_KEYBOARD - 1), + ..client_cfg(InputScript::Tap) + }; + run(client, opts_with(&backend)).await; + let rec = backend.recording.lock().unwrap(); + assert!( + !rec.calls + .iter() + .any(|c| matches!(c, InputCall::Keyboard(_))) + ); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn telemetry_flag_reaches_the_client() { let backend = RecordingBackend::new(status()); diff --git a/crates/ezd-host-core/src/input.rs b/crates/ezd-host-core/src/input.rs index 71727a3..76699a7 100644 --- a/crates/ezd-host-core/src/input.rs +++ b/crates/ezd-host-core/src/input.rs @@ -30,6 +30,11 @@ pub trait InputSink: Send { /// A key press or release (HID usage). Sinks without key support ignore it (they do not /// announce `InputStatus::KEYS`, so well-behaved clients do not send keys to them). fn key(&mut self, _k: &Key) {} + /// The client reports whether a hardware keyboard is attached (`ClientKeyboard`). Called on + /// every change and once after the sink is created if the client already said so. Sinks that + /// adapt the desktop (for example to hide the touch keyboard) undo it in `release_all` and on + /// drop. + fn keyboard_attached(&mut self, _attached: bool) {} /// Called at least every 50 ms while the session runs (e.g. to refresh stationary touches). fn tick(&mut self) {} /// Releases everything that is down (pen out, touches up, buttons up). Called at session end. @@ -90,6 +95,8 @@ pub(crate) enum InputCmd { Msg(Message), /// The output the stream shows (`None` = unknown); sent once after the source started. Output(Option), + /// The client's hardware keyboard state (`ClientKeyboard`). + Keyboard(bool), /// End of session. Stop, } @@ -321,10 +328,12 @@ const LOG_EVERY: Duration = Duration::from_secs(5); pub(crate) fn input_thread(rx: Receiver, ctx: InputContext) -> InputStats { // Wait for the output, collecting what the client already sent. let mut backlog = Vec::new(); + let mut keyboard: Option = None; let output = loop { match rx.recv() { Ok(InputCmd::Msg(m)) => backlog.push(m), Ok(InputCmd::Output(o)) => break o, + Ok(InputCmd::Keyboard(a)) => keyboard = Some(a), Ok(InputCmd::Stop) | Err(_) => return InputStats::default(), } }; @@ -351,12 +360,16 @@ pub(crate) fn input_thread(rx: Receiver, ctx: InputContext) -> InputSt match cmd { InputCmd::Msg(m) => backlog.push(m), InputCmd::Output(_) => {} + InputCmd::Keyboard(a) => keyboard = Some(a), InputCmd::Stop => { sink.release_all(); return InputStats::default(); } } } + if let Some(a) = keyboard { + sink.keyboard_attached(a); + } let mut st = Recorder { total: Hist::new(), @@ -399,6 +412,7 @@ pub(crate) fn input_thread(rx: Receiver, ctx: InputContext) -> InputSt let wait = TICK.saturating_sub(last_tick.elapsed()); match rx.recv_timeout(wait) { Ok(InputCmd::Msg(m)) => record(&mut st, sink.as_mut(), &m), + Ok(InputCmd::Keyboard(a)) => sink.keyboard_attached(a), Ok(InputCmd::Output(_)) | Err(RecvTimeoutError::Timeout) => {} Ok(InputCmd::Stop) | Err(RecvTimeoutError::Disconnected) => break, } diff --git a/crates/ezd-host-core/src/session.rs b/crates/ezd-host-core/src/session.rs index 63b8c41..c5eafc1 100644 --- a/crates/ezd-host-core/src/session.rs +++ b/crates/ezd-host-core/src/session.rs @@ -491,6 +491,12 @@ pub async fn run_host_session_with( } } }, + Ok(Some(Message::ClientKeyboard(k))) => { + tracing::debug!(attached = k.attached, "client keyboard"); + if let Some(t) = &input_tx { + let _ = t.send(InputCmd::Keyboard(k.attached)); + } + } Ok(Some(Message::Bye(b))) => break EndReason::ClientBye(b.reason), Ok(Some(Message::Reject(r))) => break EndReason::ClientBye(r.reason), Ok(Some(other)) => tracing::debug!(?other, "ignoring message"), diff --git a/crates/ezd-host-core/src/testing.rs b/crates/ezd-host-core/src/testing.rs index bb3944a..f0ebdd7 100644 --- a/crates/ezd-host-core/src/testing.rs +++ b/crates/ezd-host-core/src/testing.rs @@ -172,6 +172,8 @@ pub enum InputCall { Scroll(Scroll), /// `InputSink::key`. Key(Key), + /// `InputSink::keyboard_attached`. + Keyboard(bool), /// `InputSink::release_all`. ReleaseAll, } @@ -258,6 +260,9 @@ impl InputSink for RecordingSink { fn key(&mut self, k: &Key) { self.push(InputCall::Key(*k)); } + fn keyboard_attached(&mut self, attached: bool) { + self.push(InputCall::Keyboard(attached)); + } fn tick(&mut self) { self.recording .lock() diff --git a/crates/ezd-host-linux/src/input.rs b/crates/ezd-host-linux/src/input.rs index b050216..d0b6c20 100644 --- a/crates/ezd-host-linux/src/input.rs +++ b/crates/ezd-host-linux/src/input.rs @@ -705,7 +705,8 @@ pub fn keyboard_keys() -> impl Iterator { HID_TO_EVDEV.iter().map(|&(_, k)| k) } -/// Keyboard encoder: one frame per transition, duplicates and unknown usages ignored. +/// Keyboard encoder: one frame per transition; a press of a key already down is an autorepeat +/// (value 2). Releases of keys not down and unknown usages are ignored. #[derive(Debug, Default)] pub struct KeyboardEncoder { /// Usages currently down, in press order. @@ -718,8 +719,8 @@ impl KeyboardEncoder { Self::default() } - /// A key press or release. Pressing a key that is down or releasing one that is not emits - /// nothing. + /// A key press or release. Pressing a key that is down emits an autorepeat (value 2); + /// releasing one that is not down emits nothing. pub fn key(&mut self, k: &HidKey) -> Vec { let Some(code) = hid_to_evdev(k.usage) else { return vec![]; @@ -730,6 +731,7 @@ impl KeyboardEncoder { self.down.push(k.usage); vec![vec![key(code, 1)]] } + (true, Some(_)) => vec![vec![key(code, 2)]], (false, Some(i)) => { self.down.remove(i); vec![vec![key(code, 0)]] @@ -1280,7 +1282,11 @@ mod tests { "release of a key not down" ); assert_eq!(e.key(&hk(0x2C, true)), vec![vec![(K, Key::KEY_SPACE.0, 1)]]); - assert!(e.key(&hk(0x2C, true)).is_empty(), "duplicate press"); + assert_eq!( + e.key(&hk(0x2C, true)), + vec![vec![(K, Key::KEY_SPACE.0, 2)]], + "press of a key already down is an autorepeat" + ); assert!(e.key(&hk(0x03, true)).is_empty(), "unknown usage"); assert_eq!( e.key(&hk(0x2C, false)), diff --git a/crates/ezd-host-windows/src/input_map.rs b/crates/ezd-host-windows/src/input_map.rs index 2c25877..de7328c 100644 --- a/crates/ezd-host-windows/src/input_map.rs +++ b/crates/ezd-host-windows/src/input_map.rs @@ -554,8 +554,8 @@ pub fn hid_to_scancode(usage: u16) -> Option<(u16, bool)> { } } -/// Tracks the keys that are down; duplicate presses, releases of keys that are not down and -/// unmapped usages produce nothing. +/// Tracks the keys that are down. A press of a key already down is an autorepeat and gives +/// another key-down; releases of keys that are not down and unmapped usages produce nothing. #[derive(Debug, Default)] pub struct KeyTracker { /// `(usage, scancode, extended)` in press order. @@ -575,8 +575,10 @@ impl KeyTracker { }; let pos = self.down.iter().position(|d| d.0 == k.usage); match (k.pressed, pos) { - (true, None) => { - self.down.push((k.usage, scan, extended)); + (true, found) => { + if found.is_none() { + self.down.push((k.usage, scan, extended)); + } vec![MouseOrKey::Scan { scan, extended, @@ -1345,7 +1347,11 @@ mod tests { vec![scan(0x1D, false, true)] ); assert_eq!(t.key(&k(Key::LEFT_GUI, true)), vec![scan(0x5B, true, true)]); - assert!(t.key(&k(Key::LEFT_GUI, true)).is_empty(), "duplicate press"); + assert_eq!( + t.key(&k(Key::LEFT_GUI, true)), + vec![scan(0x5B, true, true)], + "press of a key already down is an autorepeat" + ); assert!(t.key(&k(0x03, true)).is_empty(), "unmapped"); assert_eq!(t.key(&k(Key::SPACE, true)), vec![scan(0x39, false, true)]); assert_eq!(t.key(&k(Key::SPACE, false)), vec![scan(0x39, false, false)]); diff --git a/crates/ezd-host-windows/src/lib.rs b/crates/ezd-host-windows/src/lib.rs index 34f56e4..8763f10 100644 --- a/crates/ezd-host-windows/src/lib.rs +++ b/crates/ezd-host-windows/src/lib.rs @@ -20,6 +20,7 @@ pub mod input_map; pub mod pipe_proto; pub mod policy; pub mod task_xml; +pub mod touch_keyboard; pub mod vdd_install; pub mod vdd_xml; diff --git a/crates/ezd-host-windows/src/touch_keyboard.rs b/crates/ezd-host-windows/src/touch_keyboard.rs new file mode 100644 index 0000000..4e37248 --- /dev/null +++ b/crates/ezd-host-windows/src/touch_keyboard.rs @@ -0,0 +1,148 @@ +//! Decisions for keeping the Windows touch keyboard from popping up while the client has a +//! hardware keyboard attached. +//! +//! Windows opens the touch keyboard when a text field is tapped, according to the per-user +//! DWORD `TouchKeyboardTapInvoke` (0 = never, 1 = when no keyboard is attached, 2 = always; the +//! value may be absent, which means the OS default). Keys injected by us do not count as an +//! attached keyboard, so while the client reports one we set the value to 0 and restore the +//! original afterwards. This module is the pure state machine and the encoding of the crash +//! marker; the registry access lives in `win::touch_keyboard`. + +/// Key (under HKCU) that holds `TouchKeyboardTapInvoke`. +pub const TABLET_TIP_KEY: &str = r"Software\Microsoft\TabletTip\1.7"; +/// The DWORD that decides when a tap opens the touch keyboard. +pub const TAP_INVOKE_VALUE: &str = "TouchKeyboardTapInvoke"; +/// Our own key (under HKCU). +pub const OWN_KEY: &str = r"Software\LibreStatic\ezdisplay"; +/// REG_SZ under [`OWN_KEY`] with the original value while we override it, see [`encode_saved`]. +pub const SAVED_VALUE: &str = "SavedTouchKeyboardTapInvoke"; +/// The value we write while a hardware keyboard is attached ("never"). +pub const TAP_INVOKE_NEVER: u32 = 0; + +const ABSENT: &str = "absent"; + +/// The marker text for an original value (`None` = the value did not exist). +pub fn encode_saved(original: Option) -> String { + match original { + Some(v) => v.to_string(), + None => ABSENT.to_string(), + } +} + +/// Reads a marker written by [`encode_saved`]; `None` if it is malformed. +pub fn decode_saved(s: &str) -> Option> { + let s = s.trim(); + if s == ABSENT { + Some(None) + } else { + s.parse().ok().map(Some) + } +} + +/// Tracks whether we currently override the setting and what to put back. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct TouchKeyboardGuard { + /// `Some(original)` while overridden (`original` = `None` if the value was absent). + overridden: Option>, +} + +impl TouchKeyboardGuard { + /// A guard that overrides nothing. + pub fn new() -> Self { + Self::default() + } + + /// True while the setting is overridden. + pub fn is_overridden(&self) -> bool { + self.overridden.is_some() + } + + /// The client reports a hardware keyboard. `current` is the present registry value. + /// + /// Returns the original to persist before writing [`TAP_INVOKE_NEVER`], or `None` when + /// nothing has to be done (already overridden, or the user already chose "never"). + pub fn attach(&mut self, current: Option) -> Option> { + if self.overridden.is_some() || current == Some(TAP_INVOKE_NEVER) { + return None; + } + self.overridden = Some(current); + Some(current) + } + + /// The keyboard went away, the session ended or the sink is dropped. + /// + /// Returns the original to restore (`None` original = delete the value), or `None` when + /// nothing is overridden. Calling it again returns `None`. + pub fn detach(&mut self) -> Option> { + self.overridden.take() + } + + /// Puts the guard back in the overridden state, to retry a restore that failed. + pub fn restore_failed(&mut self, original: Option) { + self.overridden = Some(original); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn attach_saves_the_original_once() { + let mut g = TouchKeyboardGuard::new(); + assert_eq!(g.attach(Some(1)), Some(Some(1))); + assert!(g.is_overridden()); + // The registry now holds 0, a repeated attach must not overwrite the saved original. + assert_eq!(g.attach(Some(0)), None); + assert_eq!(g.detach(), Some(Some(1))); + assert!(!g.is_overridden()); + assert_eq!(g.detach(), None, "restoring twice does nothing"); + } + + #[test] + fn absent_value_is_restored_as_absent() { + let mut g = TouchKeyboardGuard::new(); + assert_eq!(g.attach(None), Some(None)); + assert_eq!(g.detach(), Some(None)); + } + + #[test] + fn user_choice_of_never_is_left_alone() { + let mut g = TouchKeyboardGuard::new(); + assert_eq!(g.attach(Some(0)), None); + assert!(!g.is_overridden()); + assert_eq!(g.detach(), None); + } + + #[test] + fn detach_without_attach_is_a_no_op() { + assert_eq!(TouchKeyboardGuard::new().detach(), None); + } + + #[test] + fn can_attach_again_after_detach() { + let mut g = TouchKeyboardGuard::new(); + g.attach(Some(2)); + g.detach(); + assert_eq!(g.attach(Some(2)), Some(Some(2))); + } + + #[test] + fn failed_restore_can_be_retried() { + let mut g = TouchKeyboardGuard::new(); + g.attach(Some(1)); + let o = g.detach().unwrap(); + g.restore_failed(o); + assert_eq!(g.detach(), Some(Some(1))); + } + + #[test] + fn marker_roundtrip() { + for v in [None, Some(0), Some(1), Some(2), Some(u32::MAX)] { + assert_eq!(decode_saved(&encode_saved(v)), Some(v)); + } + assert_eq!(decode_saved("garbage"), None); + assert_eq!(decode_saved(""), None); + assert_eq!(decode_saved(" absent "), Some(None)); + } +} diff --git a/crates/ezd-host-windows/src/win/input.rs b/crates/ezd-host-windows/src/win/input.rs index 0025b36..e72f05d 100644 --- a/crates/ezd-host-windows/src/win/input.rs +++ b/crates/ezd-host-windows/src/win/input.rs @@ -6,6 +6,7 @@ //! converts them into Win32 structs and injects them. use super::display; +use super::touch_keyboard::TouchKeyboard; use super::util::err_str; use crate::input_map::{ self, KeyTracker, Modifier, MouseButton, MouseOrKey, MousePenTracker, PenFrame, PenTracker, @@ -94,6 +95,7 @@ pub fn diag_json() -> Value { json!({ "pen": show(Device::pen()), "touch": show(Device::touch()), + "touch_keyboard": super::touch_keyboard::diag_json(), "note": "needs Windows 10 1809+; input to elevated (administrator) windows is blocked unless the host runs elevated (the tray app does by default)", }) } @@ -272,6 +274,8 @@ pub struct WinInputBackend; impl WinInputBackend { /// A backend; devices are created per session, in `create`. pub fn new() -> Self { + // A host that crashed while the touch keyboard was suppressed left the setting changed. + super::touch_keyboard::recover_after_crash(); WinInputBackend } } @@ -350,6 +354,7 @@ impl InputBackend for WinInputBackend { mouse_pen: MousePenTracker::default(), touch: TouchTracker::default(), keys: KeyTracker::new(), + touch_keyboard: TouchKeyboard::new(), notes, warn_inject: RateLimit::new(WARN_EVERY), warn_send: RateLimit::new(WARN_EVERY), @@ -370,6 +375,8 @@ struct WinInputSink { mouse_pen: MousePenTracker, touch: TouchTracker, keys: KeyTracker, + /// Hides the touch keyboard while the client has a hardware keyboard; restores on drop. + touch_keyboard: TouchKeyboard, notes: Vec, warn_inject: RateLimit, warn_send: RateLimit, @@ -521,6 +528,10 @@ impl InputSink for WinInputSink { self.send(&events); } + fn keyboard_attached(&mut self, attached: bool) { + self.touch_keyboard.set_attached(attached); + } + fn tick(&mut self) { if let Some(contacts) = self.touch.refresh(Instant::now()) { self.inject_touch_contacts(&contacts); @@ -536,6 +547,7 @@ impl InputSink for WinInputSink { self.inject_touch_contacts(&contacts); let events = self.keys.release_all(); self.send(&events); + self.touch_keyboard.restore(); } fn status(&self) -> InputStatus { diff --git a/crates/ezd-host-windows/src/win/mod.rs b/crates/ezd-host-windows/src/win/mod.rs index f66cb13..cb1706d 100644 --- a/crates/ezd-host-windows/src/win/mod.rs +++ b/crates/ezd-host-windows/src/win/mod.rs @@ -17,6 +17,7 @@ pub mod input; pub mod shell; pub mod source; pub mod task; +pub mod touch_keyboard; pub mod util; pub mod vdd; pub mod vdd_install; diff --git a/crates/ezd-host-windows/src/win/touch_keyboard.rs b/crates/ezd-host-windows/src/win/touch_keyboard.rs new file mode 100644 index 0000000..1a58dbb --- /dev/null +++ b/crates/ezd-host-windows/src/win/touch_keyboard.rs @@ -0,0 +1,274 @@ +//! Registry side of the touch keyboard suppression, see [`crate::touch_keyboard`]. +//! +//! Everything here is best effort: a failure is logged and never breaks the session. + +use super::util::{from_wide, wide}; +use crate::touch_keyboard::{ + OWN_KEY, SAVED_VALUE, TABLET_TIP_KEY, TAP_INVOKE_NEVER, TAP_INVOKE_VALUE, TouchKeyboardGuard, + decode_saved, encode_saved, +}; +use windows::Win32::Foundation::{ + ERROR_FILE_NOT_FOUND, ERROR_SUCCESS, LPARAM, WIN32_ERROR, WPARAM, +}; +use windows::Win32::System::Registry::{ + HKEY_CURRENT_USER, REG_DWORD, REG_SZ, RRF_RT_REG_DWORD, RRF_RT_REG_SZ, RegDeleteKeyValueW, + RegGetValueW, RegSetKeyValueW, +}; +use windows::Win32::UI::WindowsAndMessaging::{ + HWND_BROADCAST, SMTO_ABORTIFHUNG, SendMessageTimeoutW, WM_SETTINGCHANGE, +}; +use windows::core::PCWSTR; + +/// How long one window may take to handle the settings broadcast. +const BROADCAST_TIMEOUT_MS: u32 = 100; + +fn check(r: WIN32_ERROR) -> Result<(), String> { + if r == ERROR_SUCCESS { + Ok(()) + } else { + Err(format!("registry error {}", r.0)) + } +} + +/// Reads a value of the current user; `Ok(None)` if it does not exist. +fn read_dword(subkey: &str, name: &str) -> Result, String> { + let (sk, n) = (wide(subkey), wide(name)); + let (mut v, mut bytes) = (0u32, 4u32); + // SAFETY: valid NUL-terminated strings; `v` is a valid 4-byte output buffer. + let r = unsafe { + RegGetValueW( + HKEY_CURRENT_USER, + PCWSTR(sk.as_ptr()), + PCWSTR(n.as_ptr()), + RRF_RT_REG_DWORD, + None, + Some((&mut v as *mut u32).cast()), + Some(&mut bytes), + ) + }; + if r == ERROR_FILE_NOT_FOUND { + return Ok(None); + } + check(r).map(|()| Some(v)) +} + +fn read_string(subkey: &str, name: &str) -> Result, String> { + let (sk, n) = (wide(subkey), wide(name)); + let mut buf = [0u16; 64]; + let mut bytes = std::mem::size_of_val(&buf) as u32; + // SAFETY: valid NUL-terminated strings; `buf` is `bytes` bytes long. + let r = unsafe { + RegGetValueW( + HKEY_CURRENT_USER, + PCWSTR(sk.as_ptr()), + PCWSTR(n.as_ptr()), + RRF_RT_REG_SZ, + None, + Some(buf.as_mut_ptr().cast()), + Some(&mut bytes), + ) + }; + if r == ERROR_FILE_NOT_FOUND { + return Ok(None); + } + check(r).map(|()| Some(from_wide(&buf))) +} + +fn write_dword(subkey: &str, name: &str, v: u32) -> Result<(), String> { + let (sk, n) = (wide(subkey), wide(name)); + // SAFETY: valid NUL-terminated strings; the data is a live 4-byte DWORD. + check(unsafe { + RegSetKeyValueW( + HKEY_CURRENT_USER, + PCWSTR(sk.as_ptr()), + PCWSTR(n.as_ptr()), + REG_DWORD.0, + Some((&v as *const u32).cast()), + 4, + ) + }) +} + +fn write_string(subkey: &str, name: &str, s: &str) -> Result<(), String> { + let (sk, n, data) = (wide(subkey), wide(name), wide(s)); + // SAFETY: valid NUL-terminated strings; `data` is `2 * len` bytes including the NUL. + check(unsafe { + RegSetKeyValueW( + HKEY_CURRENT_USER, + PCWSTR(sk.as_ptr()), + PCWSTR(n.as_ptr()), + REG_SZ.0, + Some(data.as_ptr().cast()), + (data.len() * 2) as u32, + ) + }) +} + +/// Deletes a value; a value that does not exist counts as deleted. +fn delete_value(subkey: &str, name: &str) -> Result<(), String> { + let (sk, n) = (wide(subkey), wide(name)); + // SAFETY: valid NUL-terminated strings. + let r = + unsafe { RegDeleteKeyValueW(HKEY_CURRENT_USER, PCWSTR(sk.as_ptr()), PCWSTR(n.as_ptr())) }; + if r == ERROR_FILE_NOT_FOUND { + return Ok(()); + } + check(r) +} + +/// Tells running programs (the touch keyboard host) that `TabletTip` settings changed. Done on +/// a short-lived thread because a hung top-level window could stall the caller. +fn broadcast_change() { + let _ = std::thread::Builder::new() + .name("ezd-settingchange".into()) + .spawn(|| { + let area = wide("TabletTip"); + // SAFETY: `area` outlives the synchronous call; lParam is a pointer to it as + // WM_SETTINGCHANGE requires. + unsafe { + SendMessageTimeoutW( + HWND_BROADCAST, + WM_SETTINGCHANGE, + WPARAM(0), + LPARAM(area.as_ptr() as isize), + SMTO_ABORTIFHUNG, + BROADCAST_TIMEOUT_MS, + None, + ); + } + }); +} + +/// Writes `value` (`None` = delete) to `TouchKeyboardTapInvoke`. +fn set_tap_invoke(value: Option) -> Result<(), String> { + match value { + Some(v) => write_dword(TABLET_TIP_KEY, TAP_INVOKE_VALUE, v), + None => delete_value(TABLET_TIP_KEY, TAP_INVOKE_VALUE), + } +} + +/// Restores the setting from the crash marker left by an earlier run that did not exit cleanly. +/// Call once when the input backend is created. +pub fn recover_after_crash() { + let saved = match read_string(OWN_KEY, SAVED_VALUE) { + Ok(Some(s)) => s, + Ok(None) => return, + Err(e) => { + tracing::warn!("touch keyboard: cannot read the saved setting: {e}"); + return; + } + }; + match decode_saved(&saved) { + Some(original) => match set_tap_invoke(original) { + Ok(()) => { + tracing::info!( + "touch keyboard: restored TouchKeyboardTapInvoke to {original:?} after an unclean exit" + ); + broadcast_change(); + } + Err(e) => { + tracing::warn!("touch keyboard: restore after an unclean exit failed: {e}"); + return; // keep the marker for the next start + } + }, + None => tracing::warn!("touch keyboard: ignoring malformed saved setting {saved:?}"), + } + if let Err(e) = delete_value(OWN_KEY, SAVED_VALUE) { + tracing::warn!("touch keyboard: cannot clear the saved setting: {e}"); + } +} + +/// Current value of `TouchKeyboardTapInvoke` and whether our marker says we override it, for +/// `ezd-host diag`. +pub fn diag_json() -> serde_json::Value { + use serde_json::json; + let current = match read_dword(TABLET_TIP_KEY, TAP_INVOKE_VALUE) { + Ok(v) => json!(v), + Err(e) => json!(format!("unreadable: {e}")), + }; + let overridden = matches!(read_string(OWN_KEY, SAVED_VALUE), Ok(Some(_))); + json!({ "touch_keyboard_tap_invoke": current, "overridden": overridden }) +} + +/// Keeps the touch keyboard from opening while the client has a hardware keyboard. +/// Restores the setting on [`restore`](Self::restore) and on drop. +#[derive(Default)] +pub struct TouchKeyboard { + guard: TouchKeyboardGuard, +} + +impl TouchKeyboard { + /// A suppressor that has changed nothing yet. + pub fn new() -> Self { + Self::default() + } + + /// The client's hardware keyboard state changed. + pub fn set_attached(&mut self, attached: bool) { + if attached { + self.suppress(); + } else { + self.restore(); + } + } + + fn suppress(&mut self) { + let current = match read_dword(TABLET_TIP_KEY, TAP_INVOKE_VALUE) { + Ok(v) => v, + Err(e) => { + tracing::warn!("touch keyboard: cannot read TouchKeyboardTapInvoke: {e}"); + return; + } + }; + let Some(original) = self.guard.attach(current) else { + return; + }; + // Persist the original first so a crash cannot leave the user stuck at "never". + if let Err(e) = write_string(OWN_KEY, SAVED_VALUE, &encode_saved(original)) { + tracing::warn!( + "touch keyboard: cannot save the original setting, not changing it: {e}" + ); + self.guard.detach(); + return; + } + match set_tap_invoke(Some(TAP_INVOKE_NEVER)) { + Ok(()) => { + tracing::info!( + "touch keyboard: hardware keyboard attached, TouchKeyboardTapInvoke {original:?} -> 0" + ); + broadcast_change(); + } + Err(e) => { + tracing::warn!("touch keyboard: cannot set TouchKeyboardTapInvoke: {e}"); + self.guard.detach(); + let _ = delete_value(OWN_KEY, SAVED_VALUE); + } + } + } + + /// Puts the original setting back, if we changed it. + pub fn restore(&mut self) { + let Some(original) = self.guard.detach() else { + return; + }; + match set_tap_invoke(original) { + Ok(()) => { + tracing::info!("touch keyboard: restored TouchKeyboardTapInvoke to {original:?}"); + if let Err(e) = delete_value(OWN_KEY, SAVED_VALUE) { + tracing::warn!("touch keyboard: cannot clear the saved setting: {e}"); + } + broadcast_change(); + } + Err(e) => { + // The marker stays, so the next start restores it. + tracing::warn!("touch keyboard: cannot restore TouchKeyboardTapInvoke: {e}"); + } + } + } +} + +impl Drop for TouchKeyboard { + fn drop(&mut self) { + self.restore(); + } +} diff --git a/crates/ezd-input/src/gesture.rs b/crates/ezd-input/src/gesture.rs index ec7a40b..8b1e996 100644 --- a/crates/ezd-input/src/gesture.rs +++ b/crates/ezd-input/src/gesture.rs @@ -306,7 +306,13 @@ impl InputEngine { .filter(|(bit, _)| c.mods & bit != 0) .map(|(_, usage)| *usage) .chain((c.key != 0).then_some(c.key)); + let mut sent = Vec::new(); for usage in keys { + // A repeated usage (key equal to a modifier) would be an autorepeat on the host. + if sent.contains(&usage) { + continue; + } + sent.push(usage); out.push(Message::Key(Key { t_us: t, usage, diff --git a/crates/ezd-proto/src/lib.rs b/crates/ezd-proto/src/lib.rs index 0a838d2..3ac2259 100644 --- a/crates/ezd-proto/src/lib.rs +++ b/crates/ezd-proto/src/lib.rs @@ -30,11 +30,13 @@ pub use negotiate::{ /// Wire protocol major version. A mismatch is fatal at handshake. pub const PROTOCOL_MAJOR: u16 = 0; /// Wire protocol minor version. Newer minors may add new `(channel, kind)` pairs. -pub const PROTOCOL_MINOR: u16 = 5; +pub const PROTOCOL_MINOR: u16 = 6; /// First protocol minor with the input messages, `InputStatus` and `ClientOptions`. pub const MINOR_INPUT: u16 = 3; /// First protocol minor with `ClientHdr` and `StreamColor` (HDR10 streaming). pub const MINOR_HDR: u16 = 5; +/// First protocol minor with `ClientKeyboard` (hardware keyboard attached to the client). +pub const MINOR_KEYBOARD: u16 = 6; /// Default TCP port used for the host listener and `adb reverse`. pub const DEFAULT_PORT: u16 = 27183; diff --git a/crates/ezd-proto/src/msg.rs b/crates/ezd-proto/src/msg.rs index 2dbce8b..0edb8bd 100644 --- a/crates/ezd-proto/src/msg.rs +++ b/crates/ezd-proto/src/msg.rs @@ -90,6 +90,12 @@ impl Hello { self.proto_minor >= crate::MINOR_HDR } + /// True if the peer speaks at least protocol minor [`MINOR_KEYBOARD`](crate::MINOR_KEYBOARD) + /// (`ClientKeyboard`). + pub fn supports_keyboard(&self) -> bool { + self.proto_minor >= crate::MINOR_KEYBOARD + } + /// Fails with [`ProtoError::VersionMismatch`] if the peer's major differs from ours. pub fn check_compatible(&self) -> Result<()> { if self.proto_major != crate::PROTOCOL_MAJOR { @@ -477,6 +483,9 @@ impl Scroll { /// `usage` is a USB HID keyboard-page (0x07) usage id, i.e. a physical key /// position on a US layout; the host applies the user's layout like a real USB /// keyboard. Clients send it only when the host reports [`InputStatus::KEYS`]. +/// +/// A press of a key that is already down is an autorepeat: hosts inject another key-down, since +/// they do not repeat on their own. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub struct Key { /// Client monotonic clock, microseconds. @@ -542,6 +551,17 @@ pub const H273_TRANSFER_PQ: u8 = 16; /// H.273 matrix coefficients code of BT.2020 non-constant luminance. pub const H273_MATRIX_BT2020_NCL: u8 = 9; +/// Whether a hardware keyboard is attached to the client (client to host, protocol 0.6). +/// +/// Sent when the state changes and right after the handshake, when the host `Hello` has minor >= +/// [`MINOR_KEYBOARD`](crate::MINOR_KEYBOARD). The host may use it to adapt its desktop, for example +/// to stop the on-screen keyboard from popping up. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct ClientKeyboard { + /// True while a hardware keyboard is attached and usable. + pub attached: bool, +} + /// What the client display and decoders can do with HDR10 (client to host, protocol 0.5). /// /// Sent right after `ClientCaps` when the host `Hello` has minor >= [`MINOR_HDR`](crate::MINOR_HDR). @@ -678,7 +698,7 @@ impl Default for StreamColor { } /// Any message of protocol 0.x (0.2 added `FrameAck`, 0.3 the input messages, -/// `InputStatus` and `ClientOptions`, 0.5 `ClientHdr` and `StreamColor`). +/// `InputStatus` and `ClientOptions`, 0.5 `ClientHdr` and `StreamColor`, 0.6 `ClientKeyboard`). #[derive(Debug, Clone, PartialEq)] #[allow(clippy::large_enum_variant)] pub enum Message { @@ -714,6 +734,8 @@ pub enum Message { ClientHdr(ClientHdr), /// Control/16 (0.5), host to client. StreamColor(StreamColor), + /// Control/17 (0.6), client to host. + ClientKeyboard(ClientKeyboard), /// Input/1 (0.3), client to host. Pen(PenSample), /// Input/2 (0.3), client to host. @@ -766,6 +788,7 @@ impl Message { Message::ClientOptions(_) => 14, Message::ClientHdr(_) => 15, Message::StreamColor(_) => 16, + Message::ClientKeyboard(_) => 17, Message::Pen(_) => 1, Message::Touch(_) => 2, Message::PointerButton(_) => 3, @@ -801,6 +824,7 @@ pub fn encode_message(msg: &Message) -> Result<(Channel, u8, Vec)> { Message::ClientOptions(m) => enc(m)?, Message::ClientHdr(m) => enc(m)?, Message::StreamColor(m) => enc(m)?, + Message::ClientKeyboard(m) => enc(m)?, Message::Pen(m) => enc(m)?, Message::Touch(m) => enc(m)?, Message::PointerButton(m) => enc(m)?, @@ -846,6 +870,7 @@ pub fn decode_message(channel: u8, kind: u8, payload: &[u8]) -> Result Message::ClientOptions(dec(c, k, payload)?), (Channel::Control, 15) => Message::ClientHdr(dec(c, k, payload)?), (Channel::Control, 16) => Message::StreamColor(dec(c, k, payload)?), + (Channel::Control, 17) => Message::ClientKeyboard(dec(c, k, payload)?), (Channel::Input, 1) => Message::Pen(dec(c, k, payload)?), (Channel::Input, 2) => Message::Touch(dec(c, k, payload)?), (Channel::Input, 3) => Message::PointerButton(dec(c, k, payload)?), @@ -963,6 +988,7 @@ mod tests { 1000, 400, )), + Message::ClientKeyboard(ClientKeyboard { attached: true }), Message::Pen(PenSample { t_us: 1 << 40, x: 65535, @@ -1152,6 +1178,15 @@ mod tests { assert!(h.supports_input()); } + #[test] + fn keyboard_support_by_minor() { + let mut h = Hello::new(Role::Client, "x", "y"); + assert!(h.supports_keyboard()); + h.proto_minor = crate::MINOR_KEYBOARD - 1; + assert!(!h.supports_keyboard()); + assert!(h.supports_hdr()); + } + #[test] fn stream_color_presets() { let sdr = StreamColor::sdr_bt709(); diff --git a/docs/protocol.md b/docs/protocol.md index 877ad8c..d8eaa09 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -1,4 +1,4 @@ -# ezdisplay wire protocol (version 0.5) +# ezdisplay wire protocol (version 0.6) All integers are little endian. The protocol runs over any reliable ordered byte stream (TCP through `adb reverse` today; AOA bulk endpoints later). It is implemented in the `ezd-proto` @@ -56,6 +56,7 @@ flowchart LR | Control | 14 | `ClientOptions` | host to client | postcard (0.3) | | Control | 15 | `ClientHdr` | client to host | postcard (0.5) | | Control | 16 | `StreamColor` | host to client | postcard (0.5) | +| Control | 17 | `ClientKeyboard` | client to host | postcard (0.6) | | Input | 1 | `Pen` (`PenSample`) | client to host | postcard (0.3) | | Input | 2 | `Touch` (`TouchFrame`) | client to host | postcard (0.3) | | Input | 3 | `PointerButton` | client to host | postcard (0.3) | @@ -111,9 +112,9 @@ per push) and yields complete messages. ### Versioning -`Hello` carries `proto_major` and `proto_minor` (currently 0 and 5; 0.2 added `FrameAck`, 0.3 +`Hello` carries `proto_major` and `proto_minor` (currently 0 and 6; 0.2 added `FrameAck`, 0.3 the input messages, `InputStatus` and `ClientOptions`, 0.4 the `Key` message, 0.5 `ClientHdr` and -`StreamColor` for HDR10). A different major version is fatal: the +`StreamColor` for HDR10, 0.6 `ClientKeyboard`). A different major version is fatal: the receiver answers `Reject` and closes. Minor versions only add new `(channel, kind)` pairs, so peers with different minors interoperate. `Hello::supports_input()` is true when the peer's minor is at least `MINOR_INPUT` = 3; a host must not send `InputStatus` or @@ -122,6 +123,8 @@ Input messages to an older host. `Key` needs no minor gate: a client sends it on host's `InputStatus.caps` has `KEYS`, and an older host would skip the unknown pair anyway. `Hello::supports_hdr()` is true when the peer's minor is at least `MINOR_HDR` = 5: a client sends `ClientHdr` only to such a host, and a host sends `StreamColor` only to such a client. +`Hello::supports_keyboard()` is true when the peer's minor is at least `MINOR_KEYBOARD` = 6: a +client sends `ClientKeyboard` only to such a host. ## Handshake and session @@ -320,6 +323,14 @@ bits `TOUCH` = 1, `PEN` = 2, `ACTIONS` = 4, `KEYS` = 8 (what the host can inject `note` explaining what is unavailable (empty when all is fine); `ClientOptions { flags: u32 }` with `TELEMETRY` = 1 (show the telemetry overlay). +### Hardware keyboard (0.6) + +Client to host, on the Control channel: `ClientKeyboard { attached: bool }`, sent right after the +handshake (when the host minor is at least 6) and whenever a hardware keyboard is attached or +detached on the client. The host may use it to adapt its desktop; the Windows host stops the touch +keyboard from popping up while `attached` is true and restores the setting when it becomes false or +the session ends. A host that does not care ignores it. + ### HDR10 (0.5) Client to host, on the Control channel, right after the host `Hello` when the host minor is at