//! AT-SPI, the Linux equivalent of UI Automation (ported from `capri_linux/atspi_tree.py`). //! A window's accessible tree is read once into a [`Tree`] snapshot (bounded BFS); all control //! classification is pure code over that snapshot. Live calls (focus, set text, invoke, value, //! hit test) go through [`Accessibility`]. Element id = `""`. use std::collections::HashMap; use std::time::{Duration, Instant}; use async_trait::async_trait; use atspi::proxy::accessible::{AccessibleProxy, ObjectRefExt}; use atspi::proxy::component::ComponentProxy; use atspi::{CoordType, Interface, InterfaceSet, ObjectRefOwned, Role, State, StateSet}; use capri_perception::imaging::Rect; use capri_perception::platform::DesktopWindow; use parking_lot::Mutex; use regex::Regex; use serde::Serialize; #[derive(Clone, Debug)] pub struct Node { pub id: String, pub bus: String, pub path: String, pub parent: Option, pub role: Role, pub name: String, pub states: StateSet, pub interfaces: InterfaceSet, /// Global desktop pixels. pub rect: Option, pub accessible_id: String, /// Text/Value contents for fields, combo boxes, sliders and unnamed text (bounded). pub value: Option, } impl Node { pub fn has(&self, s: State) -> bool { self.states.contains(s) } } /// Snapshot of one window's tree; `nodes[0]` is the frame. #[derive(Clone, Debug)] pub struct Tree { pub nodes: Vec, pub pid: u32, /// Process is a web browser (address-bar heuristics). pub browser: bool, } /// One observed control in the native helper's shape. #[derive(Clone, Debug, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Control { pub id: String, pub untrusted_name: String, pub untrusted_value: String, #[serde(rename = "type")] pub kind: String, pub automation_id: String, pub x: i32, pub y: i32, pub image_candidate: bool, pub editable: bool, pub focused: bool, pub browser_address: bool, pub browser_search: bool, pub page_content: bool, pub hovered: bool, pub selected: Option, } fn clip(s: &str, n: usize) -> String { s.chars().take(n).collect() } pub fn base_type(role: Role) -> &'static str { use Role::*; match role { Button | ToggleButton => "Button", Link => "Hyperlink", PageTab => "TabItem", MenuItem | CheckMenuItem | RadioMenuItem | Menu => "MenuItem", CheckBox => "CheckBox", RadioButton => "RadioButton", ComboBox => "ComboBox", ListItem => "ListItem", TreeItem => "TreeItem", TableCell => "DataItem", Slider => "Slider", Label | Static | Paragraph | Heading | Text | Caption => "Text", Image | Icon => "Image", Entry | PasswordText | Terminal => "Edit", SpinButton => "Spinner", DocumentWeb | DocumentFrame | DocumentText => "Document", Frame | Window | Dialog => "Window", ToolBar => "ToolBar", MenuBar => "MenuBar", List => "List", Tree => "Tree", Table => "Table", Panel => "Pane", Section | Grouping => "Group", ScrollBar => "ScrollBar", StatusBar => "StatusBar", _ => "Custom", } } fn is_document(r: Role) -> bool { matches!(r, Role::DocumentWeb | Role::DocumentFrame) } fn is_top(r: Role) -> bool { matches!(r, Role::Frame | Role::Window | Role::Dialog) } /// Real, enabled, writable, non-password text field (Chromium rich editors expose Text only). pub fn editable(n: &Node) -> bool { use Role::*; let roles = matches!(n.role, Entry | Text | ComboBox | DocumentWeb | DocumentFrame | DocumentText | SpinButton | Paragraph | Section | Terminal); roles && n.has(State::Editable) && !n.has(State::ReadOnly) && (n.has(State::Enabled) || n.has(State::Sensitive)) && (n.interfaces.contains(Interface::EditableText) || n.has(State::Focusable)) && n.interfaces.contains(Interface::Text) } pub fn control_type(n: &Node) -> String { let base = base_type(n.role); let edit = editable(n) && (base == "Custom" || matches!(n.role, Role::Text | Role::Paragraph | Role::Section)); format!("ControlType.{}", if edit { "Edit" } else { base }) } static SECRET: std::sync::LazyLock = std::sync::LazyLock::new(|| Regex::new(r"(?i)password|token|secret|api.?key|mot de passe|парол|секрет").unwrap()); static ADDRESS_NAME: std::sync::LazyLock = std::sync::LazyLock::new(|| Regex::new(r"(?i)address|adresse|url|search or enter|rechercher ou saisir").unwrap()); static SEARCH_ID: std::sync::LazyLock = std::sync::LazyLock::new(|| Regex::new(r"(?i)^(?:q|search|searchbox|APjFqb)$").unwrap()); static SEARCH_NAME: std::sync::LazyLock = std::sync::LazyLock::new(|| { Regex::new(r"(?i)^(?:search|search query|search Google|search the web|rechercher|recherche|поиск|найти|поисковый запрос|suchen|buscar|cerca|pesquisar|szukaj|пошук|بحث|搜索|検索|검색)$").unwrap() }); impl Tree { pub fn find(&self, id: &str) -> Option { (!id.is_empty()).then(|| self.nodes.iter().position(|n| n.id == id)).flatten() } fn ancestors(&self, i: usize) -> impl Iterator + '_ { std::iter::successors(self.nodes[i].parent, move |p| self.nodes[*p].parent) } /// `i` is `ancestor` or below it. pub fn within(&self, i: usize, ancestor: usize) -> bool { i == ancestor || self.ancestors(i).any(|a| a == ancestor) } pub fn focused(&self) -> Option { self.nodes.iter().position(|n| n.has(State::Focused)) } pub fn modal(&self) -> bool { self.nodes.first().is_some_and(|f| f.has(State::Modal) || f.role == Role::Dialog) } pub fn in_document(&self, i: usize) -> bool { for a in std::iter::once(i).chain(self.ancestors(i)) { if is_document(self.nodes[a].role) { return true; } if is_top(self.nodes[a].role) { return false; } } false } /// Browser address bar: inside a toolbar (or address/urlbar id, or address-like name), not in a page. pub fn browser_address(&self, i: usize) -> bool { if !self.browser { return false; } let mut toolbar = false; for a in std::iter::once(i).chain(self.ancestors(i)) { let n = &self.nodes[a]; if is_document(n.role) { return false; } let id = n.accessible_id.to_lowercase(); toolbar |= n.role == Role::ToolBar || id.contains("address") || id.contains("urlbar"); } toolbar || ADDRESS_NAME.is_match(&self.nodes[i].name) } pub fn web_search_field(&self, i: usize) -> bool { SEARCH_ID.is_match(&self.nodes[i].accessible_id) || SEARCH_NAME.is_match(&self.nodes[i].name) } /// One control for the observation, or `None` to skip it. pub fn describe(&self, i: usize, pointer: (i32, i32), focused_id: &str) -> Option { let n = &self.nodes[i]; if !n.has(State::Showing) || n.role == Role::PasswordText || !(n.has(State::Enabled) || n.has(State::Sensitive)) { return None; } let r = n.rect?; let is_edit = editable(n); let kind = control_type(n); let wanted = ["Button", "Hyperlink", "TabItem", "MenuItem", "CheckBox", "RadioButton", "ComboBox", "ListItem", "TreeItem", "Slider", "Text", "Image", "DataItem"]; if !is_edit && !wanted.iter().any(|w| kind.ends_with(&format!(".{w}"))) { return None; } let mut label = n.name.clone(); if label.trim().is_empty() && !is_edit { if kind != "ControlType.Text" { return None; } label = clip(n.value.as_deref().unwrap_or(""), 100); if label.trim().is_empty() { return None; } } let address = is_edit && self.browser_address(i); let page = self.in_document(i); let shown = if !SECRET.is_match(&label) && (is_edit || kind == "ControlType.ComboBox" || kind == "ControlType.Slider") { clip(n.value.as_deref().unwrap_or(""), if address { 2048 } else { 500 }) } else { String::new() }; let selected = if n.has(State::Selectable) { Some(n.has(State::Selected)) } else if kind == "ControlType.CheckBox" || kind == "ControlType.RadioButton" { Some(n.has(State::Checked)) } else { None }; Some(Control { id: n.id.clone(), untrusted_name: clip(&label, 100), untrusted_value: shown, automation_id: clip(&n.accessible_id, 100), x: r.x + r.width as i32 / 2, y: r.y + r.height as i32 / 2, image_candidate: kind == "ControlType.Image" && r.width >= 96 && r.height >= 80, editable: is_edit, focused: n.id == focused_id || n.has(State::Focused), browser_address: address, browser_search: is_edit && !address && page && self.web_search_field(i), page_content: page, hovered: r.contains(pointer.0, pointer.1), selected, kind, }) } /// Observation controls: <= 200 collected, ranked, cut to <= 140 and <= 50 000 JSON bytes. pub fn controls(&self, pointer: (i32, i32)) -> (Vec, bool) { let focused = self.focused().map(|i| self.nodes[i].id.clone()).unwrap_or_default(); let mut all: Vec = (1..self.nodes.len()).filter_map(|i| self.describe(i, pointer, &focused)).take(200).collect(); static IMAGES: std::sync::LazyLock = std::sync::LazyLock::new(|| Regex::new(r"(?i)^(?:Images|Картинки|Изображения|Bilder|Imágenes|Imagens)$").unwrap()); let rank = |c: &Control| -> u8 { if c.focused { 0 } else if c.browser_address { 2 } else if IMAGES.is_match(&c.untrusted_name) || c.image_candidate { 5 } else if c.kind == "ControlType.Text" { 8 } else { 6 } }; all.sort_by_key(rank); let total = all.len(); let mut size = 0; let mut kept = vec![]; for c in all { let len = serde_json::to_vec(&c).map(|v| v.len() + 1).unwrap_or(usize::MAX); if kept.len() >= 140 || size + len > 50_000 { break; } size += len; kept.push(c); } let truncated = kept.len() < total; (kept, truncated) } /// Hit check: the deepest accessible at the point is the element (or inside it), or a /// button-like element containing it. `None` chain = toolkit without hit testing. pub fn hit_matches(&self, element: usize, x: i32, y: i32, chain: Option<&[String]>) -> bool { let Some(r) = self.nodes[element].rect.filter(|r| r.contains(x, y)) else { return false }; let _ = r; let Some(chain) = chain.filter(|c| !c.is_empty()) else { return true }; let id = &self.nodes[element].id; if chain.iter().any(|c| c == id) { return true; } // A control drawn inside the target (YouTube Music shows a play button over a hovered row) // still receives the click within the target. if chain.iter().filter_map(|c| self.find(c)).any(|h| h != element && self.within(h, element)) { return true; } let hit = chain.last().and_then(|h| self.find(h)); hit.is_some_and(|h| { let kind = control_type(&self.nodes[h]); ["Button", "Hyperlink", "ListItem", "DataItem"].iter().any(|k| kind.ends_with(k)) && self.within(element, h) }) } } /// Live accessibility operations. #[async_trait] pub trait Accessibility: Send + Sync { /// Snapshot of the window's tree (`limit` nodes, `timeout`), `None` = no accessible frame. async fn tree(&self, window: &DesktopWindow, relative: bool, browser: bool, limit: usize, timeout: Duration) -> Option; async fn focus(&self, node: &Node) -> bool; async fn set_text(&self, node: &Node, text: &str) -> bool; async fn invoke(&self, node: &Node) -> bool; /// Current text (rich-editor padding stripped) or numeric value. async fn value(&self, node: &Node, limit: usize) -> Option; /// Ids from the frame down to the deepest accessible at a global point. async fn at_point(&self, tree: &Tree, window: &DesktopWindow, relative: bool, x: i32, y: i32) -> Option>; } pub struct Atspi { conn: zbus::Connection, pids: Mutex>, } impl Atspi { /// Sets `org.a11y.Status.IsEnabled` (Qt, Chromium and Firefox then expose trees; apps started /// earlier may need a restart) and connects to the accessibility bus. pub async fn connect() -> anyhow::Result { let _ = atspi::connection::set_session_accessibility(true).await; // A plain connection to the accessibility bus (no registry/peer bookkeeping needed). let session = zbus::Connection::session().await?; let address: String = session.call_method(Some("org.a11y.Bus"), "/org/a11y/bus", Some("org.a11y.Bus"), "GetAddress", &()).await?.body().deserialize()?; let conn = zbus::connection::Builder::address(address.as_str())?.build().await?; Ok(Self { conn, pids: Mutex::default() }) } async fn pid(&self, bus: &str) -> u32 { if let Some(p) = self.pids.lock().get(bus) { return *p; } let pid = async { let dbus = zbus::fdo::DBusProxy::new(&self.conn).await.ok()?; dbus.get_connection_unix_process_id(zbus::names::BusName::try_from(bus).ok()?).await.ok() } .await .unwrap_or(0); self.pids.lock().insert(bus.into(), pid); pid } async fn accessible(&self, bus: &str, path: &str) -> Option> { AccessibleProxy::builder(&self.conn).destination(bus.to_string()).ok()?.path(path.to_string()).ok()?.cache_properties(zbus::proxy::CacheProperties::No).build().await.ok() } async fn component(&self, bus: &str, path: &str) -> Option> { ComponentProxy::builder(&self.conn).destination(bus.to_string()).ok()?.path(path.to_string()).ok()?.cache_properties(zbus::proxy::CacheProperties::No).build().await.ok() } async fn node(&self, r: &ObjectRefOwned, pid: u32, parent: Option, origin: Option<(i32, i32)>) -> Option { let bus = r.name_as_str()?.to_string(); let path = r.path_as_str().to_string(); let p = r.as_accessible_proxy(&self.conn).await.ok()?; let role = p.get_role().await.ok()?; let states = p.get_state().await.unwrap_or_else(|_| StateSet::empty()); let interfaces = p.get_interfaces().await.unwrap_or_else(|_| InterfaceSet::empty()); let name = p.name().await.unwrap_or_default(); let accessible_id = p.accessible_id().await.unwrap_or_default(); let mut rect = None; if interfaces.contains(Interface::Component) && let Some(c) = self.component(&bus, &path).await && let Ok((x, y, w, h)) = c.get_extents(if origin.is_some() { CoordType::Window } else { CoordType::Screen }).await && w > 0 && h > 0 { let (ox, oy) = origin.unwrap_or((0, 0)); rect = Some(Rect { x: x + ox, y: y + oy, width: w as u32, height: h as u32 }); } let mut node = Node { id: format!("{pid}{path}"), bus, path, parent, role, name, states, interfaces, rect, accessible_id, value: None }; let wants_value = editable(&node) || matches!(role, Role::ComboBox | Role::Slider) || (base_type(role) == "Text" && node.name.trim().is_empty()); if wants_value { node.value = self.value(&node, 8001).await; } Some(node) } /// The accessible top-level matching a compositor window (title, then ACTIVE, then sole, then SHOWING). async fn frame(&self, window: &DesktopWindow) -> Option { let root = self.accessible("org.a11y.atspi.Registry", "/org/a11y/atspi/accessible/root").await?; let mut candidates: Vec<(ObjectRefOwned, String, StateSet)> = vec![]; for app in root.get_children().await.ok()?.into_iter().take(400) { let Some(bus) = app.name_as_str() else { continue }; if self.pid(bus).await != window.pid { continue; } let Ok(proxy) = app.as_accessible_proxy(&self.conn).await else { continue }; for top in proxy.get_children().await.unwrap_or_default().into_iter().take(60) { let Ok(t) = top.as_accessible_proxy(&self.conn).await else { continue }; if t.get_role().await.is_ok_and(is_top) { let (name, states) = (t.name().await.unwrap_or_default(), t.get_state().await.unwrap_or_else(|_| StateSet::empty())); candidates.push((top.clone(), name, states)); } } } pick_frame(&window.title, candidates.iter().map(|c| (c.1.as_str(), c.2)).collect::>().as_slice()).map(|i| candidates[i].0.clone()) } } /// Frame choice over (name, states) candidates; NBSP/whitespace-insensitive title match. pub fn pick_frame(title: &str, candidates: &[(&str, StateSet)]) -> Option { let norm = |s: &str| s.split_whitespace().collect::>().join(" "); let t = norm(title); let exact: Vec = (0..candidates.len()).filter(|i| !t.is_empty() && norm(candidates[*i].0) == t).collect(); if exact.len() == 1 { return Some(exact[0]); } let pool: Vec = if exact.is_empty() { (0..candidates.len()).collect() } else { exact }; let active: Vec = pool.iter().copied().filter(|i| candidates[*i].1.contains(State::Active)).collect(); if active.len() == 1 { return Some(active[0]); } if candidates.len() == 1 { return Some(0); } let showing: Vec = pool.into_iter().filter(|i| candidates[*i].1.contains(State::Showing)).collect(); (showing.len() == 1).then(|| showing[0]) } #[async_trait] impl Accessibility for Atspi { async fn tree(&self, window: &DesktopWindow, relative: bool, browser: bool, limit: usize, timeout: Duration) -> Option { let started = Instant::now(); let frame = self.frame(window).await?; let origin = relative.then_some(window.client); let mut nodes = vec![self.node(&frame, window.pid, None, origin).await?]; let mut queue = std::collections::VecDeque::from([(0usize, frame)]); 'walk: while let Some((index, r)) = queue.pop_front() { let Ok(proxy) = r.as_accessible_proxy(&self.conn).await else { continue }; for child in proxy.get_children().await.unwrap_or_default().into_iter().take(200) { if nodes.len() > limit || started.elapsed() > timeout { break 'walk; } let Some(node) = self.node(&child, window.pid, Some(index), origin).await else { continue }; // Hidden subtrees are pruned (heavy pages exhaust the budget otherwise). let descend = node.has(State::Showing) || is_top(node.role); nodes.push(node); if descend { queue.push_back((nodes.len() - 1, child)); } } } Some(Tree { nodes, pid: window.pid, browser }) } async fn focus(&self, node: &Node) -> bool { match self.component(&node.bus, &node.path).await { Some(c) => c.grab_focus().await.unwrap_or(false), None => false, } } async fn set_text(&self, node: &Node, text: &str) -> bool { let Ok(b) = atspi::proxy::editable_text::EditableTextProxy::builder(&self.conn).destination(node.bus.clone()) else { return false }; let Ok(b) = b.path(node.path.clone()) else { return false }; match b.cache_properties(zbus::proxy::CacheProperties::No).build().await { Ok(p) => p.set_text_contents(text).await.unwrap_or(false), Err(_) => false, } } async fn invoke(&self, node: &Node) -> bool { let Ok(b) = atspi::proxy::action::ActionProxy::builder(&self.conn).destination(node.bus.clone()) else { return false }; let Ok(b) = b.path(node.path.clone()) else { return false }; let Ok(p) = b.cache_properties(zbus::proxy::CacheProperties::No).build().await else { return false }; let n = p.n_actions().await.unwrap_or(0); for i in 0..n { let name = p.get_name(i).await.unwrap_or_default().to_lowercase(); if matches!(name.as_str(), "click" | "press" | "activate" | "jump" | "") { return p.do_action(i).await.unwrap_or(false); } } n > 0 && p.do_action(0).await.unwrap_or(false) } async fn value(&self, node: &Node, limit: usize) -> Option { if node.interfaces.contains(Interface::Text) { let p = atspi::proxy::text::TextProxy::builder(&self.conn).destination(node.bus.clone()).ok()?.path(node.path.clone()).ok()?.cache_properties(zbus::proxy::CacheProperties::No).build().await.ok()?; let count = p.character_count().await.ok()?.max(0) as usize; let raw = p.get_text(0, count.min(limit) as i32).await.ok()?; let rich = !node.interfaces.contains(Interface::EditableText) && node.has(State::Editable); return Some(if rich { raw.replace(['\u{feff}', '\u{fffc}'], "").trim_end_matches('\n').to_string() } else { raw }); } if node.interfaces.contains(Interface::Value) { let p = atspi::proxy::value::ValueProxy::builder(&self.conn).destination(node.bus.clone()).ok()?.path(node.path.clone()).ok()?.cache_properties(zbus::proxy::CacheProperties::No).build().await.ok()?; return p.current_value().await.ok().map(|v| v.to_string()); } None } async fn at_point(&self, tree: &Tree, window: &DesktopWindow, relative: bool, x: i32, y: i32) -> Option> { let frame = tree.nodes.first()?; let (px, py, coord) = if relative { (x - window.client.0, y - window.client.1, CoordType::Window) } else { (x, y, CoordType::Screen) }; let (mut bus, mut path) = (frame.bus.clone(), frame.path.clone()); let mut chain = vec![frame.id.clone()]; for _ in 0..40 { let c = self.component(&bus, &path).await?; let Ok(next) = c.get_accessible_at_point(px, py, coord).await else { break }; if next.is_null() || next.path_as_str() == path { break; } bus = next.name_as_str()?.to_string(); path = next.path_as_str().to_string(); chain.push(format!("{}{}", tree.pid, path)); } (chain.len() > 1).then_some(chain) } } #[cfg(test)] pub mod tests { use super::*; pub fn node(id: &str, parent: Option, role: Role, name: &str, states: &[State], ifaces: &[Interface], rect: (i32, i32, u32, u32)) -> Node { let mut s = StateSet::empty(); states.iter().for_each(|x| s.insert(*x)); let mut i = InterfaceSet::empty(); ifaces.iter().for_each(|x| i.insert(*x)); Node { id: id.into(), bus: ":1.5".into(), path: id.into(), parent, role, name: name.into(), states: s, interfaces: i, rect: Some(Rect { x: rect.0, y: rect.1, width: rect.2, height: rect.3 }), accessible_id: String::new(), value: None } } /// A browser window: toolbar address bar, a page with a search field and a button. pub fn browser_tree() -> Tree { use Interface::*; use State::*; let vis = [Showing, Enabled]; let mut address = node("9/a", Some(1), Role::Entry, "Search or enter address", &[Showing, Enabled, Editable, Focusable], &[Text, EditableText, Component], (100, 40, 600, 30)); address.value = Some("https://www.google.com/".into()); let mut search = node("9/s", Some(2), Role::Entry, "Search", &[Showing, Enabled, Editable, Focusable, Focused], &[Text, EditableText, Component], (300, 300, 400, 40)); search.value = Some(String::new()); Tree { nodes: vec![ node("9/f", None, Role::Frame, "Google — Firefox", &vis, &[Component], (0, 0, 1280, 800)), node("9/t", Some(0), Role::ToolBar, "Navigation", &vis, &[Component], (0, 30, 1280, 50)), node("9/d", Some(0), Role::DocumentWeb, "Google", &vis, &[Component, Text], (0, 80, 1280, 720)), address, search, node("9/b", Some(2), Role::Button, "Google Search", &vis, &[Component, Action], (300, 360, 120, 30)), node("9/p", Some(2), Role::PasswordText, "Password", &[Showing, Enabled, Editable], &[Text, Component], (0, 0, 10, 10)), node("9/h", Some(2), Role::Button, "Hidden", &[Enabled], &[Component], (0, 0, 10, 10)), ], pid: 9, browser: true, } } #[test] fn classification() { let mut t = browser_tree(); t.nodes.swap(3, 3); // parents of address/search point at toolbar (1) and document (2) assert!(editable(&t.nodes[3]) && t.browser_address(3) && !t.in_document(3)); assert!(!t.browser_address(4) && t.in_document(4) && t.web_search_field(4)); let (controls, truncated) = t.controls((310, 310)); assert!(!truncated); let ids: Vec<&str> = controls.iter().map(|c| c.id.as_str()).collect(); assert_eq!(ids, vec!["9/s", "9/a", "9/b"], "focused first, password and hidden skipped"); let s = &controls[0]; assert!(s.focused && s.browser_search && s.page_content && s.hovered && s.kind == "ControlType.Edit"); assert_eq!(controls[1].untrusted_value, "https://www.google.com/"); assert_eq!((controls[2].x, controls[2].y), (360, 375)); assert!(!t.modal()); t.browser = false; assert!(!t.browser_address(3)); } #[test] fn secrets_and_hits() { let mut t = browser_tree(); t.nodes[3].name = "API key".into(); let c = t.describe(3, (0, 0), "").unwrap(); assert_eq!(c.untrusted_value, "", "secret-named fields are never read"); assert!(t.hit_matches(5, 310, 370, None), "no hit testing: bounds are the evidence"); assert!(t.hit_matches(5, 310, 370, Some(&["9/f".into(), "9/d".into(), "9/b".into()]))); assert!(!t.hit_matches(5, 310, 370, Some(&["9/f".into(), "9/d".into()])), "covered by its document"); assert!(!t.hit_matches(5, 0, 0, None), "outside bounds"); } #[test] fn frame_choice() { let active = StateSet::new(State::Active); let none = StateSet::empty(); assert_eq!(pick_frame("YouTube Music", &[("YouTube\u{a0}Music", none), ("Other", active)]), Some(0)); assert_eq!(pick_frame("x", &[("A", none), ("B", active)]), Some(1)); assert_eq!(pick_frame("x", &[("A", none)]), Some(0)); assert_eq!(pick_frame("x", &[("A", none), ("B", none)]), None, "ambiguous: no controls"); } }