Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(cua-driver): resolve Windows press_key characters on the target's layout (#6201)
injaneity6edcd6bd42e9
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/input/keyboard.rs b/libs/cua-driver/rust/crates/platform-windows/src/input/keyboard.rsindex a0b1d9b8ae..e78c5a9394 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/input/keyboard.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/input/keyboard.rs@@ -343,10 +343,12 @@ pub fn post_key(hwnd: u64, key: &str, modifiers: &[&str]) -> Result<()> {// the renderer; mirror the WM_CHAR path and retarget to that child when// the target thread exposes one.let target = focused_descendant(hwnd_win).unwrap_or(hwnd_win);- let vk = key_name_to_vk(key)?;+ let (vk, scan) = match resolve_press(target, key, modifiers)? {+ Press::Key { vk, scan } => (vk, scan),+ Press::Text(ch) => return post_type_text(hwnd, &ch.to_string()),+ };let has_alt = modifiers.iter().any(|m| *m == "alt" || *m == "menu");- let scan = unsafe { MapVirtualKeyW(vk.0 as u32, MAPVK_VK_TO_VSC) };let repeat_lp = |scan: u32, extended: bool, key_up: bool| {let mut lp: u32 = 1; // repeat countlp |= scan << 16;@@ -456,7 +458,10 @@ pub fn send_key_synthesized_after_focus(// diagnostic early than silently no-op.bail!(msg);}- let key_vk = key_name_to_vk(key)?;+ let (key_vk, key_scan) = match resolve_press(target, key, modifiers)? {+ Press::Key { vk, scan } => (vk, scan),+ Press::Text(ch) => return send_text_synthesized_after_focus(hwnd, &ch.to_string(), focus),+ };let mod_vks: Vec<VIRTUAL_KEY> = modifiers.iter().filter_map(|m| modifier_vk(m)).collect();// Build the INPUT sequence: modifiers down, key down, key up, modifiers up@@ -466,8 +471,8 @@ pub fn send_key_synthesized_after_focus(for mvk in &mod_vks {events.push(key_input(*mvk, false));}- events.push(key_input(key_vk, false));- events.push(key_input(key_vk, true));+ events.push(scanned_key_input(key_vk, key_scan, false));+ events.push(scanned_key_input(key_vk, key_scan, true));for mvk in mod_vks.iter().rev() {events.push(key_input(*mvk, true));}@@ -865,7 +870,12 @@ fn unicode_key_input(unit: u16, up: bool) -> INPUT {/// or up (`up = true`). Uses scancode + EXTENDEDKEY where applicable so the/// target sees a hardware-like keystroke.fn key_input(vk: VIRTUAL_KEY, up: bool) -> INPUT {- let scan = unsafe { MapVirtualKeyW(vk.0 as u32, MAPVK_VK_TO_VSC) } as u16;+ let scan = unsafe { MapVirtualKeyW(vk.0 as u32, MAPVK_VK_TO_VSC) };+ scanned_key_input(vk, scan, up)+}++fn scanned_key_input(vk: VIRTUAL_KEY, scan: u32, up: bool) -> INPUT {+ let scan = scan as u16;let mut flags: KEYBD_EVENT_FLAGS = KEYBD_EVENT_FLAGS(0);// Scancode is more reliable than VK for some apps. EXTENDEDKEY flag// makes arrow / nav / right-side modifier keys work correctly.@@ -939,6 +949,47 @@ fn is_extended(vk: VIRTUAL_KEY) -> bool {)}+/// A key press resolved for one target window.+enum Press {+ /// A virtual key and its scan code on the layout that translates it.+ Key { vk: VIRTUAL_KEY, scan: u32 },+ /// A character the target's layout cannot type with one unshifted key;+ /// it goes through `type_text`'s Unicode path instead.+ Text(char),+}++/// A single printable character with no modifiers must type that character,+/// so it is resolved on the target thread's keyboard layout (#6181): on Thai+/// Kedmanee VK_3 types '-', and on AZERTY '3' needs Shift. Named keys and+/// chords such as ctrl+s stay on their virtual keys.+fn resolve_press(target: HWND, key: &str, modifiers: &[&str]) -> Result<Press> {+ use windows::Win32::UI::Input::KeyboardAndMouse::{+ GetKeyboardLayout, MapVirtualKeyExW, VkKeyScanExW,+ };+ let mut chars = key.chars();+ if let (Some(ch), None, true) = (chars.next(), chars.next(), modifiers.is_empty()) {+ if !ch.is_control() {+ // Letter names are case-insensitive, as on the other platforms:+ // "A" types what "a" types and does not add Shift.+ let ch = ch.to_ascii_lowercase();+ let hkl = unsafe { GetKeyboardLayout(GetWindowThreadProcessId(target, None)) };+ let vk = u16::try_from(ch as u32).ok().and_then(|unit| {+ crate::keycodes::unshifted_layout_key(unsafe { VkKeyScanExW(unit, hkl) })+ });+ return Ok(match vk {+ Some(vk) => Press::Key {+ vk: VIRTUAL_KEY(vk),+ scan: unsafe { MapVirtualKeyExW(vk as u32, MAPVK_VK_TO_VSC, hkl) },+ },+ None => Press::Text(ch),+ });+ }+ }+ let vk = key_name_to_vk(key)?;+ let scan = unsafe { MapVirtualKeyW(vk.0 as u32, MAPVK_VK_TO_VSC) };+ Ok(Press::Key { vk, scan })+}+fn key_name_to_vk(key: &str) -> Result<VIRTUAL_KEY> {use windows::Win32::UI::Input::KeyboardAndMouse::*;// Windows reserves the ASCII values themselves as the virtual-key codesdiff --git a/libs/cua-driver/rust/crates/platform-windows/src/keycodes.rs b/libs/cua-driver/rust/crates/platform-windows/src/keycodes.rsindex 7b31acff9a..f860da01ee 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/keycodes.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/keycodes.rs@@ -13,10 +13,44 @@ pub(crate) fn ascii_alphanumeric_virtual_key_code(key: &str) -> Option<u16> {}}+/// The virtual key that types a character unshifted on the target's layout,+/// given that character's `VkKeyScanExW` result on that layout.+///+/// `None` means the key cannot be sent as a plain virtual key: the layout has+/// no key for the character (-1, whose shift byte is also set), it needs a+/// shift state, or it is only on the numpad, which types a navigation key+/// when NumLock is off.+pub(crate) fn unshifted_layout_key(vk_scan: i16) -> Option<u16> {+ let [vk, shift_state] = vk_scan.to_le_bytes();+ (shift_state == 0 && !(0x60..=0x6F).contains(&vk)).then_some(vk as u16)+}+#[cfg(test)]mod tests {use super::*;+ #[test]+ fn unshifted_key_on_the_layout_is_sent_as_that_key() {+ // US: 'a' is VK_A, '/' is VK_OEM_2; F1 sits just past the numpad range.+ assert_eq!(unshifted_layout_key(0x0041), Some(0x41));+ assert_eq!(unshifted_layout_key(0x00BF), Some(0xBF));+ assert_eq!(unshifted_layout_key(0x0070), Some(0x70));+ }++ #[test]+ fn character_the_layout_cannot_type_unshifted_has_no_key() {+ // Thai Kedmanee has no key for 'a'.+ assert_eq!(unshifted_layout_key(-1), None);+ // AZERTY types '3' with Shift+VK_3; US types 'A' with Shift+VK_A.+ assert_eq!(unshifted_layout_key(0x0133), None);+ assert_eq!(unshifted_layout_key(0x0141), None);+ // Thai Kedmanee only has '3' on the numpad (VK_NUMPAD3); the whole+ // numpad range through VK_DIVIDE is excluded.+ assert_eq!(unshifted_layout_key(0x0063), None);+ assert_eq!(unshifted_layout_key(0x0060), None);+ assert_eq!(unshifted_layout_key(0x006F), None);+ }+#[test]fn maps_ascii_letters_to_uppercase_virtual_key_codes() {for letter in b'a'..=b'z' {