diff --git a/crates/capri-computer/src/native.rs b/crates/capri-computer/src/native.rs new file mode 100644 index 0000000..9744400 --- /dev/null +++ b/crates/capri-computer/src/native.rs @@ -0,0 +1,628 @@ +//! Native observation and input primitives (`computer_*` of `capri_linux/main.py`), in-process. +//! Every input re-checks the observed target (window id, pid, process start time, allowed +//! process) immediately before and during input; refusals before input are preflight codes. +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use capri_perception::platform::{process, DesktopState, DesktopWindow}; + +use crate::a11y::{self, Accessibility, Control, Tree}; +use crate::backend::{Button, Input, Windows}; +use crate::error::*; +use crate::keys; + +/// Identity of the observed window carried by every input. +#[derive(Clone, Debug, PartialEq)] +pub struct Target { + pub window_id: String, + pub process_id: u32, + pub started: String, +} + +#[derive(Clone, Debug)] +pub struct State { + pub window: DesktopWindow, + pub started: String, + pub controls: Vec, + pub truncated: bool, + pub accessibility: bool, + pub modal: bool, + pub discord: bool, + pub executable: String, +} + +impl State { + pub fn target(&self) -> Target { + Target { window_id: self.window.id.clone(), process_id: self.window.pid, started: self.started.clone() } + } +} + +const BROWSERS: [&str; 12] = ["firefox", "chrome", "chromium", "msedge", "microsoft-edge", "brave", "opera", "vivaldi", "librewolf", "zen", "floorp", "waterfox"]; + +pub fn browser_process(pid: u32) -> bool { + let exe = process::executable(pid).and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_lowercase())).unwrap_or_default(); + let name = process::name(pid).to_lowercase(); + BROWSERS.iter().any(|b| exe.contains(b) || name.contains(b)) +} + +pub fn discord_window(w: &DesktopWindow) -> bool { + let name = process::name(w.pid).to_lowercase(); + ["discord", "discordptb", "discordcanary"].iter().any(|d| name == *d || w.wm_class.eq_ignore_ascii_case(d)) +} + +pub struct Native { + pub windows: Arc, + pub input: Arc, + pub a11y: Arc, + /// Process allow check (not Capri, same user); replaceable in tests. + pub allowed: Arc bool + Send + Sync>, +} + +fn smoothstep(t: f64) -> f64 { + t * t * (3.0 - 2.0 * t) +} + +/// Top-most window containing the point, skipping Capri's own windows (except the target). +pub fn window_at<'a>(state: &'a DesktopState, x: i32, y: i32, target: &str, allowed: &dyn Fn(u32) -> bool) -> Option<&'a DesktopWindow> { + state.windows.iter().find(|w| w.rect.contains(x, y) && (w.id == target || allowed(w.pid))) +} + +impl Native { + async fn state_now(&self) -> NResult { + Ok(self.windows.state(false).await?) + } + + pub async fn tree_of(&self, w: &DesktopWindow) -> Option { + self.a11y.tree(w, self.windows.relative_a11y(), browser_process(w.pid), 800, Duration::from_secs(2)).await + } + + /// The foreground window if it is an allowed app, else the first suitable window (activated). + async fn observation_window(&self) -> NResult { + let state = self.state_now().await?; + if let Some(a) = state.active().filter(|a| (self.allowed)(a.pid)) { + return Ok(a.clone()); + } + let target = state.windows.iter().find(|w| !w.minimized && w.rect.width > 0 && w.rect.height > 0 && !w.title.trim().is_empty() && (self.allowed)(w.pid)).cloned(); + let Some(target) = target else { return Err(preflight(APPLICATION_UNAVAILABLE, "Open the application you want Capri to control. No input was sent.")) }; + if !self.windows.activate(&target).await? { + return Err(preflight(FOREGROUND_CHANGED, "The application behind Capri could not take focus. Select it and try again. No input was sent.")); + } + Ok(self.state_now().await?.active().cloned().unwrap_or(target)) + } + + pub async fn observe(&self) -> NResult { + let window = self.observation_window().await?; + let tree = self.tree_of(&window).await; + let pointer = self.state_now().await.map(|s| s.cursor).unwrap_or_default(); + let discord = discord_window(&window); + let (mut controls, truncated) = tree.as_ref().map(|t| t.controls(pointer)).unwrap_or_default(); + if discord { + // TODO: Discord's composer/pane checks (Capri's discord-application.mjs) are not ported, so its chat text and drafts are withheld. + for c in &mut controls { + c.untrusted_value.clear(); + if c.kind == "ControlType.Text" { + c.untrusted_name = "Discord text".into(); + } + } + } + let modal = window.modal || tree.as_ref().is_some_and(Tree::modal); + Ok(State { + started: process::started_ticks(window.pid), + executable: process::executable(window.pid).map(|p| p.display().to_string()).unwrap_or_default(), + accessibility: tree.is_some(), + window, + controls, + truncated, + modal, + discord, + }) + } + + /// The observed window must be foreground (re-activated if Capri took focus). + pub async fn input_target(&self, t: &Target, before_input: bool) -> NResult { + if t.window_id.is_empty() || !t.window_id.chars().all(|c| c.is_ascii_digit()) || t.window_id.starts_with('0') || t.window_id.len() > 20 { + return Err(fail("Observe the intended foreground window first.")); + } + let mut active = self.state_now().await?.active().cloned(); + if active.as_ref().is_none_or(|a| a.id != t.window_id) { + // Talking to Capri focuses Capri: bring back exactly the observed window. + let all = self.windows.state(true).await?; + if let Some(observed) = all.windows.iter().find(|w| w.id == t.window_id) + && self.windows.activate(observed).await.unwrap_or(false) + { + let end = Instant::now() + Duration::from_millis(1500); + while Instant::now() < end { + active = self.state_now().await?.active().cloned(); + if active.as_ref().is_some_and(|a| a.id == t.window_id) { + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + } + } + let Some(active) = active.filter(|a| a.id == t.window_id) else { + let m = "The foreground window changed. Observe it again before input."; + return Err(if before_input { preflight(FOREGROUND_CHANGED, m) } else { fail(m) }); + }; + if active.pid == 0 || active.pid != t.process_id { + return Err(fail("The target process changed.")); + } + if !(self.allowed)(active.pid) { + return Err(preflight(APPLICATION_UNAVAILABLE, "The target application identity could not be verified for input. Select another application and observe it again. No input was sent.")); + } + if process::started_ticks(active.pid) != t.started { + return Err(fail("The target process restarted.")); + } + Ok(active) + } + + async fn pointer_matches(&self, x: i32, y: i32, target: &str) -> NResult { + let state = self.state_now().await?; + Ok(window_at(&state, x, y, target, &*self.allowed).is_some_and(|w| w.id == target)) + } + + /// Smoothstep motion from the current pointer, target identity re-checked at every step. + async fn move_pointer(&self, t: &Target, x: i32, y: i32, duration: u64, dragging: bool) -> NResult<()> { + let start = self.state_now().await?.cursor; + let began = Instant::now(); + loop { + self.input_target(t, false).await?; + let p = if duration == 0 { 1.0 } else { (began.elapsed().as_millis() as f64 / duration as f64).min(1.0) }; + let e = smoothstep(p); + let (nx, ny) = ((start.0 as f64 + (x - start.0) as f64 * e).round() as i32, (start.1 as f64 + (y - start.1) as f64 * e).round() as i32); + if dragging && !self.pointer_matches(nx, ny, &t.window_id).await? { + return Err(fail("Another window covers the drag path. Drag stopped.")); + } + self.input.move_to(nx, ny).await?; + if p >= 1.0 { + return Ok(()); + } + tokio::time::sleep(Duration::from_millis(12)).await; + } + } + + fn duration(d: Option, fallback: u64) -> NResult { + let v = d.unwrap_or(fallback); + if v > 2000 { + return Err(fail("Pointer motion must be within two seconds.")); + } + Ok(v) + } + + async fn hit_chain(&self, tree: &Tree, w: &DesktopWindow, x: i32, y: i32) -> Option> { + self.a11y.at_point(tree, w, self.windows.relative_a11y(), x, y).await + } + + /// Moves the pointer, and clicks when `click` is set. + #[allow(clippy::too_many_arguments)] + pub async fn click(&self, t: &Target, x: i32, y: i32, control_id: Option<&str>, click: Option<(Button, u8)>, duration: Option) -> NResult<&'static str> { + let w = self.input_target(t, true).await?; + self.input.ready().await?; + let tree = self.tree_of(&w).await; + let (mut x, mut y) = (x, y); + let mut element = None; + if let Some(id) = control_id.filter(|c| !c.is_empty()) { + let tree = tree.as_ref().ok_or_else(|| fail("The pointer target is no longer available. Observe it again."))?; + let i = tree.find(id).filter(|i| tree.nodes[*i].has(atspi::State::Showing)).ok_or_else(|| fail("The pointer target is no longer available. Observe it again."))?; + let r = tree.nodes[i].rect.ok_or_else(|| fail("The pointer target has no visible geometry."))?; + let mut point = None; + for (fx, fy) in [(0.5, 0.5), (0.25, 0.5), (0.75, 0.5), (0.5, 0.25), (0.5, 0.75)] { + let (px, py) = (r.x + (r.width as f64 * fx) as i32, r.y + (r.height as f64 * fy) as i32); + if self.pointer_matches(px, py, &t.window_id).await? && tree.hit_matches(i, px, py, self.hit_chain(tree, &w, px, py).await.as_deref()) { + point = Some((px, py)); + break; + } + } + (x, y) = point.ok_or_else(|| preflight(TARGET_COVERED, "The visible control does not match the observed target. No click was sent."))?; + element = Some(i); + } + let bounds = self.state_now().await?.desktop_bounds().ok_or_else(|| fail("No active display."))?; + if !bounds.contains(x, y) { + return Err(fail("Pointer coordinates are outside the desktop.")); + } + self.input_target(t, true).await?; + if !self.pointer_matches(x, y, &t.window_id).await? { + return Err(preflight(TARGET_COVERED, "Another window covers the pointer target. No click was sent.")); + } + self.move_pointer(t, x, y, Self::duration(duration, 220)?, false).await?; + let Some((button, count)) = click else { return Ok("Moved the pointer.") }; + if let (Some(i), Some(tree)) = (element, tree.as_ref()) + && !tree.hit_matches(i, x, y, self.hit_chain(tree, &w, x, y).await.as_deref()) + { + return Err(preflight(TARGET_COVERED, "The page moved during pointer movement. No click was sent. Observe it again.")); + } + if !self.pointer_matches(x, y, &t.window_id).await? { + return Err(preflight(TARGET_COVERED, "The pointer target became covered during movement. No click was sent.")); + } + if !(1..=2).contains(&count) { + return Err(fail("Invalid click count.")); + } + for n in 0..count { + if n > 0 { + tokio::time::sleep(Duration::from_millis(60)).await; + } + let checked = self.input_target(t, false).await; + let down = match checked { + Ok(_) => self.input.button(button, true).await, + Err(e) => Err(e), + }; + let _ = self.input.button(button, false).await; + down?; + } + Ok("Clicked the requested position.") + } + + /// Pressed in order, held, released in reverse. + pub async fn keys(&self, t: &Target, keys: &[String], hold_ms: u64, focused_control_id: Option<&str>) -> NResult<&'static str> { + let w = self.input_target(t, true).await?; + self.input.ready().await?; + if hold_ms > 2000 || keys.is_empty() { + return Err(fail("Invalid key hold.")); + } + if let Some(expected) = focused_control_id.filter(|f| !f.is_empty()) { + let tree = self.tree_of(&w).await; + if tree.as_ref().and_then(|t| t.focused().map(|i| t.nodes[i].id.clone())).as_deref() != Some(expected) { + return Err(preflight(FOREGROUND_CHANGED, "Keyboard focus changed since observation. No keys were sent.")); + } + } + let syms: Vec = keys.iter().map(|k| keys::keysym(k)).collect::>()?; + let mut pressed = vec![]; + let result = async { + for s in &syms { + if self.state_now().await?.active().is_none_or(|a| a.id != t.window_id) { + return Err(if pressed.is_empty() { preflight(FOREGROUND_CHANGED, "The foreground window changed. No keys were sent.") } else { fail("The foreground window changed during input.") }); + } + self.input.key(*s, true).await?; + pressed.push(*s); + } + let end = Instant::now() + Duration::from_millis(hold_ms); + while Instant::now() < end { + if self.state_now().await?.active().is_none_or(|a| a.id != t.window_id) { + return Err(fail("The foreground window changed during input.")); + } + tokio::time::sleep(Duration::from_millis(15)).await; + } + Ok(()) + } + .await; + for s in pressed.iter().rev() { + let _ = self.input.key(*s, false).await; + } + result.map(|_| "Pressed the requested keys.") + } + + pub async fn scroll(&self, t: &Target, amount: i32) -> NResult<&'static str> { + self.input_target(t, true).await?; + self.input.ready().await?; + if amount == 0 || amount.abs() > 10 { + return Err(fail("Use one to ten scroll steps.")); + } + self.input.scroll(amount).await?; + Ok("Scrolled the foreground window.") + } + + /// Between two observed points of the same app. + #[allow(clippy::too_many_arguments)] + pub async fn drag(&self, t: &Target, from: (i32, i32, Option<&str>), to: (i32, i32, Option<&str>), modifiers: &[String], duration: Option) -> NResult<&'static str> { + let w = self.input_target(t, true).await?; + self.input.ready().await?; + let mut mods: Vec = vec![]; + for m in modifiers { + if !["CTRL", "SHIFT", "ALT"].contains(&m.as_str()) { + return Err(fail("Invalid drag modifier.")); + } + let s = keys::keysym(m)?; + if mods.contains(&s) { + return Err(fail("Duplicate drag modifier.")); + } + mods.push(s); + } + let tree = self.tree_of(&w).await; + let resolve = async |p: (i32, i32, Option<&str>)| -> NResult<(i32, i32)> { + let (mut x, mut y) = (p.0, p.1); + if let Some(id) = p.2.filter(|s| !s.is_empty()) { + let t = tree.as_ref().ok_or_else(|| fail("The drag target is no longer visible."))?; + let i = t.find(id).filter(|i| t.nodes[*i].has(atspi::State::Showing)).ok_or_else(|| fail("The drag target is no longer visible."))?; + let r = t.nodes[i].rect.ok_or_else(|| fail("The drag target has no geometry."))?; + (x, y) = (r.x + r.width as i32 / 2, r.y + r.height as i32 / 2); + } + if !self.pointer_matches(x, y, &w.id).await? { + return Err(fail("Another window covers the drag target.")); + } + Ok((x, y)) + }; + let start = resolve(from).await?; + let finish = resolve(to).await?; + if self.input.busy().await { + return Err(fail("Release mouse and modifier keys before dragging.")); + } + self.move_pointer(t, start.0, start.1, Self::duration(duration, 350)?, false).await?; + self.input_target(t, false).await?; + let result = async { + for m in &mods { + self.input.key(*m, true).await?; + } + self.input.button(Button::Left, true).await?; + tokio::time::sleep(Duration::from_millis(80)).await; + self.move_pointer(t, finish.0, finish.1, Self::duration(duration, 500)?.max(200), true).await?; + tokio::time::sleep(Duration::from_millis(80)).await; + NResult::Ok(()) + } + .await; + let _ = self.input.button(Button::Left, false).await; + for m in mods.iter().rev() { + let _ = self.input.key(*m, false).await; + } + result.map(|_| "Dragged between the observed targets. Verify the result.") + } + + /// Real keystrokes into the observed field after verified focus, then read back. + pub async fn type_text(&self, t: &Target, control_id: &str, text: &str, append: bool, duration: Option) -> NResult<()> { + let w = self.input_target(t, true).await?; + self.input.ready().await?; + let len = text.chars().count(); + if !(1..=4000).contains(&len) { + return Err(fail("Invalid input text.")); + } + let tree = self.tree_of(&w).await.ok_or_else(|| preflight(FIELD_STALE, "This application does not expose its fields. No text was sent."))?; + let field = tree.find(control_id).filter(|i| a11y::editable(&tree.nodes[*i]) && tree.nodes[*i].has(atspi::State::Showing)).ok_or_else(|| preflight(FIELD_STALE, "That editable target is no longer available. No text was sent."))?; + let node = tree.nodes[field].clone(); + let old = self.a11y.value(&node, 16001).await.unwrap_or_default(); + let expected = if append { format!("{old}{text}") } else { text.to_string() }; + if expected.chars().count() > 8000 { + return Err(fail("The resulting text is too long.")); + } + if self.input.busy().await { + return Err(preflight(INPUT_BUSY, "Release mouse and modifier keys before text entry. No text was sent.")); + } + let (ctrl, shift, home, end, l) = (keys::keysym("CTRL")?, keys::keysym("SHIFT")?, keys::keysym("HOME")?, keys::keysym("END")?, keys::keysym("L")?); + let focused_inside = async |me: &Self| -> bool { + let fresh = me.tree_of(&w).await; + fresh.is_some_and(|f| f.focused().is_some_and(|fi| f.find(&node.id).is_some_and(|ni| f.within(fi, ni)))) + }; + if tree.browser_address(field) { + self.input_target(t, false).await?; + let r = async { + self.input.key(ctrl, true).await?; + self.input.key(l, true).await?; + self.input.key(l, false).await + } + .await; + let _ = self.input.key(ctrl, false).await; + r?; + let end_at = Instant::now() + Duration::from_millis(600); + let mut ok = false; + while Instant::now() < end_at && !ok { + ok = self.tree_of(&w).await.is_some_and(|f| f.focused().is_some_and(|i| a11y::editable(&f.nodes[i]) && f.browser_address(i))); + tokio::time::sleep(Duration::from_millis(40)).await; + } + if !ok { + return Err(if w.fullscreen { preflight(FULLSCREEN_TOOLBAR, "Leave browser fullscreen before using its hidden address bar. No text was sent.") } else { preflight(FIELD_FOCUS_CHANGED, "The observed browser address field could not be focused. No text was sent.") }); + } + } else { + let r = node.rect.ok_or_else(|| preflight(TARGET_COVERED, "The text field is covered. No text was sent."))?; + let (x, y) = (r.x + r.width as i32 / 2, r.y + r.height as i32 / 2); + if !self.pointer_matches(x, y, &t.window_id).await? { + return Err(preflight(TARGET_COVERED, "The text field is covered. No text was sent.")); + } + self.move_pointer(t, x, y, Self::duration(duration, 220)?, false).await?; + self.input_target(t, false).await?; + let down = self.input.button(Button::Left, true).await; + let _ = self.input.button(Button::Left, false).await; + down?; + tokio::time::sleep(Duration::from_millis(100)).await; + if self.state_now().await?.active().is_none_or(|a| a.id != t.window_id) { + return Err(preflight(FIELD_FOCUS_CHANGED, "The foreground changed. No text was sent.")); + } + // Toolkits that do not report focus after a real click: focus only this observed field. + if !focused_inside(self).await && !(self.a11y.focus(&node).await && focused_inside(self).await) { + return Err(preflight(FIELD_FOCUS_CHANGED, "The click focused a different control. Observe the page again; no text was sent.")); + } + } + self.input_target(t, false).await?; + let select = async { + self.input.key(ctrl, true).await?; + if append { + self.input.key(end, true).await?; + self.input.key(end, false).await?; + } else { + self.input.key(home, true).await?; + self.input.key(home, false).await?; + self.input.key(shift, true).await?; + self.input.key(end, true).await?; + self.input.key(end, false).await?; + self.input.key(shift, false).await?; + } + NResult::Ok(()) + } + .await; + let _ = self.input.key(shift, false).await; + let _ = self.input.key(ctrl, false).await; + select?; + self.input_target(t, false).await?; + if !focused_inside(self).await { + return Err(fail("Keyboard focus changed during text entry. Check the field before retrying.")); + } + self.input.type_text(text).await?; + let normalize = |s: &str| s.replace("\r\n", "\n"); + let deadline = Instant::now() + Duration::from_millis((1200 + 4 * len as u64).min(5000)); + loop { + self.input_target(t, false).await?; + if self.a11y.value(&node, 16001).await.is_some_and(|v| normalize(&v) == normalize(&expected)) { + return Ok(()); + } + if Instant::now() >= deadline { + return Err(fail("Text entry could not be verified. Check the field before retrying.")); + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + } + + /// Best-effort release of held keys and a button (never fails). + pub async fn release(&self, keys: &[String], button: Option