//! Windows-only UIA implementation for [`super::UiaSurface`]. //! //! UIA is a COM API. The [`IUIAutomation`] handle is `!Send`, so we own a //! dedicated worker thread that: //! //! 1. Initializes COM in the multi-threaded apartment (MTA). //! 2. Creates the `CUIAutomation` singleton and keeps the `IUIAutomation` //! handle alive on this thread. //! 3. Receives `WorkerCmd`s over a `mpsc` channel and dispatches them. //! 4. Tears COM down cleanly when the channel closes or `Shutdown` arrives. //! //! Concurrent callers are serialized through the channel, which matches //! UIA's effective threading model anyway. See `docs/uia-mapping.md` §10. #![cfg(target_os = "windows")] use std::collections::HashMap; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{self, RecvTimeoutError}; use std::sync::Mutex; use std::thread::{self, JoinHandle}; use std::time::{Duration, SystemTime}; use windows::core::Result as WinResult; use windows::core::{BSTR, VARIANT}; use windows::Win32::Foundation::LPARAM; use windows::Win32::Foundation::{CloseHandle, BOOL, HANDLE, HGLOBAL, HWND, POINT, RECT}; use windows::Win32::Graphics::Gdi::{ BitBlt, CreateCompatibleBitmap, CreateCompatibleDC, DeleteDC, DeleteObject, GetDIBits, GetWindowDC, ReleaseDC, SelectObject, BITMAPINFO, BITMAPINFOHEADER, BI_RGB, DIB_RGB_COLORS, HGDIOBJ, RGBQUAD, SRCCOPY, }; use windows::Win32::System::Com::{ CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED, SAFEARRAY, }; use windows::Win32::System::DataExchange::{ CloseClipboard, EmptyClipboard, GetClipboardData, OpenClipboard, SetClipboardData, }; use windows::Win32::System::Memory::{GlobalAlloc, GlobalLock, GlobalUnlock, GMEM_MOVEABLE}; use windows::Win32::System::Ole::{ SafeArrayAccessData, SafeArrayDestroy, SafeArrayGetLBound, SafeArrayGetUBound, SafeArrayUnaccessData, CF_UNICODETEXT, }; use windows::Win32::System::Threading::{ AttachThreadInput, GetCurrentThreadId, OpenProcess, QueryFullProcessImageNameW, PROCESS_NAME_FORMAT, PROCESS_QUERY_LIMITED_INFORMATION, }; use windows::Win32::UI::Accessibility::{ CUIAutomation, ExpandCollapseState_Collapsed, ExpandCollapseState_Expanded, ExpandCollapseState_LeafNode, ExpandCollapseState_PartiallyExpanded, IUIAutomation, IUIAutomationCacheRequest, IUIAutomationCondition, IUIAutomationElement, IUIAutomationElementArray, IUIAutomationExpandCollapsePattern, IUIAutomationInvokePattern, IUIAutomationRangeValuePattern, IUIAutomationScrollItemPattern, IUIAutomationSelectionItemPattern, IUIAutomationSelectionPattern, IUIAutomationTogglePattern, IUIAutomationTreeWalker, IUIAutomationValuePattern, IUIAutomationVirtualizedItemPattern, IUIAutomationWindowPattern, ToggleState_Indeterminate, ToggleState_Off, ToggleState_On, TreeScope, TreeScope_Children, TreeScope_Element, TreeScope_Subtree, UIA_AutomationIdPropertyId, UIA_BoundingRectanglePropertyId, UIA_ButtonControlTypeId, UIA_CalendarControlTypeId, UIA_CheckBoxControlTypeId, UIA_ClassNamePropertyId, UIA_ComboBoxControlTypeId, UIA_ControlTypePropertyId, UIA_CustomControlTypeId, UIA_DataGridControlTypeId, UIA_DataItemControlTypeId, UIA_DocumentControlTypeId, UIA_EditControlTypeId, UIA_ExpandCollapsePatternId, UIA_GroupControlTypeId, UIA_HasKeyboardFocusPropertyId, UIA_HeaderControlTypeId, UIA_HeaderItemControlTypeId, UIA_HelpTextPropertyId, UIA_HyperlinkControlTypeId, UIA_ImageControlTypeId, UIA_InvokePatternId, UIA_IsEnabledPropertyId, UIA_IsKeyboardFocusablePropertyId, UIA_IsOffscreenPropertyId, UIA_IsPasswordPropertyId, UIA_IsRequiredForFormPropertyId, UIA_LevelPropertyId, UIA_ListControlTypeId, UIA_ListItemControlTypeId, UIA_MenuBarControlTypeId, UIA_MenuControlTypeId, UIA_MenuItemControlTypeId, UIA_NamePropertyId, UIA_PaneControlTypeId, UIA_ProgressBarControlTypeId, UIA_RadioButtonControlTypeId, UIA_RangeValuePatternId, UIA_ScrollBarControlTypeId, UIA_ScrollItemPatternId, UIA_SelectionItemPatternId, UIA_SelectionPatternId, UIA_SemanticZoomControlTypeId, UIA_SeparatorControlTypeId, UIA_SliderControlTypeId, UIA_SpinnerControlTypeId, UIA_SplitButtonControlTypeId, UIA_StatusBarControlTypeId, UIA_TabControlTypeId, UIA_TabItemControlTypeId, UIA_TableControlTypeId, UIA_TextControlTypeId, UIA_ThumbControlTypeId, UIA_TitleBarControlTypeId, UIA_TogglePatternId, UIA_ToolBarControlTypeId, UIA_ToolTipControlTypeId, UIA_TreeControlTypeId, UIA_TreeItemControlTypeId, UIA_ValuePatternId, UIA_VirtualizedItemPatternId, UIA_WindowControlTypeId, UIA_WindowPatternId, WindowVisualState_Normal, UIA_CONTROLTYPE_ID, UIA_PROPERTY_ID, }; use windows::Win32::UI::HiDpi::{ GetDpiForWindow, SetProcessDpiAwarenessContext, DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2, }; use windows::Win32::UI::Input::KeyboardAndMouse::{ SendInput, INPUT, INPUT_0, INPUT_KEYBOARD, INPUT_MOUSE, KEYBDINPUT, KEYBD_EVENT_FLAGS, KEYEVENTF_KEYUP, KEYEVENTF_UNICODE, MOUSEEVENTF_ABSOLUTE, MOUSEEVENTF_HWHEEL, MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP, MOUSEEVENTF_MIDDLEDOWN, MOUSEEVENTF_MIDDLEUP, MOUSEEVENTF_MOVE, MOUSEEVENTF_RIGHTDOWN, MOUSEEVENTF_RIGHTUP, MOUSEEVENTF_VIRTUALDESK, MOUSEEVENTF_WHEEL, MOUSEINPUT, VIRTUAL_KEY, VK_APPS, VK_BACK, VK_CAPITAL, VK_CONTROL, VK_DELETE, VK_DOWN, VK_END, VK_ESCAPE, VK_HOME, VK_INSERT, VK_LEFT, VK_LWIN, VK_MENU, VK_NEXT, VK_NUMLOCK, VK_PAUSE, VK_PRIOR, VK_RETURN, VK_RIGHT, VK_RWIN, VK_SCROLL, VK_SHIFT, VK_SNAPSHOT, VK_SPACE, VK_TAB, VK_UP, }; use windows::Win32::UI::WindowsAndMessaging::{ EnumWindows, GetForegroundWindow, GetSystemMetrics, GetWindowRect, GetWindowTextLengthW, GetWindowTextW, GetWindowThreadProcessId, IsIconic, IsWindow, IsWindowVisible, SetForegroundWindow, ShowWindow, SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN, SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN, SW_RESTORE, }; use agent_ctrl_core::{ assign_scope_refs, Action, ActionResult, AppContext, Bounds, Checked, ClipboardOp, Error, MouseButton, MouseOp, NativeHandle, Node, RefEntry, RefId, RefMap, Region, Result, Role, ScreenshotTarget, Snapshot, SnapshotOptions, State, SurfaceKind, WindowContext, WindowInfo, WindowTarget, }; // ---------- Worker thread ---------- /// How long to wait for a single UIA worker job before declaring the session /// wedged. A normal snapshot is well under a second; even a heavy app's tree /// walk is a handful of seconds. If a job hasn't finished in this long the /// target application is almost certainly not pumping messages (not /// responding), and the cross-process COM call inside the worker will never /// return - so we give up on the session rather than hang the daemon forever. const CALL_TIMEOUT: Duration = Duration::from_secs(45); /// A unit of work to run on the UIA worker thread. The closure receives the /// worker's mutable state and is responsible for shipping its own result back /// to the caller (typically via a captured `oneshot::Sender`). type WorkerJob = Box; /// Commands the worker thread accepts. enum WorkerCmd { /// Run an arbitrary closure with access to [`WorkerState`]. Run(WorkerJob), /// Cooperative shutdown - drop COM objects and exit the loop. Shutdown, } /// State held by the UIA worker thread. Owns the live COM objects plus the /// `RefMap` and target window from the most recent snapshot for action-time /// re-resolution. struct WorkerState { automation: IUIAutomation, /// Pre-built cache request describing the properties and patterns the /// snapshot walk needs. `BuildUpdatedCache` with this fetches a whole /// window subtree in one cross-process call, after which every per-node /// read (`Cached*` getters, cached pattern accessors) is in-process. /// Without it, a snapshot is O(nodes x properties) COM round-trips, which /// is seconds of latency on Outlook/Excel-scale trees. cache_request: IUIAutomationCacheRequest, /// `RefMap` from the most recent successful snapshot. Replaced wholesale /// each time `snapshot()` runs, so action-time resolution can never use /// stale entries from older snapshots. last_refs: RefMap, /// HWND that the most recent snapshot was taken from. `None` until the /// first snapshot. Subsequent actions resolve elements relative to this /// window, not the foreground (which may have changed in the meantime). last_hwnd: Option, /// Most recent successful snapshot. Used to draw ref labels onto /// annotated screenshots without re-walking UIA. last_snapshot: Option, } /// Owns the worker thread that holds the live UIA session. /// /// Drop sends a `Shutdown` and waits for the worker to exit. If the worker /// has already died the drop is effectively a no-op. If the session has been /// poisoned (a prior call timed out, so the worker is presumed stuck inside an /// unresponsive app's COM call) Drop does *not* join - the thread would never /// return - and instead detaches it so the daemon can move on. pub(crate) struct UiaInner { sender: Mutex>, worker: Option>, /// Set once a worker job exceeds [`CALL_TIMEOUT`]. After that, every call /// fails fast instead of queueing behind the stuck job, and the session /// must be closed and re-opened. poisoned: AtomicBool, } impl UiaInner { /// Spawn the worker, wait for COM/UIA init to succeed (or fail fast). pub(crate) fn new() -> Result { let (cmd_tx, cmd_rx) = mpsc::channel::(); let (ready_tx, ready_rx) = mpsc::channel::>(); let worker = thread::Builder::new() .name("agent-ctrl-uia".into()) .spawn(move || { // Become Per-Monitor-DPI-V2 aware before any window/coordinate // calls. Without this, UIA's physical-pixel `BoundingRectangle` // values would be mixed with DPI-virtualized `GetSystemMetrics` // results, so cursor positioning and screenshots would be wrong // on scaled displays. Process-wide and idempotent; we ignore the // result (FALSE means it was already set, or the OS predates the // API - in which case the host is older than our stated minimum). set_dpi_awareness(); // SAFETY: `CoInitializeEx` is sound to call once per thread. We // pass `None` for the reserved pointer (documented usage) and // `COINIT_MULTITHREADED` because UIA supports MTA and we never // pump a message loop on this thread. let init = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }; if init.is_err() { let _ = ready_tx.send(Err(init.into())); return; } // SAFETY: `CUIAutomation` and `IUIAutomation` are well-known COM // identifiers shipped with Windows. `CLSCTX_INPROC_SERVER` is the // documented activation context for the UIA client library. let automation: IUIAutomation = match unsafe { CoCreateInstance(&CUIAutomation, None, CLSCTX_INPROC_SERVER) } { Ok(a) => a, Err(e) => { let _ = ready_tx.send(Err(e)); // SAFETY: paired with the successful `CoInitializeEx` above. unsafe { CoUninitialize() }; return; } }; let cache_request = match build_cache_request(&automation) { Ok(req) => req, Err(e) => { let _ = ready_tx.send(Err(e)); // SAFETY: paired with the successful `CoInitializeEx` above. unsafe { CoUninitialize() }; return; } }; let _ = ready_tx.send(Ok(())); let mut state = WorkerState { automation, cache_request, last_refs: RefMap::new(), last_hwnd: None, last_snapshot: None, }; while let Ok(cmd) = cmd_rx.recv() { match cmd { WorkerCmd::Run(job) => { // A panic inside one job must not take down the // whole session - the caller of that job already // sees an error (its reply channel was dropped // during the unwind); the next job runs normally. // `WorkerState` is plain data plus a COM pointer // that COM calls leave in a consistent state, so // asserting unwind-safety is sound here. let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { job(&mut state); })); if outcome.is_err() { tracing::error!("UIA worker job panicked; session continues"); } } WorkerCmd::Shutdown => break, } } // Order matters: drop COM interfaces BEFORE `CoUninitialize`, // since releasing an interface after uninit is undefined behavior. drop(state); // SAFETY: paired with the successful `CoInitializeEx` above. unsafe { CoUninitialize() }; }) .map_err(|e| Error::Surface(format!("failed to spawn UIA worker: {e}")))?; // Wait for the worker to finish COM init and report status. match ready_rx.recv_timeout(Duration::from_secs(5)) { Ok(Ok(())) => Ok(Self { sender: Mutex::new(cmd_tx), worker: Some(worker), poisoned: AtomicBool::new(false), }), Ok(Err(e)) => Err(Error::Surface(format!("UIA initialization failed: {e}"))), Err(RecvTimeoutError::Timeout) => Err(Error::Surface( "UIA worker did not complete init in 5s".into(), )), Err(RecvTimeoutError::Disconnected) => { Err(Error::Surface("UIA worker died during init".into())) } } } /// Run a closure on the UIA worker thread and await its result, with the /// default [`CALL_TIMEOUT`]. async fn run(&self, f: F) -> Result where F: FnOnce(&mut WorkerState) -> Result + Send + 'static, R: Send + 'static, { self.run_with_timeout(CALL_TIMEOUT, f).await } /// Run a closure on the UIA worker thread and await its result, giving up /// after `timeout`. /// /// The closure receives a mutable reference to [`WorkerState`], giving it /// access to the live `IUIAutomation` and the most recent snapshot's refs. /// COM safety: the closure runs *on* the worker thread, so it can use /// `!Send` UIA types freely. Only the returned `R` (which must be `Send`) /// crosses thread boundaries. /// /// If the worker doesn't reply within `timeout` the session is poisoned: /// the in-flight job is abandoned (it is presumed stuck in a COM call to an /// unresponsive app and will never return), every subsequent call fails /// fast, and the caller must close and re-open the session. async fn run_with_timeout(&self, timeout: Duration, f: F) -> Result where F: FnOnce(&mut WorkerState) -> Result + Send + 'static, R: Send + 'static, { if self.poisoned.load(Ordering::Acquire) { return Err(Error::Surface( "UIA session is wedged - a prior call to an unresponsive app timed out; close and re-open this session".into(), )); } let (reply_tx, reply_rx) = tokio::sync::oneshot::channel(); let job: WorkerJob = Box::new(move |state| { let _ = reply_tx.send(f(state)); }); // Send the job. Brief lock; released before the await. let send_result = match self.sender.lock() { Ok(sender) => sender.send(WorkerCmd::Run(job)), Err(_) => return Err(Error::Surface("UIA worker sender mutex poisoned".into())), }; if send_result.is_err() { return Err(Error::Surface("UIA worker is no longer running".into())); } match tokio::time::timeout(timeout, reply_rx).await { Ok(Ok(result)) => result, Ok(Err(_)) => Err(Error::Surface("UIA worker dropped reply channel".into())), Err(_elapsed) => { self.poisoned.store(true, Ordering::Release); Err(Error::Surface(format!( "UIA call timed out after {}s - the target application is not responding; close and re-open this session", timeout.as_secs() ))) } } } /// Capture a snapshot of the foreground window. pub(crate) async fn snapshot(&self, opts: &SnapshotOptions) -> Result { let opts = opts.clone(); self.run(move |state| capture_foreground(state, &opts)) .await } /// Capture the pinned window without replacing action-time refs. pub(crate) async fn snapshot_for_observation( &self, opts: &SnapshotOptions, ) -> Result { let opts = opts.clone(); self.run(move |state| { let hwnd = state.last_hwnd.ok_or_else(|| { Error::Snapshot( "no snapshot committed for this session - run `agent-ctrl snapshot` first" .into(), ) })?; capture_with_options(&state.automation, &state.cache_request, &opts, hwnd) }) .await } /// Promote an observation capture to the action-time snapshot. pub(crate) async fn commit_observation(&self, snapshot: &Snapshot) -> Result<()> { let snapshot = snapshot.clone(); self.run(move |state| { if snapshot.surface_kind != SurfaceKind::Uia { return Err(Error::Surface( "cannot commit a non-UIA observation to a UIA session".into(), )); } state.last_refs = snapshot.refs.clone(); state.last_snapshot = Some(snapshot); Ok(()) }) .await } /// Execute an action against the most recent snapshot's refs. pub(crate) async fn act(&self, action: Action) -> Result { // `Action::Wait { ms }` deliberately blocks the worker for `ms`, so its // call budget is the requested sleep plus the usual headroom; every // other action gets the default. let timeout = match action { Action::Wait { ms } => Duration::from_millis(ms).saturating_add(CALL_TIMEOUT), _ => CALL_TIMEOUT, }; self.run_with_timeout(timeout, move |state| act_dispatch(state, &action)) .await } /// Enumerate all visible top-level windows owned by the same process as /// the session's pinned window. Mirrors agent-browser's tab_list shape. pub(crate) async fn list_windows(&self) -> Result> { self.run(list_windows_inner).await } } impl Drop for UiaInner { fn drop(&mut self) { if let Ok(sender) = self.sender.lock() { let _ = sender.send(WorkerCmd::Shutdown); } let Some(worker) = self.worker.take() else { return; }; if self.poisoned.load(Ordering::Acquire) { // The worker is stuck in a COM call that will never return; joining // would hang this thread too. Detach it (dropping the handle) and // let the OS reap it when the process exits. drop(worker); return; } let _ = worker.join(); } } // ---------- Snapshot pieces ---------- /// Element properties fetched in bulk by [`build_cache_request`]; every one is /// then read per node from the local cache with no COM round-trip - either via /// a typed `Cached*` getter, or, for `Level` (which has no typed getter), via /// `GetCachedPropertyValue`. Must be kept in sync with the cache reads in /// [`build_node`]. const CACHED_PROPERTIES: [UIA_PROPERTY_ID; 13] = [ UIA_ControlTypePropertyId, UIA_NamePropertyId, UIA_ClassNamePropertyId, UIA_AutomationIdPropertyId, UIA_IsEnabledPropertyId, UIA_IsOffscreenPropertyId, UIA_HasKeyboardFocusPropertyId, UIA_IsKeyboardFocusablePropertyId, UIA_IsPasswordPropertyId, UIA_BoundingRectanglePropertyId, UIA_IsRequiredForFormPropertyId, UIA_HelpTextPropertyId, UIA_LevelPropertyId, ]; /// Build the per-session [`IUIAutomationCacheRequest`]. `BuildUpdatedCache` /// with this fetches a whole window subtree's properties in one cross-process /// call; afterwards the snapshot walk reads everything via in-process `Cached*` /// getters. The tree filter mirrors the Control view so `GetCachedChildren` /// returns the same node set `ControlViewWalker` would (see docs §9). The tree /// scope is set per-snapshot from [`SnapshotOptions::depth`]. fn build_cache_request(automation: &IUIAutomation) -> WinResult { // SAFETY: `automation` is a valid COM interface; these are config calls // with no out-of-band pointers. let req = unsafe { automation.CreateCacheRequest() }?; let control_view = unsafe { automation.ControlViewCondition() }?; unsafe { req.SetTreeFilter(&control_view) }?; for prop in CACHED_PROPERTIES { unsafe { req.AddProperty(prop) }?; } Ok(req) } /// Pick the cache scope that fetches just enough of the tree for `depth`. /// `Some(0)` -> the root only; `Some(1)` -> root plus direct children; deeper /// or unbounded -> the whole subtree (the walk then trims to `depth`). const fn cache_scope_for_depth(depth: Option) -> TreeScope { match depth { Some(0) => TreeScope_Element, Some(1) => TreeScope_Children, _ => TreeScope_Subtree, } } /// Build a [`Snapshot`] for the targeted window and store its refs + HWND /// on the [`WorkerState`] for subsequent action-time re-resolution. fn capture_foreground(state: &mut WorkerState, opts: &SnapshotOptions) -> Result { let hwnd = resolve_target_hwnd(&opts.target)?; let snap = capture_with_options(&state.automation, &state.cache_request, opts, hwnd)?; state.last_refs = snap.refs.clone(); state.last_hwnd = Some(hwnd); state.last_snapshot = Some(snap.clone()); Ok(snap) } fn capture_with_options( automation: &IUIAutomation, cache_request: &IUIAutomationCacheRequest, opts: &SnapshotOptions, hwnd: HWND, ) -> Result { // SAFETY: `hwnd` is either a valid window handle or null; `ElementFromHandle` // is documented to return an error in the latter case rather than dereferencing. let root_element = unsafe { automation.ElementFromHandle(hwnd) } .map_err(|e| Error::Snapshot(format!("ElementFromHandle: {e}")))?; // Capture per-window DPI once; we apply the same factor to every node's // bounds since they all live in the same window. See docs §6. let dpi_scale = window_dpi_scale(hwnd); // Pull the whole (Control-view-filtered) subtree into a local cache in one // round-trip; every `Cached*` read below is then in-process. See docs §9. // SAFETY: `cache_request` and `root_element` are valid COM interfaces. unsafe { cache_request.SetTreeScope(cache_scope_for_depth(opts.depth)) } .map_err(|e| Error::Snapshot(format!("CacheRequest::SetTreeScope: {e}")))?; let root_element = unsafe { root_element.BuildUpdatedCache(cache_request) } .map_err(|e| Error::Snapshot(format!("BuildUpdatedCache: {e}")))?; let mut refs = RefMap::new(); // `nth_seen` tracks `(role, name) → count` *globally* across the whole // snapshot in pre-order DFS. The action-time walker mirrors this exactly // so it can rediscover any element the agent references. let mut nth_seen: HashMap<(Role, String), usize> = HashMap::new(); let (mut root, root_signals) = build_node(&root_element, None, dpi_scale); if qualifies_for_ref(&root.role, &root_signals) { let key = (root.role.clone(), root.name.clone()); let counter = nth_seen.entry(key).or_insert(0); let nth = *counter; *counter += 1; let id = refs.insert( root.role.clone(), root.name.clone(), nth, root.native.clone(), ); root.ref_id = Some(id); } root.children = walk_children(&root_element, &mut refs, &mut nth_seen, 1, opts, dpi_scale)?; assign_scope_refs(&mut root); let window_title = if root.name.is_empty() { None } else { Some(root.name.clone()) }; // SAFETY: `root_element` is a valid COM interface. let pid_signed = unsafe { root_element.CurrentProcessId() } .map_err(|e| Error::Snapshot(format!("CurrentProcessId: {e}")))?; let pid = u32::try_from(pid_signed) .map_err(|_| Error::Snapshot(format!("invalid PID from UIA: {pid_signed}")))?; // The window may belong to a protected or higher-integrity process we // cannot `OpenProcess` (a system service, an elevated app driven from an // unelevated agent). The accessibility tree is still valid and is the // point of the snapshot, so degrade the app context to a pid placeholder // rather than failing the whole capture. let (app_id, app_name) = process_info(pid).unwrap_or_else(|_| (format!("pid:{pid}"), format!("pid_{pid}"))); Ok(Snapshot { captured_at: SystemTime::now(), surface_kind: SurfaceKind::Uia, app: AppContext { id: app_id, name: app_name, }, window: Some(WindowContext { id: format!("{:#x}", hwnd.0 as usize), title: window_title, }), root, refs, }) } /// Walk every cached child of `parent` and emit `Node`s. /// /// Pre-order DFS over the local cache populated by `BuildUpdatedCache`, so the /// per-node reads in `build_node` are in-process. `nth_seen` is the *global* /// per-snapshot counter described in `capture_with_options`. Honors /// `opts.compact` (drop unnamed `Generic` nodes; their children are hoisted /// into the caller's list) and `opts.depth` (the cache scope already bounds /// depths 0 and 1; this trims deeper requests). fn walk_children( parent: &IUIAutomationElement, refs: &mut RefMap, nth_seen: &mut HashMap<(Role, String), usize>, depth: usize, opts: &SnapshotOptions, dpi_scale: f64, ) -> Result> { if let Some(max) = opts.depth { if depth > max { return Ok(Vec::new()); } } let mut result: Vec = Vec::new(); for child in cached_children(parent) { let (mut node, signals) = build_node(&child, Some(parent), dpi_scale); // Allocate ref BEFORE recursing so `nth` follows pre-order DFS. // `find_in_tree` mirrors this exact ordering at action time. See // `qualifies_for_ref` for which elements earn a ref. if qualifies_for_ref(&node.role, &signals) { let key = (node.role.clone(), node.name.clone()); let counter = nth_seen.entry(key).or_insert(0); let nth = *counter; *counter += 1; let id = refs.insert( node.role.clone(), node.name.clone(), nth, node.native.clone(), ); node.ref_id = Some(id); } node.children = walk_children(&child, refs, nth_seen, depth + 1, opts, dpi_scale)?; if opts.compact && is_compactable(&node) { // Hoist the children into our caller's list - the empty Generic // wrapper is dropped, but its descendants survive. result.extend(std::mem::take(&mut node.children)); } else { result.push(node); } } Ok(result) } /// Collect the cached children of `parent` (those that were within the cache /// request's tree scope). Returns an empty vec when the element has no cached /// children or the cache array can't be read. fn cached_children(parent: &IUIAutomationElement) -> Vec { // SAFETY: `parent` is a valid COM interface obtained from the cache; this // returns `Err` (no cached children) or a valid array we index into. let Ok(array): WinResult = (unsafe { parent.GetCachedChildren() }) else { return Vec::new(); }; let Ok(len) = (unsafe { array.Length() }) else { return Vec::new(); }; let mut out = Vec::with_capacity(usize::try_from(len.max(0)).unwrap_or(0)); for i in 0..len { // SAFETY: `i` is in `0..Length()`. if let Ok(elem) = unsafe { array.GetElement(i) } { out.push(elem); } } out } /// Roles that may carry an editable value via UIA's `ValuePattern`. We only /// query the pattern for these to keep snapshot cost bounded - querying every /// node would add a COM round-trip per element on trees of thousands. fn role_might_have_value(role: &Role) -> bool { matches!( role, Role::TextField | Role::Document | Role::ComboBox | Role::SearchBox | Role::SpinButton | Role::Slider | Role::Unknown(_) ) } /// Read the element's `ValuePattern` value when present. /// /// Returns `(value, is_read_only)`. `None` if the pattern isn't supported. fn read_value_pattern(element: &IUIAutomationElement) -> Option<(String, bool)> { // SAFETY: `element` is a valid COM interface; UIA pattern IDs are well-known. let pattern: IUIAutomationValuePattern = unsafe { element.GetCurrentPatternAs(UIA_ValuePatternId) }.ok()?; let value = unsafe { pattern.CurrentValue() } .ok() .map(|b| b.to_string()) .unwrap_or_default(); let read_only = unsafe { pattern.CurrentIsReadOnly() }.is_ok_and(BOOL::as_bool); Some((value, read_only)) } /// Live-read whether an element is password-protected. Used by action-time /// ref resolution to mirror snapshot-time value suppression. fn is_current_password(element: &IUIAutomationElement) -> bool { // SAFETY: `element` is a valid COM interface. unsafe { element.CurrentIsPassword() }.is_ok_and(BOOL::as_bool) } /// Ref-emission inputs that [`build_node`] extracts but that aren't carried /// on [`Node`] itself. Combined with the node's role by [`qualifies_for_ref`]. struct RefSignals { /// Element exposes a non-read-only `ValuePattern` - it is an editable /// field even when its role isn't ARIA-interactive (the typical case for /// Win11 Notepad's `Document`-typed edit area). has_editable_value: bool, /// Element reports `IsKeyboardFocusable` - a user can Tab to it and act /// on it, which is the signal that catches custom controls UIA doesn't /// classify as one of the interactive roles. keyboard_focusable: bool, } /// Decide whether an element earns a `RefId`. Per `docs/uia-mapping.md` §9 an /// element is reffable when any of the following holds: /// /// - its role is ARIA-interactive ([`Role::is_interactive`]); or /// - it exposes a non-read-only `ValuePattern`; or /// - it is keyboard-focusable and its role is not purely structural /// ([`Role::is_structural`]) - this is what surfaces focusable custom /// controls the agent can clearly act on. /// /// Both the snapshot walk and the action-time `nth` walk /// ([`element_qualifies_as_ref`]) must apply this exact predicate, or refs /// stop resolving. The keyboard-focus tier deliberately excludes structural /// roles (panes, groups, windows) so a focusable container doesn't flood the /// ref map. fn qualifies_for_ref(role: &Role, signals: &RefSignals) -> bool { role.is_interactive() || signals.has_editable_value || (signals.keyboard_focusable && !role.is_structural()) } /// Read `HelpText` for the [`Node::description`] field. UIA apps often mirror /// the `Name` into `HelpText`; we keep it only when it adds information, so a /// node never carries a `description` that just repeats its `name`. fn read_help_text(element: &IUIAutomationElement, name: &str) -> Option { // SAFETY: `element` is a valid cached COM interface; reads the local cache. let text = unsafe { element.CachedHelpText() }.ok()?.to_string(); let trimmed = text.trim(); if trimmed.is_empty() || trimmed == name { None } else { Some(trimmed.to_string()) } } /// Read the UIA `Level` property - the 1-based hierarchy depth UIA exposes on /// tree items, list items, and headings. `Level` has no typed `Cached*` /// getter, so we read it from the cache as a VARIANT. UIA reports `0` for /// elements that have no level; we map that (and any non-positive value) to /// `None` so only elements that genuinely carry a level surface one. fn read_level(element: &IUIAutomationElement) -> Option { // SAFETY: `element` is a valid cached COM interface; `UIA_LevelPropertyId` // is in the cache request, so this reads the local cache, no round-trip. let variant = unsafe { element.GetCachedPropertyValue(UIA_LevelPropertyId) }.ok()?; let level = i32::try_from(&variant).ok()?; if level > 0 { Some(level) } else { None } } /// Read a value-bearing node's current value plus whether it is editable. /// /// Prefers `ValuePattern` (text fields, combo boxes, documents). When the /// element has no `ValuePattern` it falls back to `RangeValuePattern` for the /// numeric position of sliders and spinners. The returned bool is the /// `has_editable_value` signal: `true` only for a non-read-only `ValuePattern`, /// because that is the pattern the `Fill` action drives - a range control is /// already an interactive role and earns its ref regardless. fn read_node_value(element: &IUIAutomationElement, is_password: bool) -> (Option, bool) { if is_password { return (None, false); } if let Some((text, read_only)) = read_value_pattern(element) { let value = if text.is_empty() { None } else { Some(text) }; return (value, !read_only); } (read_range_value(element), false) } /// Read `RangeValuePattern.Value` as a display string. Sliders and spinners /// expose their position here rather than through `ValuePattern`. fn read_range_value(element: &IUIAutomationElement) -> Option { // SAFETY: `element` is a valid COM interface; UIA pattern IDs are well-known. let pattern: IUIAutomationRangeValuePattern = unsafe { element.GetCurrentPatternAs(UIA_RangeValuePatternId) }.ok()?; // SAFETY: `pattern` is a valid IUIAutomationRangeValuePattern. let value = unsafe { pattern.CurrentValue() }.ok()?; Some(format_range_value(value)) } /// Format a `RangeValuePattern` value for display: whole numbers render with /// no fractional part (a slider at 40 reads `"40"`, not `"40.0"`); other /// values keep their natural precision. fn format_range_value(v: f64) -> String { if v.is_finite() && v.fract() == 0.0 && v.abs() < 1e15 { #[allow(clippy::cast_possible_truncation)] let whole = v as i64; whole.to_string() } else { v.to_string() } } /// Map an [`IUIAutomationElement`] (from the cache built by `BuildUpdatedCache`) /// to a [`Node`] (no children populated). /// /// Returns `(node, signals)`. The plain element properties come from the local /// cache (`Cached*` getters / cached `GetCachedPropertyValue` - no COM /// round-trip); the pattern-derived state (`value`, `checked`, `expanded`, /// `selected`) and the runtime-id handle are read live, but only for roles /// that plausibly carry them, so a tree of structural nodes still costs /// roughly one round-trip per node. Each read is best-effort: a /// missing/unsupported value yields a defensible default rather than failing /// the whole node. The returned [`RefSignals`] carry the two ref-emission /// inputs not visible on `Node` itself; [`qualifies_for_ref`] combines them /// with the role. fn build_node( element: &IUIAutomationElement, parent: Option<&IUIAutomationElement>, dpi_scale: f64, ) -> (Node, RefSignals) { // SAFETY: each getter dereferences only the COM `this` pointer (the // receiver), which is valid for the lifetime of `element`. The `Cached*` // variants read from the local cache populated by `BuildUpdatedCache`. let control_type = unsafe { element.CachedControlType() }.unwrap_or(UIA_CONTROLTYPE_ID(0)); let class_name = unsafe { element.CachedClassName() } .ok() .map(|b| b.to_string()) .unwrap_or_default(); let role = promoted_role(element, control_type, &class_name, parent); let name = unsafe { element.CachedName() } .ok() .map(|b| b.to_string()) .unwrap_or_default(); let description = read_help_text(element, &name); let is_enabled = unsafe { element.CachedIsEnabled() }.is_ok_and(BOOL::as_bool); let is_offscreen = unsafe { element.CachedIsOffscreen() }.is_ok_and(BOOL::as_bool); let has_focus = unsafe { element.CachedHasKeyboardFocus() }.is_ok_and(BOOL::as_bool); let keyboard_focusable = unsafe { element.CachedIsKeyboardFocusable() }.is_ok_and(BOOL::as_bool); let is_password = unsafe { element.CachedIsPassword() }.is_ok_and(BOOL::as_bool); let bounds = unsafe { element.CachedBoundingRectangle() } .ok() .map(|r| Bounds { x: f64::from(r.left) / dpi_scale, y: f64::from(r.top) / dpi_scale, w: f64::from(r.right - r.left) / dpi_scale, h: f64::from(r.bottom - r.top) / dpi_scale, }); let level = read_level(element); let (value, has_editable_value) = if role_might_have_value(&role) { read_node_value(element, is_password) } else { (None, false) }; let checked = if role_might_be_toggleable(&role) { read_toggle_state(element) } else { None }; let expanded = if role_might_expand(&role) { read_expand_state(element) } else { None }; let selected = if role_might_be_selectable(&role) { read_selection_state(element) } else { None }; let required = if role_might_be_required(&role) { read_required_for_form(element) } else { None }; let native = build_native_handle(element); let node = Node { ref_id: None, role, name, description, value, state: State { visible: !is_offscreen, enabled: is_enabled, focused: has_focus, selected, checked, expanded, required, }, bounds, level, children: Vec::new(), opaque: false, native, }; ( node, RefSignals { has_editable_value, keyboard_focusable, }, ) } /// Roles plausibly hosting `TogglePattern`. Cheap pre-filter so we don't /// add a COM round-trip per element on trees of thousands. fn role_might_be_toggleable(role: &Role) -> bool { matches!( role, Role::Checkbox | Role::Switch | Role::MenuItem | Role::MenuItemCheckbox | Role::Button | Role::Unknown(_) ) } /// Roles plausibly hosting `ExpandCollapsePattern`. Includes ComboBox (the /// drop-down expands), TreeItem (subtree disclosure), MenuItem (sub-menus), /// and Group (collapsibles). fn role_might_expand(role: &Role) -> bool { matches!( role, Role::ComboBox | Role::TreeItem | Role::MenuItem | Role::Group | Role::ListItem | Role::Unknown(_) ) } /// Roles plausibly hosting `SelectionItemPattern`. Tabs, list options, and /// tree items all expose `IsSelected`. fn role_might_be_selectable(role: &Role) -> bool { matches!( role, Role::Tab | Role::ListItem | Role::TreeItem | Role::Radio | Role::Option | Role::MenuItemRadio | Role::Cell | Role::Row | Role::Unknown(_) ) } /// Roles plausibly carrying `IsRequiredForForm`. Limited to form input /// controls - most other elements never set it. fn role_might_be_required(role: &Role) -> bool { matches!( role, Role::TextField | Role::ComboBox | Role::SearchBox | Role::SpinButton | Role::Unknown(_) ) } /// Read `TogglePattern.ToggleState` if supported. Maps UIA's tristate /// (`Off` / `On` / `Indeterminate`) to our [`Checked`] enum. fn read_toggle_state(element: &IUIAutomationElement) -> Option { // SAFETY: `element` is a valid COM interface; UIA pattern IDs are well-known. let pattern: IUIAutomationTogglePattern = unsafe { element.GetCurrentPatternAs(UIA_TogglePatternId) }.ok()?; let state = unsafe { pattern.CurrentToggleState() }.ok()?; Some(if state == ToggleState_On { Checked::True } else if state == ToggleState_Indeterminate { Checked::Mixed } else if state == ToggleState_Off { Checked::False } else { // Unknown future state - bias toward "off" rather than dropping the // signal entirely. A new ToggleState variant is unlikely but safer // to handle than to crash the snapshot. Checked::False }) } /// Read `ExpandCollapsePattern.ExpandCollapseState` if supported. Per /// `docs/uia-mapping.md` §2: `Expanded` and `PartiallyExpanded` map to /// `true`; `Collapsed` and `LeafNode` map to `false`. fn read_expand_state(element: &IUIAutomationElement) -> Option { // SAFETY: `element` is a valid COM interface. let pattern: IUIAutomationExpandCollapsePattern = unsafe { element.GetCurrentPatternAs(UIA_ExpandCollapsePatternId) }.ok()?; let state = unsafe { pattern.CurrentExpandCollapseState() }.ok()?; // Collapsed, LeafNode, and any future variant all map to `false` - we // only care whether children are currently showing. Reference the // remaining constants explicitly so an upstream rename surfaces here. let _ = (ExpandCollapseState_Collapsed, ExpandCollapseState_LeafNode); Some(state == ExpandCollapseState_Expanded || state == ExpandCollapseState_PartiallyExpanded) } /// Read `SelectionItemPattern.IsSelected` if supported. fn read_selection_state(element: &IUIAutomationElement) -> Option { // SAFETY: `element` is a valid COM interface. let pattern: IUIAutomationSelectionItemPattern = unsafe { element.GetCurrentPatternAs(UIA_SelectionItemPatternId) }.ok()?; let is_selected = unsafe { pattern.CurrentIsSelected() }.ok()?; Some(is_selected.as_bool()) } /// Read `IsRequiredForForm`. Always available as an element property; the /// role gate keeps us from paying for it on elements that are never /// form-required (panels, separators, etc.). fn read_required_for_form(element: &IUIAutomationElement) -> Option { // SAFETY: `element` is a valid cached COM interface; this reads the value // from the local cache populated by `BuildUpdatedCache`. let required = unsafe { element.CachedIsRequiredForForm() }.ok()?; // Most apps never set this - only emit `Some(true)` to avoid littering // every form field with `required: false`. if required.as_bool() { Some(true) } else { None } } /// Build the platform handle stored on every emitted [`Node`]. The handle is /// later cloned into the `RefMap` entry for elements that get a `RefId`, so /// action-time resolution can take a fast path through UIA's property index /// rather than walking the full subtree. /// /// Returns `None` only when both `RuntimeId` extraction and `AutomationId` /// reads fail - the element is then so degenerate that there's nothing /// useful to record. fn build_native_handle(element: &IUIAutomationElement) -> Option { let runtime_id = extract_runtime_id(element).unwrap_or_default(); let automation_id = extract_automation_id(element); if runtime_id.is_empty() && automation_id.is_none() { return None; } Some(NativeHandle::Uia { runtime_id, automation_id, }) } /// Pull the UIA `RuntimeId` out of an element and pack it as little-endian /// bytes (4 bytes per `i32` slot). RuntimeIds are unstable across UIA sessions /// but unique within one, so [`find_by_runtime_id`] uses these bytes as a /// mid-tier action-time resolver, and downstream code can compare elements /// without re-walking. Works on both cached and live elements. fn extract_runtime_id(element: &IUIAutomationElement) -> Option> { // SAFETY: `element` is a valid COM interface; `GetRuntimeId` returns a // SAFEARRAY pointer we own and must destroy. let array_ptr = unsafe { element.GetRuntimeId() }.ok()?; if array_ptr.is_null() { return None; } let ids = read_i32_safearray(array_ptr); let mut bytes = Vec::with_capacity(ids.len() * 4); for id in ids { bytes.extend_from_slice(&id.to_le_bytes()); } if bytes.is_empty() { None } else { Some(bytes) } } /// Read the `AutomationId` property from the local cache. Most Win32 controls /// don't set it; WPF and WinUI controls do. Empty strings are normalized to /// `None` so a present `Some("")` never tricks the fast-path resolver into /// matching the wrong element. fn extract_automation_id(element: &IUIAutomationElement) -> Option { // SAFETY: `element` is a valid cached COM interface. let bstr = unsafe { element.CachedAutomationId() }.ok()?; let s = bstr.to_string(); if s.is_empty() { None } else { Some(s) } } /// Read a one-dimensional SAFEARRAY of `i32` (the only shape `GetRuntimeId` /// returns) into a `Vec`. Always destroys the SAFEARRAY before returning, /// even on read failure - leaking would slowly bloat the UIA process's heap /// across thousands of nodes. fn read_i32_safearray(array: *mut SAFEARRAY) -> Vec { if array.is_null() { return Vec::new(); } // SAFETY: `array` is a valid SAFEARRAY pointer obtained from UIA. Each // SafeArray* call below is safe given a valid pointer; we destroy the // array on every exit path. Bounds come back as i32s; data is a slice // of i32 we copy out before unaccessing. unsafe { let (Ok(lbound), Ok(ubound)) = (SafeArrayGetLBound(array, 1), SafeArrayGetUBound(array, 1)) else { let _ = SafeArrayDestroy(array); return Vec::new(); }; let count = ubound.checked_sub(lbound).and_then(|d| d.checked_add(1)); let Some(count) = count .filter(|c| *c > 0) .and_then(|c| usize::try_from(c).ok()) else { let _ = SafeArrayDestroy(array); return Vec::new(); }; let mut data: *mut core::ffi::c_void = std::ptr::null_mut(); if SafeArrayAccessData(array, &raw mut data).is_err() || data.is_null() { let _ = SafeArrayDestroy(array); return Vec::new(); } let slice = std::slice::from_raw_parts(data.cast::(), count); let out = slice.to_vec(); let _ = SafeArrayUnaccessData(array); let _ = SafeArrayDestroy(array); out } } /// Compact-mode predicate: drop unnamed structural-only wrapper nodes. fn is_compactable(node: &Node) -> bool { matches!(node.role, Role::Generic) && node.name.is_empty() && !node.state.focused } /// UIA ControlType → canonical [`Role`]. Per `docs/uia-mapping.md` §1. fn role_from_control_type(ct: UIA_CONTROLTYPE_ID, class_name: &str) -> Role { // Mappings are listed grouped by target Role so that ControlTypes which // share a Role (e.g. Pane / ProgressBar / ScrollBar all become Generic) // can be collapsed without confusing clippy. if ct == UIA_ButtonControlTypeId || ct == UIA_SplitButtonControlTypeId { Role::Button } else if ct == UIA_CheckBoxControlTypeId { Role::Checkbox } else if ct == UIA_ComboBoxControlTypeId { Role::ComboBox } else if ct == UIA_CustomControlTypeId { promote_class_name(class_name) } else if ct == UIA_DataGridControlTypeId { Role::Grid } else if ct == UIA_DataItemControlTypeId { Role::Row } else if ct == UIA_DocumentControlTypeId { Role::Document } else if ct == UIA_EditControlTypeId { Role::TextField } else if ct == UIA_GroupControlTypeId || ct == UIA_CalendarControlTypeId || ct == UIA_SemanticZoomControlTypeId { Role::Group } else if ct == UIA_HeaderControlTypeId { Role::RowGroup } else if ct == UIA_HeaderItemControlTypeId { Role::ColumnHeader } else if ct == UIA_HyperlinkControlTypeId { Role::Link } else if ct == UIA_ImageControlTypeId { Role::Image } else if ct == UIA_ListControlTypeId { Role::List } else if ct == UIA_ListItemControlTypeId { Role::ListItem } else if ct == UIA_MenuControlTypeId { Role::Menu } else if ct == UIA_MenuBarControlTypeId { Role::MenuBar } else if ct == UIA_MenuItemControlTypeId { Role::MenuItem } else if ct == UIA_PaneControlTypeId || ct == UIA_ProgressBarControlTypeId || ct == UIA_ScrollBarControlTypeId || ct == UIA_SeparatorControlTypeId || ct == UIA_TextControlTypeId || ct == UIA_ThumbControlTypeId || ct == UIA_TitleBarControlTypeId || ct == UIA_ToolTipControlTypeId { Role::Generic } else if ct == UIA_RadioButtonControlTypeId { Role::Radio } else if ct == UIA_SliderControlTypeId { Role::Slider } else if ct == UIA_SpinnerControlTypeId { Role::SpinButton } else if ct == UIA_StatusBarControlTypeId { Role::Region } else if ct == UIA_TabControlTypeId { Role::TabList } else if ct == UIA_TabItemControlTypeId { Role::Tab } else if ct == UIA_TableControlTypeId { Role::Table } else if ct == UIA_ToolBarControlTypeId { Role::Toolbar } else if ct == UIA_TreeControlTypeId { Role::Tree } else if ct == UIA_TreeItemControlTypeId { Role::TreeItem } else if ct == UIA_WindowControlTypeId { Role::Window } else { Role::Unknown(format!("uia_ct_{}", ct.0)) } } /// Apply the pattern-based role promotions from `docs/uia-mapping.md` §1 on /// top of the raw `ControlType → Role` mapping. /// /// The promotions: /// - `MenuItem` + `TogglePattern` → `MenuItemCheckbox`. UIA doesn't expose a /// reliable "is radio" hint, so we don't distinguish radio menu items - /// anything checkable becomes `MenuItemCheckbox`. /// - `Window` + `WindowPattern.IsModal=true` → `Dialog`. Top-level frames /// stay as `Window`; modal popups become `Dialog`. /// - `ListItem` whose `parent` exposes `SelectionPattern` → `Option`. List /// items inside a selection container act like `