Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua-driver): give each character of a text its own spare keycode (#5158)

injaneityf7e177fab667
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/input/mod.rs b/libs/cua-driver/rust/crates/platform-linux/src/input/mod.rs
index e9d3f667b6..0de7e513d6 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/input/mod.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/input/mod.rs
@@ -3382,11 +3382,11 @@ pub fn send_type_text(xid: u64, text: &str) -> Result<()> {
fn type_text_with_preflight<G>(
text: &str,
- mapping: &GetKeyboardMappingReply,
+ keymap: &GetKeyboardMappingReply,
mut remap: impl FnMut(char, &mut GetKeyboardMappingReply) -> Result<(u8, Option<G>)>,
mut send: impl FnMut(u8, bool) -> Result<()>,
-) -> Result<()> {
- let mut mapping = mapping.clone();
+) -> Result<Vec<G>> {
+ let mut mapping = keymap.clone();
let mut guards = Vec::new();
let mut resolved = std::collections::HashMap::new();
let mut keys = Vec::new();
@@ -3398,8 +3398,14 @@ fn type_text_with_preflight<G>(
Some(key) => key,
None => {
let (keycode, guard) = remap(ch, &mut mapping).map_err(|error| {
+ let needed = text
+ .chars()
+ .map(mpx_keyboard::keysym_for_char)
+ .filter(|keysym| !keymap.keysyms.contains(keysym))
+ .collect::<std::collections::HashSet<_>>()
+ .len();
anyhow::anyhow!(
- "typed 0 of {} characters: {error:#}",
+ "typed 0 of {} characters: the text needs {needed} spare keycodes: {error:#}",
text.chars().count()
)
})?;
@@ -3416,7 +3422,7 @@ fn type_text_with_preflight<G>(
for (keycode, needs_shift) in keys {
send(keycode, needs_shift)?;
}
- Ok(())
+ Ok(guards)
}
/// Type a string with an additional `inter_char_ms` delay between each character.
@@ -3425,7 +3431,7 @@ pub fn send_type_text_with_delay(xid: u64, text: &str, inter_char_ms: u64) -> Re
let window = xid as u32;
let root = conn.setup().roots[0].root;
let mapping = conn.get_keyboard_mapping(8, 248)?.reply()?;
- type_text_with_preflight(
+ let _guards = type_text_with_preflight(
text,
&mapping,
|ch, mapping| {
@@ -3510,7 +3516,7 @@ pub fn send_type_text_xtest(text: &str) -> Result<()> {
.get(..kpm)
.and_then(|s| s.iter().copied().find(|&k| k != 0))
.unwrap_or(50);
- type_text_with_preflight(
+ let _guards = type_text_with_preflight(
text,
&mapping,
|ch, mapping| {
@@ -4192,7 +4198,7 @@ mod key_name_alias_tests {
assert_eq!(
error.to_string(),
format!(
- "typed 0 of 3 characters: no spare keycode available to remap keysym 0x{:X}",
+ "typed 0 of 3 characters: the text needs 2 spare keycodes: no spare keycode available to remap keysym 0x{:X}",
super::mpx_keyboard::keysym_for_char('好')
)
);
@@ -4200,6 +4206,54 @@ mod key_name_alias_tests {
assert_eq!(target, "existing");
}
+ struct Restore<'a>(&'a std::cell::Cell<usize>);
+
+ impl Drop for Restore<'_> {
+ fn drop(&mut self) {
+ self.0.set(self.0.get() + 1);
+ }
+ }
+
+ #[test]
+ fn text_preflight_restores_every_remap_after_success_and_failure() {
+ let mapping = GetKeyboardMappingReply {
+ keysyms_per_keycode: 2,
+ sequence: 0,
+ keysyms: vec!['a' as u32, 'A' as u32, 0, 0, 0, 0],
+ };
+ for (text, fail_send, ok, sent) in [
+ ("你好你a", false, true, 4),
+ ("你好约", false, false, 0),
+ ("你好", true, false, 1),
+ ] {
+ let restored = std::cell::Cell::new(0);
+ let mut events = 0;
+ let result = type_text_with_preflight(
+ text,
+ &mapping,
+ |ch, mapping| {
+ reserve_spare_keycode(
+ mapping,
+ super::mpx_keyboard::keysym_for_char(ch),
+ |_, _, _, _| Ok(Restore(&restored)),
+ )
+ .map(|(keycode, guard)| (keycode, Some(guard)))
+ },
+ |_, _| {
+ events += 1;
+ if fail_send {
+ anyhow::bail!("send failed");
+ }
+ Ok(())
+ },
+ );
+ assert_eq!(result.is_ok(), ok, "{text}");
+ drop(result);
+ assert_eq!(restored.get(), 2, "{text}");
+ assert_eq!(events, sent, "{text}");
+ }
+ }
+
#[test]
fn text_preflight_preserves_shift_order_and_reuses_remaps() {
let mapping = GetKeyboardMappingReply {
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/input/mpx_keyboard.rs b/libs/cua-driver/rust/crates/platform-linux/src/input/mpx_keyboard.rs
index 1415be9960..7adc8376d5 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/input/mpx_keyboard.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/input/mpx_keyboard.rs
@@ -121,31 +121,20 @@ fn tap_steps(keycode: u8, needs_shift: bool, shift: Option<u16>, steps: &mut Vec
/// allocator) INLINE, one character at a time, so a mixed-script string
/// (an in-map prefix, a character needing remap, more in-map text) keeps its
/// original order in `steps` — remapping a character never defers it behind
-/// the characters that came after it in `text`. `remap` returns `None` when
-/// the character could neither be found in the keymap nor hosted on a spare
-/// keycode; such characters are returned in the second tuple element.
-pub(super) fn plan_text_with_fallback<F>(
+/// the characters that came after it in `text`.
+pub(super) fn plan_text_with_fallback<G>(
mapping: &GetKeyboardMappingReply,
shift_x_keycode: Option<u8>,
text: &str,
- mut remap: F,
-) -> (Vec<KeyStep>, Vec<char>)
-where
- F: FnMut(char) -> Option<u8>,
-{
+ remap: impl FnMut(char, &mut GetKeyboardMappingReply) -> Result<(u8, Option<G>)>,
+) -> Result<(Vec<KeyStep>, Vec<G>)> {
let shift = shift_x_keycode.and_then(evdev_code_for_x_keycode);
let mut steps = Vec::with_capacity(text.len() * 2);
- let mut skipped = Vec::new();
- for ch in text.chars() {
- match char_to_keycode_shift(mapping, keysym_for_char(ch)) {
- Some((keycode, needs_shift)) => tap_steps(keycode, needs_shift, shift, &mut steps),
- None => match remap(ch) {
- Some(keycode) => tap_steps(keycode, false, shift, &mut steps),
- None => skipped.push(ch),
- },
- }
- }
- (steps, skipped)
+ let guards = type_text_with_preflight(text, mapping, remap, |keycode, needs_shift| {
+ tap_steps(keycode, needs_shift, shift, &mut steps);
+ Ok(())
+ })?;
+ Ok((steps, guards))
}
/// Plan a chord: modifiers pressed in order, the key tapped (with Shift when
@@ -529,7 +518,6 @@ fn deliver(
cursor_id: &str,
target_window: u64,
steps: &[KeyStep],
- skipped_characters: Vec<char>,
remap_guards: Vec<RemappedKeycode<'_>>,
keymap_conn: &RustConnection,
) -> Result<KeyboardDeliveryReport> {
@@ -640,7 +628,7 @@ fn deliver(
core_focus_unchanged,
delivery_confirmed,
key_events: steps.len(),
- skipped_characters,
+ skipped_characters: Vec::new(),
focus_guard: None,
released_stuck,
path: MPX_UINPUT_PATH,
@@ -673,34 +661,11 @@ pub fn send_virtual_keyboard_text(
// (e.g. an ASCII prefix, a character needing remap, then more ASCII)
// would come out with all the in-map characters first, reordering the
// typed text relative to what was asked for.
- let mut guards = Vec::new();
- let mut remap_mapping = keymap.mapping.clone();
- let (steps, skipped) =
- plan_text_with_fallback(
- &keymap.mapping,
- keymap.shift,
- text,
- |ch| match keycode_for_keysym(
- &keymap.conn,
- &mut remap_mapping,
- keysym_for_char(ch),
- &ch.to_string(),
- ) {
- Ok((keycode, guard)) => {
- guards.extend(guard);
- Some(keycode)
- }
- Err(_) => None,
- },
- );
- deliver(
- cursor_id,
- target_window,
- &steps,
- skipped,
- guards,
- &keymap.conn,
- )
+ let (steps, guards) =
+ plan_text_with_fallback(&keymap.mapping, keymap.shift, text, |ch, mapping| {
+ keycode_for_keysym(&keymap.conn, mapping, keysym_for_char(ch), &ch.to_string())
+ })?;
+ deliver(cursor_id, target_window, &steps, guards, &keymap.conn)
}
/// Press `key` with `modifiers` held, into `target_window`, without touching
@@ -732,14 +697,7 @@ pub fn send_virtual_keyboard_key(
}
};
let steps = plan_chord(&modifier_keycodes, keycode, needs_shift, keymap.shift);
- deliver(
- cursor_id,
- target_window,
- &steps,
- Vec::new(),
- guards,
- &keymap.conn,
- )
+ deliver(cursor_id, target_window, &steps, guards, &keymap.conn)
}
#[cfg(test)]
@@ -794,8 +752,9 @@ mod tests {
#[test]
fn text_plan_taps_keys_and_wraps_shifted_glyphs_in_shift() {
- let (steps, missing) = plan_text_with_fallback(&mapping(), Some(50), "aA1!\n", |_| None);
- assert!(missing.is_empty());
+ let (steps, _) =
+ plan_text_with_fallback::<()>(&mapping(), Some(50), "aA1!\n", |_, _| unreachable!())
+ .unwrap();
assert_eq!(
steps,
vec![
@@ -821,7 +780,8 @@ mod tests {
fn text_plan_without_a_shift_keycode_types_the_unshifted_level() {
// No Shift in the modifier map: the keycode is still tapped (the
// server types the base glyph) rather than the character being lost.
- let (steps, _) = plan_text_with_fallback(&mapping(), None, "A", |_| None);
+ let (steps, _) =
+ plan_text_with_fallback::<()>(&mapping(), None, "A", |_, _| unreachable!()).unwrap();
assert_eq!(steps, vec![step(30, true), step(30, false)]);
}
@@ -833,14 +793,14 @@ mod tests {
// more ASCII. The remapped character must land in the MIDDLE of the
// key-event sequence, not be deferred to the end.
const REMAPPED_KEYCODE: u8 = 250; // spare, per the mapping() doc comment
- let (steps, skipped) = plan_text_with_fallback(&mapping(), Some(50), "aé1", |ch| {
+ let (steps, _) = plan_text_with_fallback::<()>(&mapping(), Some(50), "aé1", |ch, _| {
assert_eq!(
ch, 'é',
"only the out-of-keymap character should hit the fallback"
);
- Some(REMAPPED_KEYCODE)
- });
- assert!(skipped.is_empty());
+ Ok((REMAPPED_KEYCODE, None))
+ })
+ .unwrap();
let remapped_evdev = evdev_code_for_x_keycode(REMAPPED_KEYCODE).unwrap();
assert_eq!(
steps,
@@ -860,10 +820,59 @@ mod tests {
}
#[test]
- fn text_plan_with_fallback_reports_characters_the_remap_also_misses() {
- let (steps, skipped) = plan_text_with_fallback(&mapping(), Some(50), "a€a", |_| None);
- assert_eq!(steps.len(), 4); // both 'a's still tap
- assert_eq!(skipped, vec!['€']);
+ fn text_plan_fails_without_steps_and_restores_remaps_when_spares_run_out() {
+ let mut keymap = mapping();
+ keymap
+ .keysyms
+ .iter_mut()
+ .filter(|sym| **sym == 0)
+ .skip(2)
+ .for_each(|sym| *sym = 1);
+ let restored = std::cell::Cell::new(0);
+ let error = plan_text_with_fallback(&keymap, Some(50), "aé€a", |ch, mapping| {
+ reserve_spare_keycode(mapping, keysym_for_char(ch), |_, _, _, _| {
+ Ok(Restore(&restored))
+ })
+ .map(|(keycode, guard)| (keycode, Some(guard)))
+ })
+ .err()
+ .unwrap();
+ assert!(
+ error
+ .to_string()
+ .starts_with("typed 0 of 4 characters: the text needs 2 spare keycodes"),
+ "{error:#}"
+ );
+ assert_eq!(restored.get(), 1);
+ }
+
+ struct Restore<'a>(&'a std::cell::Cell<usize>);
+
+ impl Drop for Restore<'_> {
+ fn drop(&mut self) {
+ self.0.set(self.0.get() + 1);
+ }
+ }
+
+ #[test]
+ fn text_plan_gives_distinct_missing_characters_distinct_keycodes() {
+ let mut remaps = Vec::new();
+ let (steps, _) = plan_text_with_fallback(&mapping(), Some(50), "é€é", |ch, mapping| {
+ let (keycode, ()) =
+ reserve_spare_keycode(mapping, keysym_for_char(ch), |_, _, _, _| Ok(()))?;
+ remaps.push(ch);
+ Ok((keycode, None::<()>))
+ })
+ .unwrap();
+ assert_eq!(remaps, ['é', '€']);
+ let presses: Vec<u16> = steps
+ .iter()
+ .filter(|step| step.press)
+ .map(|step| step.evdev_code)
+ .collect();
+ assert_eq!(presses.len(), 3);
+ assert_ne!(presses[0], presses[1]);
+ assert_eq!(presses[0], presses[2]);
}
#[test]
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/input/targeted.rs b/libs/cua-driver/rust/crates/platform-linux/src/input/targeted.rs
index 684d519f86..ee6f41af2b 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/input/targeted.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/input/targeted.rs
@@ -528,27 +528,6 @@ impl KeyboardMap {
pub(crate) fn lookup(&self, keysym: u32) -> Option<(u8, bool)> {
super::char_to_keycode_shift(&self.mapping, keysym)
}
-
- /// Like [`lookup`](Self::lookup), but borrows a spare keycode when the map
- /// has no keycode for `keysym` (non-Latin text on a US map, sparse
- /// headless keymaps). The guard restores the map on drop.
- pub(crate) fn lookup_or_remap<'a>(
- &self,
- conn: &'a RustConnection,
- keysym: u32,
- ) -> Result<(u8, bool, Option<super::RemappedKeycode<'a>>), TargetedInputError> {
- if let Some((code, shift)) = self.lookup(keysym) {
- return Ok((code, shift, None));
- }
- let (code, guard) = super::keycode_for_keysym(
- conn,
- &mut self.mapping.clone(),
- keysym,
- &format!("0x{keysym:X}"),
- )
- .map_err(failed)?;
- Ok((code, false, guard))
- }
}
pub(crate) fn fake_motion(
@@ -664,21 +643,27 @@ pub(crate) fn type_xtest(
keymap: &KeyboardMap,
text: &str,
) -> Result<(), TargetedInputError> {
- for character in text.chars() {
- let sym = match character {
- '\n' | '\r' => XK_RETURN,
- '\t' => XK_TAB,
- other => char_keysym(other),
- };
- let (code, shift, guard) = keymap.lookup_or_remap(conn, sym)?;
- tap(conn, root, keymap, code, shift)?;
- if guard.is_some() {
- // Let the focused client translate the event under the temporary
- // mapping before the guard restores it.
- sync(conn)?;
- std::thread::sleep(Duration::from_millis(10));
- }
- drop(guard);
+ let guards = super::type_text_with_preflight(
+ text,
+ &keymap.mapping,
+ |character, mapping| {
+ super::keycode_for_keysym(
+ conn,
+ mapping,
+ super::mpx_keyboard::keysym_for_char(character),
+ &character.to_string(),
+ )
+ },
+ |code, shift| Ok(tap(conn, root, keymap, code, shift)?),
+ )
+ .map_err(|error| {
+ error
+ .downcast::<TargetedInputError>()
+ .unwrap_or_else(failed)
+ })?;
+ if !guards.is_empty() {
+ sync(conn)?;
+ std::thread::sleep(Duration::from_millis(10));
}
Ok(())
}
diff --git a/libs/cua-driver/rust/crates/platform-linux/tests/key_input_x11.rs b/libs/cua-driver/rust/crates/platform-linux/tests/key_input_x11.rs
index e3c9ff62d6..def6e5615b 100644
--- a/libs/cua-driver/rust/crates/platform-linux/tests/key_input_x11.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/tests/key_input_x11.rs
@@ -403,3 +403,28 @@ fn xtest_text_fails_when_no_spare_keycode_is_left() -> Result<()> {
}
Ok(())
}
+
+#[test]
+#[ignore = "requires an isolated X11 display with XTEST"]
+fn xtest_text_gives_each_missing_character_its_own_keycode() -> Result<()> {
+ let (conn, screen) = connect()?;
+ focused_input_window(&conn, screen)?;
+ let spare = spare_keycodes(&conn)?;
+ assert!(
+ spare.len() >= 2,
+ "the test display has fewer than 2 spare keycodes"
+ );
+ send_type_text_xtest("\u{4f60}\u{597d}\u{4f60}")?;
+ let presses: Vec<u8> = keyboard_events(&conn, 6)?
+ .into_iter()
+ .filter(|(pressed, _)| *pressed)
+ .map(|(_, event)| event.detail)
+ .collect();
+ assert!(
+ presses.iter().all(|keycode| spare.contains(keycode)),
+ "{presses:?}"
+ );
+ assert_ne!(presses[0], presses[1], "{presses:?}");
+ assert_eq!(presses[0], presses[2], "{presses:?}");
+ Ok(())
+}