actl-uia 0.1.9

Windows UIA backend: the ONLY crate allowed to touch COM/unsafe
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
//! Strict scoped queries use fallible child enumeration, never the legacy fuzzy chain.
use crate::{internal, locate::Located};
use actl_core::{
    CtlError, ErrorCode,
    selector::{Filter, Scope, Selector},
};
use serde_json::json;
use uiautomation::{UIAutomation, UIElement, types::TreeScope};

#[derive(Clone)]
struct Node {
    element: UIElement,
    condition: uiautomation::core::UICondition,
    cache: uiautomation::core::UICacheRequest,
}

trait Tree: Clone {
    fn exact_candidates(
        &self,
        _filter: &Filter,
        _scope: Scope,
        _include_root: bool,
    ) -> Result<Option<Vec<Self>>, CtlError> {
        Ok(None)
    }
    fn children(&self) -> Result<Vec<Self>, CtlError>;
    fn matches(&self, filter: &Filter) -> Result<bool, CtlError>;
    fn evidence(&self) -> Result<serde_json::Value, CtlError>;
}

/// Only an observed absence may satisfy wait --gone.
pub(crate) fn observed<T>(result: Result<T, CtlError>) -> Result<Option<T>, CtlError> {
    match result {
        Ok(value) => Ok(Some(value)),
        Err(error) if error.code == ErrorCode::NotFound => Ok(None),
        Err(error) => Err(error),
    }
}

impl Tree for Node {
    fn exact_candidates(
        &self,
        filter: &Filter,
        scope: Scope,
        include_root: bool,
    ) -> Result<Option<Vec<Self>>, CtlError> {
        use uiautomation::{types::UIProperty, variants::Variant};
        let seed = filter
            .id
            .as_ref()
            .map(|s| (UIProperty::AutomationId, Variant::from(s.clone())))
            .or_else(|| {
                filter
                    .name
                    .as_ref()
                    .map(|s| (UIProperty::Name, Variant::from(s.clone())))
            })
            .or_else(|| {
                filter
                    .role
                    .as_deref()
                    .and_then(role_id)
                    .map(|id| (UIProperty::ControlType, Variant::from(id)))
            });
        let Some((property, value)) = seed else {
            return Ok(None);
        };
        let auto = UIAutomation::new().map_err(internal)?;
        let condition = auto
            .create_property_condition(property, value, None)
            .map_err(|e| crate::read_channel::failure("selector.condition", e))?;
        let native_scope = match (scope, include_root) {
            (Scope::Children, _) => TreeScope::Children,
            (Scope::Descendants, true) => TreeScope::Subtree,
            (Scope::Descendants, false) => TreeScope::Descendants,
        };
        // RawView cache and the complete provider result preserve scope/uniqueness.
        // Failure must never fall through to DFS or become an empty result.
        let _t = actl_core::trace::scope("selector.find_all_build_cache");
        self.element
            .find_all_build_cache(native_scope, &condition, &self.cache)
            .map(|hits| {
                Some(
                    hits.into_iter()
                        .map(|element| Self {
                            element,
                            condition: self.condition.clone(),
                            cache: self.cache.clone(),
                        })
                        .collect(),
                )
            })
            .map_err(|e| crate::read_channel::failure("selector.query", e))
    }
    fn children(&self) -> Result<Vec<Self>, CtlError> {
        self.element
            .find_all_build_cache(TreeScope::Children, &self.condition, &self.cache)
            .map(|nodes| {
                nodes
                    .into_iter()
                    .map(|element| Self {
                        element,
                        condition: self.condition.clone(),
                        cache: self.cache.clone(),
                    })
                    .collect()
            })
            .map_err(internal)
    }
    fn matches(&self, filter: &Filter) -> Result<bool, CtlError> {
        let _t = actl_core::trace::scope("selector.match_properties");
        // A failed required property read is unknown, not an absent match.
        let role = filter
            .role
            .as_ref()
            .map(|_| {
                self.element
                    .get_control_type()
                    .map(|v| format!("{v:?}"))
                    .map_err(internal)
            })
            .transpose()?;
        let id = filter
            .id
            .as_ref()
            .map(|_| self.element.get_automation_id().map_err(internal))
            .transpose()?;
        let name = (filter.name.is_some() || filter.name_contains.is_some())
            .then(|| self.element.get_name().map_err(internal))
            .transpose()?;
        Ok(filter.matches(role.as_deref(), id.as_deref(), name.as_deref()))
    }
    fn evidence(&self) -> Result<serde_json::Value, CtlError> {
        Ok(json!({
            "role": format!("{:?}", self.element.get_control_type().map_err(internal)?),
            "name": self.element.get_name().map_err(internal)?,
            "automation_id": self.element.get_automation_id().map_err(internal)?,
        }))
    }
}

fn collect<T: Tree>(
    root: &T,
    filter: &Filter,
    scope: Scope,
    include_root: bool,
) -> Result<Vec<T>, CtlError> {
    actl_core::wait_control::check()?;
    if let Some(candidates) = root.exact_candidates(filter, scope, include_root)? {
        if candidates.len() > crate::window::MAX_ELEMENTS {
            return Err(CtlError::with_evidence(
                ErrorCode::NotActionable,
                "uia query exceeded candidate budget; narrow the conditions",
                json!({"reason":"selector_budget_exceeded"}),
            ));
        }
        let mut hits = Vec::new();
        for candidate in candidates {
            actl_core::wait_control::check()?;
            if candidate.matches(filter)? {
                hits.push(candidate);
            }
        }
        actl_core::wait_control::check()?;
        return Ok(hits);
    }
    let mut pending = vec![(root.clone(), 0u32)];
    let mut count = 0usize;
    let mut hits = Vec::new();
    while let Some((node, depth)) = pending.pop() {
        actl_core::wait_control::check()?;
        count += 1;
        if count > crate::window::MAX_ELEMENTS || depth > crate::window::MAX_DEPTH {
            return Err(CtlError::with_evidence(
                ErrorCode::NotActionable,
                "uia query exceeded traversal budget; narrow the window or container",
                json!({"reason":"selector_budget_exceeded"}),
            ));
        }
        if (include_root || depth > 0) && node.matches(filter)? {
            hits.push(node.clone());
        }
        if scope == Scope::Descendants || depth == 0 {
            let children = node.children()?;
            if count + pending.len() + children.len() > crate::window::MAX_ELEMENTS {
                return Err(CtlError::with_evidence(
                    ErrorCode::NotActionable,
                    "uia query exceeded traversal budget; narrow the window or container",
                    json!({"reason":"selector_budget_exceeded"}),
                ));
            }
            pending.extend(children.into_iter().rev().map(|n| (n, depth + 1)));
        }
    }
    Ok(hits)
}

fn unique<T: Tree>(mut hits: Vec<T>, phase: &str) -> Result<T, CtlError> {
    if hits.len() == 1 {
        return hits
            .pop()
            .ok_or_else(|| CtlError::internal("missing unique UIA candidate"));
    }
    let count = hits.len();
    let candidates = hits
        .iter()
        .take(20)
        .map(Tree::evidence)
        .collect::<Result<Vec<_>, _>>()?;
    Err(CtlError::with_evidence(
        if count == 0 {
            ErrorCode::NotFound
        } else {
            ErrorCode::Ambiguous
        },
        format!("uia {phase} requires exactly one match; found {count}"),
        json!({"phase":phase,"count":count,"candidates":candidates,"truncated":count > 20}),
    ))
}

fn resolve<T: Tree>(root: &T, selector: &Selector) -> Result<T, CtlError> {
    let container = if let Some(filter) = &selector.within {
        unique(collect(root, filter, Scope::Descendants, true)?, "within")?
    } else {
        root.clone()
    };
    // Container itself is excluded; an unscoped subtree includes the window root.
    unique(
        collect(
            &container,
            &selector.filter,
            selector.scope,
            selector.within.is_none() && selector.scope == Scope::Descendants,
        )?,
        "match",
    )
}

/// Do not inherit the legacy walker's error-as-end-of-tree window discovery.
pub(crate) fn window(auto: &UIAutomation, app: Option<&str>) -> Result<UIElement, CtlError> {
    let handle = match app {
        Some(pattern) if pattern.starts_with("hwnd:") => {
            Some(crate::window::parse_hwnd(&pattern[5..])?)
        }
        None => Some(
            crate::window::foreground_window()
                .ok_or_else(|| CtlError::internal("foreground window could not be observed"))?
                .1,
        ),
        _ => None,
    };
    if let Some(handle) = handle {
        crate::display_support::reject_display(handle)?;
        if crate::native_windows::native_window(handle)?.is_empty() {
            return Err(CtlError::new(
                ErrorCode::NotFound,
                "native target window is absent",
            ));
        }
        // An existing native window with an unavailable provider is unknown, not absent.
        let _t = actl_core::trace::scope("window.element_from_handle");
        return auto
            .element_from_handle(uiautomation::types::Handle::from(handle))
            .map_err(internal);
    }
    let pattern = app.ok_or_else(|| CtlError::internal("missing window query"))?;
    // 与 find_window 同源的桌面根枚举瞬态重试;此前此处把枚举失败误映射为 Internal
    let windows = match crate::native_windows::title_elements(auto, pattern)? {
        Some(windows) => windows,
        None => crate::observation::desktop_children(auto)?,
    };
    let mut matched = Vec::new();
    for element in windows {
        let _t = actl_core::trace::scope("window.candidate_properties");
        if let Some(hwnd) = crate::window::native_hwnd(&element)
            && crate::display_support::is_display_window(hwnd)
        {
            continue;
        }
        if element.get_name().map_err(internal)?.contains(pattern) {
            matched.push(element);
        }
    }
    // Node 的 condition/cache 只服务后续 children 遍历,命中后再构建
    let hits: Vec<Node> = if matched.is_empty() {
        Vec::new()
    } else {
        let condition = auto.create_true_condition().map_err(internal)?;
        let cache = raw_cache(auto, &condition)?;
        matched
            .into_iter()
            .map(|element| Node {
                element,
                condition: condition.clone(),
                cache: cache.clone(),
            })
            .collect()
    };
    Ok(unique(hits, "window")?.element)
}

fn raw_cache(
    auto: &UIAutomation,
    condition: &uiautomation::core::UICondition,
) -> Result<uiautomation::core::UICacheRequest, CtlError> {
    let cache = auto.create_cache_request().map_err(internal)?;
    // FindAll's implicit control view omits raw-only containers visible to snapshot.
    // Explicit RawView (true) preserves actual parent/child scope as well as membership.
    cache.set_tree_filter(condition.clone()).map_err(internal)?;
    cache.set_tree_scope(TreeScope::Element).map_err(internal)?;
    Ok(cache)
}

pub(crate) fn locate(
    auto: &UIAutomation,
    root: &UIElement,
    selector: &Selector,
) -> Result<Located, CtlError> {
    let condition = auto.create_true_condition().map_err(internal)?;
    let cache = raw_cache(auto, &condition)?;
    let node = Node {
        element: root.clone(),
        condition,
        cache,
    };
    let hit = resolve(&node, selector)?;
    let _t = actl_core::trace::scope("selector.result_properties");
    Ok(Located {
        window_title: root.get_name().map_err(internal)?,
        role: format!("{:?}", hit.element.get_control_type().map_err(internal)?),
        name: Some(hit.element.get_name().map_err(internal)?),
        automation_id: Some(hit.element.get_automation_id().map_err(internal)?),
        resolved_by: "uia-composite",
        element: hit.element,
    })
}

// Match the supported UIA enum, preserving case-insensitive strict role semantics.
fn role_id(role: &str) -> Option<i32> {
    use uiautomation::types::ControlType;
    (ControlType::Button as i32..=ControlType::AppBar as i32).find(|id| {
        ControlType::try_from(*id).is_ok_and(|kind| format!("{kind:?}").eq_ignore_ascii_case(role))
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    mod provider;
    #[derive(Clone)]
    struct Fake {
        id: &'static str,
        role: &'static str,
        name: &'static str,
        children: Vec<Fake>,
        broken: bool,
    }
    impl Tree for Fake {
        fn children(&self) -> Result<Vec<Self>, CtlError> {
            if self.broken {
                Err(CtlError::internal("provider disconnected"))
            } else {
                Ok(self.children.clone())
            }
        }
        fn matches(&self, f: &Filter) -> Result<bool, CtlError> {
            Ok(f.matches(Some(self.role), Some(self.id), Some(self.name)))
        }
        fn evidence(&self) -> Result<serde_json::Value, CtlError> {
            Ok(json!({"id":self.id}))
        }
    }
    fn node(id: &'static str, role: &'static str, children: Vec<Fake>) -> Fake {
        Fake {
            id,
            role,
            name: "OK",
            children,
            broken: false,
        }
    }
    fn tree() -> Fake {
        node(
            "window",
            "Window",
            vec![
                node("other", "Button", vec![]),
                node(
                    "panel",
                    "Pane",
                    vec![
                        node("save", "Button", vec![]),
                        node("nested", "Pane", vec![node("deep", "Button", vec![])]),
                    ],
                ),
            ],
        )
    }
    fn query(json: &str) -> Selector {
        Selector::parse(json).unwrap()
    }
    #[test]
    fn container_and_conjunction_are_required() {
        let q = query(
            r#"{"match":{"role":"Button","name":"OK"},"within":{"id":"panel"},"scope":"children"}"#,
        );
        assert_eq!(resolve(&tree(), &q).unwrap().id, "save");
        let mut missing = q.clone();
        missing.within.as_mut().unwrap().id = Some("absent".into());
        let e = resolve(&tree(), &missing).err().unwrap();
        assert_eq!(e.code, ErrorCode::NotFound);
        assert_eq!(e.evidence.unwrap()["phase"], "within");
        let mut mismatch = q;
        mismatch.filter.name = Some("ok".into());
        assert_eq!(
            resolve(&tree(), &mismatch).err().unwrap().code,
            ErrorCode::NotFound
        );
    }
    #[test]
    fn descendants_and_ambiguous_containers_fail_closed() {
        let q = query(r#"{"match":{"role":"Button"},"within":{"id":"panel"}}"#);
        assert_eq!(
            resolve(&tree(), &q).err().unwrap().code,
            ErrorCode::Ambiguous
        );
        let q = query(r#"{"match":{"id":"save"},"within":{"role":"Pane"}}"#);
        let e = resolve(&tree(), &q).err().unwrap();
        assert_eq!(e.code, ErrorCode::Ambiguous);
        assert_eq!(e.evidence.unwrap()["phase"], "within");
    }
    #[test]
    fn exclude_container_and_relocate_after_rebuild() {
        let q = query(r#"{"match":{"id":"panel"},"within":{"id":"panel"}}"#);
        assert_eq!(
            resolve(&tree(), &q).err().unwrap().code,
            ErrorCode::NotFound
        );
        let q = query(r#"{"match":{"id":"save"}}"#);
        assert_eq!(resolve(&tree(), &q).unwrap().id, "save");
        let rebuilt = node("window", "Window", vec![]);
        assert_eq!(
            resolve(&rebuilt, &q).err().unwrap().code,
            ErrorCode::NotFound
        );
    }
    #[test]
    fn incomplete_observation_never_proves_uniqueness_or_absence() {
        let mut root = tree();
        root.children[0].broken = true;
        for q in [
            r#"{"match":{"id":"save"}}"#,
            r#"{"match":{"id":"missing"}}"#,
        ] {
            assert_eq!(
                resolve(&root, &query(q)).err().unwrap().code,
                ErrorCode::Internal
            );
        }
    }
    #[test]
    fn budget_is_an_error_not_partial_success() {
        let mut root = node("last", "Button", vec![]);
        for _ in 0..=crate::window::MAX_DEPTH {
            root = node("level", "Pane", vec![root]);
        }
        assert_eq!(
            resolve(&root, &query(r#"{"match":{"id":"last"}}"#))
                .err()
                .unwrap()
                .code,
            ErrorCode::NotActionable
        );
    }

    #[test]
    fn wait_does_not_convert_errors_to_absence() {
        for code in [
            ErrorCode::Internal,
            ErrorCode::NotActionable,
            ErrorCode::Ambiguous,
            ErrorCode::Protocol,
            ErrorCode::Aborted,
            ErrorCode::PermDenied,
            ErrorCode::StaleRef,
        ] {
            assert_eq!(
                observed::<()>(Err(CtlError::new(code, "unknown")))
                    .unwrap_err()
                    .code,
                code
            );
        }
        assert!(
            observed::<()>(Err(CtlError::new(ErrorCode::NotFound, "absent")))
                .unwrap()
                .is_none()
        );
    }

    #[test]
    fn ambiguity_envelope_contract() {
        let q = query(r#"{"match":{"role":"Button"},"within":{"id":"panel"}}"#);
        let error = resolve(&tree(), &q).err().unwrap();
        let envelope = actl_core::ErrorEnvelope::new("find", &error, 0);
        assert_eq!(
            serde_json::to_value(envelope).unwrap(),
            serde_json::from_str::<serde_json::Value>(include_str!(
                "../tests/golden/selector_ambiguous.json"
            ))
            .unwrap()
        );
    }
}