Skip to main content

mgui_runtime/
accessibility.rs

1//! 无障碍语义树 — 平台无关的 AccessKit 数据转换与 action 路由。
2//!
3//! winit Adapter 的创建(activator / action channel / deactivator)在
4//! `mgui-shell-desktop::a11y`;本模块只做 `ElementTree` 语义快照 →
5//! `accesskit::TreeUpdate` 的转换与 Focus/Click/SetValue 分发,
6//! 因此依赖树中没有 winit / accesskit_winit。
7
8use std::collections::HashMap;
9
10use accesskit::{
11    Action, ActionData, ActionRequest, Node, NodeId, Role, TextDirection, TextPosition, TextSelection, Tree, TreeUpdate,
12};
13
14use mgui_core::{
15    ElementId, ElementTree, Key as SlotKey, LiveRegion, Point, PointerData, Rect, SemanticsData, SemanticsRole,
16    WidgetEvent,
17};
18
19// =============================================================================
20// 辅助:SemanticsRole → accesskit Role
21// =============================================================================
22
23fn to_accesskit_role(role: SemanticsRole) -> Role {
24    match role {
25        SemanticsRole::Button => Role::Button,
26        SemanticsRole::CheckBox => Role::CheckBox,
27        SemanticsRole::Slider => Role::Slider,
28        SemanticsRole::TextInput => Role::TextInput,
29        SemanticsRole::TextRun => Role::TextRun,
30        SemanticsRole::Label => Role::Label,
31        SemanticsRole::Image => Role::Image,
32        SemanticsRole::Container => Role::GenericContainer,
33        SemanticsRole::Unknown => Role::Unknown,
34        SemanticsRole::Dialog => Role::Dialog,
35        SemanticsRole::Tab => Role::Tab,
36        SemanticsRole::TabList => Role::TabList,
37        SemanticsRole::TabPanel => Role::TabPanel,
38        SemanticsRole::List => Role::List,
39        SemanticsRole::ListItem => Role::ListItem,
40        SemanticsRole::ListOption => Role::MenuListOption,
41        SemanticsRole::Grid => Role::Grid,
42        SemanticsRole::GridRow => Role::Row,
43        SemanticsRole::GridCell => Role::Cell,
44        SemanticsRole::Tree => Role::Tree,
45        SemanticsRole::TreeItem => Role::TreeItem,
46        SemanticsRole::Progress => Role::ProgressIndicator,
47        SemanticsRole::Toast => Role::Alert,
48        SemanticsRole::Menu => Role::Menu,
49        SemanticsRole::MenuItem => Role::MenuItem,
50        SemanticsRole::ComboBox => Role::ComboBox,
51        SemanticsRole::RadioGroup => Role::RadioGroup,
52        SemanticsRole::RadioButton => Role::RadioButton,
53        SemanticsRole::Tooltip => Role::Tooltip,
54        SemanticsRole::Splitter => Role::Splitter,
55    }
56}
57
58// =============================================================================
59// ElementId → NodeId(公开给 main.rs)
60// =============================================================================
61
62pub fn to_node_id(id: ElementId) -> NodeId {
63    // slotmap::KeyData.as_ffi() → u64
64    NodeId(id.data().as_ffi())
65}
66
67// =============================================================================
68// 语义树 → TreeUpdate(公开给 main.rs)
69// =============================================================================
70
71/// 把 `build_accessibility_tree()` 输出的语义快照转成 accesskit::TreeUpdate。
72///
73/// - `tree`:core 产出的 Vec<(ElementId, SemanticsData)>
74/// - `focus`:当前焦点 ElementId(可能 None)
75/// - `dpr`:设备像素比 — bounds 从逻辑像素乘 DPR 转物理像素
76/// - `is_initial`:true 时包含 Tree 元信息(首次推树时必须提供)
77pub fn build_tree_update(
78    tree: &[(ElementId, SemanticsData)],
79    focus: Option<ElementId>,
80    dpr: f32,
81    is_initial: bool,
82) -> TreeUpdate {
83    let sem_map: HashMap<ElementId, &SemanticsData> = tree.iter().map(|(id, s)| (*id, s)).collect();
84
85    // core 会在首位插入合成根(A11Y_ROOT);手工构造的旧格式数组仍回退到 first()
86    let root_element_id = tree
87        .iter()
88        .find(|(id, _)| *id == ElementId::A11Y_ROOT)
89        .map(|(id, _)| *id)
90        .or_else(|| tree.first().map(|(id, _)| *id));
91    let root_node_id = root_element_id.map(to_node_id);
92
93    let mut nodes: Vec<(NodeId, Node)> = Vec::with_capacity(tree.len());
94    // 虚拟子项使用独立 id 空间(从 u64::MAX - 1 递减)。
95    // A11Y_ROOT 的 ElementId 是 slotmap KeyData::from_ffi(u64::MAX),映射为
96    // NodeId(u64::MAX);虚拟节点必须避开它,否则根与虚拟子节点 NodeId 冲突,
97    // AccessKit 增量更新时会形成环并栈溢出(Windows UIA 实测)。
98    let mut virtual_counter: u64 = 0;
99
100    for (el_id, sd) in tree {
101        let nid = to_node_id(*el_id);
102        // 合成根必须是"可包含"的普通角色:AccessKit 的过滤器会把 GenericContainer
103        // 从 UIA 树中跳过,连带 root 没有 filtered_parent,导致 UIA NextSibling
104        // 无法从第一个顶层语义分支走到后面的兄弟(内容分支整段丢失)。
105        let role = if *el_id == ElementId::A11Y_ROOT { Role::Window } else { to_accesskit_role(sd.role) };
106        let mut node = Node::new(role);
107
108        if let Some(label) = &sd.label {
109            if !label.is_empty() {
110                node.set_label(Box::<str>::from(label.as_str()));
111            }
112        }
113        if let Some(value) = &sd.value {
114            node.set_value(value.clone());
115        }
116        if let Some(toggled) = sd.toggled {
117            node.set_toggled(if toggled { accesskit::Toggled::True } else { accesskit::Toggled::False });
118        }
119        if let Some(expanded) = sd.expanded {
120            node.set_expanded(expanded);
121        }
122        if let Some(selected) = sd.selected {
123            node.set_selected(selected);
124        }
125        if sd.modal {
126            node.set_modal();
127        }
128        if let Some(live) = sd.live {
129            node.set_live(match live {
130                LiveRegion::Polite => accesskit::Live::Polite,
131                LiveRegion::Assertive => accesskit::Live::Assertive,
132            });
133        }
134
135        let bounds = accesskit::Rect::new(
136            sd.bounds.x as f64 * dpr as f64,
137            sd.bounds.y as f64 * dpr as f64,
138            (sd.bounds.x + sd.bounds.width) as f64 * dpr as f64,
139            (sd.bounds.y + sd.bounds.height) as f64 * dpr as f64,
140        );
141        node.set_bounds(bounds);
142
143        if let Some(nv) = sd.numeric {
144            node.set_min_numeric_value(nv.min);
145            node.set_max_numeric_value(nv.max);
146            node.set_numeric_value_step(nv.step);
147            node.set_numeric_value(nv.value);
148        }
149
150        if !sd.enabled {
151            node.set_disabled();
152        }
153        if sd.read_only {
154            node.set_read_only();
155        }
156        // 禁用/只读节点暴露 action 会让 SR 允许用户触发无效修改
157        if sd.enabled {
158            if sd.focusable {
159                node.add_action(Action::Focus);
160            }
161            match sd.role {
162                SemanticsRole::Button => node.add_action(Action::Click),
163                SemanticsRole::CheckBox => node.add_action(Action::Click),
164                SemanticsRole::Slider | SemanticsRole::Splitter => node.add_action(Action::SetValue),
165                SemanticsRole::TextInput if !sd.read_only => node.add_action(Action::SetValue),
166                SemanticsRole::Tab | SemanticsRole::ListItem | SemanticsRole::TreeItem => {
167                    node.add_action(Action::Click)
168                }
169                SemanticsRole::MenuItem
170                | SemanticsRole::ComboBox
171                | SemanticsRole::RadioButton
172                | SemanticsRole::ListOption => node.add_action(Action::Click),
173                _ => {}
174            }
175            // 阅读器可请求把节点(含虚拟行)滚入可视区;无滚动祖先时动作被忽略。
176            node.add_action(Action::ScrollIntoView);
177        }
178
179        // 虚拟子项(单 RO 列表/菜单的行语义):递归构建,行/单元格均可暴露
180        let mut virtual_children: Vec<NodeId> = Vec::new();
181        let mut text_runs: Vec<TextRunNode> = Vec::new();
182        push_virtual_nodes(
183            &sd.virtual_items,
184            Point::new(sd.bounds.x, sd.bounds.y),
185            dpr,
186            &mut virtual_counter,
187            &mut nodes,
188            &mut virtual_children,
189            &mut text_runs,
190        );
191
192        // 文本选区挂在文本框宿主节点上,anchor/focus 指向行 TextRun 子节点
193        if let Some((anchor, focus)) = sd.text_selection {
194            if let (Some((anchor_node, anchor_index)), Some((focus_node, focus_index))) =
195                (locate_text_run(&text_runs, anchor), locate_text_run(&text_runs, focus))
196            {
197                node.set_text_selection(TextSelection {
198                    anchor: TextPosition { node: anchor_node, character_index: anchor_index },
199                    focus: TextPosition { node: focus_node, character_index: focus_index },
200                });
201            }
202        }
203        if sd.enabled && sd.role == SemanticsRole::TextInput && !text_runs.is_empty() {
204            node.add_action(Action::SetTextSelection);
205        }
206
207        let mut ak_children: Vec<NodeId> =
208            sd.children.iter().filter(|cid| sem_map.contains_key(cid)).map(|cid| to_node_id(*cid)).collect();
209        ak_children.extend(virtual_children);
210        node.set_children(ak_children);
211        nodes.push((nid, node));
212    }
213
214    let focus_node_id = match focus {
215        Some(fid) if sem_map.contains_key(&fid) => to_node_id(fid),
216        _ => root_node_id.unwrap_or(NodeId(0u64)),
217    };
218
219    let tree_info = if is_initial {
220        Some(Tree {
221            root: root_node_id.unwrap_or(NodeId(0u64)),
222            toolkit_name: Some("mgui".into()),
223            toolkit_version: Some(env!("CARGO_PKG_VERSION").into()),
224        })
225    } else {
226        None
227    };
228
229    TreeUpdate { nodes, tree: tree_info, focus: focus_node_id }
230}
231
232// =============================================================================
233// Action 解析辅助(NodeId → ElementId)
234// =============================================================================
235
236/// 把 NodeId 转回 ElementId(accesskit NodeId.0 = slotmap KeyData.as_ffi())
237pub fn node_id_to_element_id(nid: NodeId) -> ElementId {
238    ElementId::from_ffi(nid.0)
239}
240
241/// 从语义快照中取元素的中心点(逻辑像素);找不到返回 None。
242pub fn center_from_semantics(semantics: &[(ElementId, SemanticsData)], el_id: ElementId) -> Option<Point> {
243    semantics
244        .iter()
245        .find(|(id, _)| *id == el_id)
246        .map(|(_, sd)| Point::new(sd.bounds.x + sd.bounds.width / 2.0, sd.bounds.y + sd.bounds.height / 2.0))
247}
248
249/// 平台无关的 AccessKit 动作路由(Focus / Click / SetValue)。
250///
251/// desktop 单/多窗口 host 共用同一份逻辑,避免 SetValue 角色映射、now_ms、
252/// 目标失效处理各自漂移。返回值 = 是否已消费。
253pub fn dispatch_action(
254    tree: &mut ElementTree,
255    semantics: &[(ElementId, SemanticsData)],
256    request: &ActionRequest,
257    now_ms: u64,
258    fallback_center: Point,
259) -> bool {
260    // 虚拟语义子项:NodeId 不在元素空间,按建树时的确定性分配反推归属元素与行 bounds
261    if let Some(target) = virtual_item_target(semantics, request.target) {
262        match request.action {
263            Action::Click => {
264                let rect = target.rect;
265                let center = Point::new(rect.x + rect.width * 0.5, rect.y + rect.height * 0.5);
266                let data = PointerData::new(center, now_ms);
267                tree.request_focus(target.owner);
268                tree.dispatch_event(&WidgetEvent::PointerDown(data), center);
269                tree.dispatch_event(&WidgetEvent::PointerUp(data), center);
270            }
271            Action::Focus => tree.request_focus(target.owner),
272            Action::Expand if target.role == SemanticsRole::TreeItem && target.expanded == Some(false) => {
273                tree.request_focus(target.owner);
274                tree.dispatch_event_to(
275                    target.owner,
276                    &WidgetEvent::SetExpanded { item: Some(target.id), expanded: true },
277                );
278            }
279            Action::Collapse if target.role == SemanticsRole::TreeItem && target.expanded == Some(true) => {
280                tree.request_focus(target.owner);
281                tree.dispatch_event_to(
282                    target.owner,
283                    &WidgetEvent::SetExpanded { item: Some(target.id), expanded: false },
284                );
285            }
286            Action::SetTextSelection if target.role == SemanticsRole::TextRun => {
287                let Some(ActionData::SetTextSelection(selection)) = request.data.as_ref() else {
288                    return false;
289                };
290                let Some((anchor, focus)) = map_text_selection(semantics, target.owner, selection) else {
291                    log::debug!("AccessKit SetTextSelection: 无法映射文本位置到宿主 {:?}", target.owner);
292                    return false;
293                };
294                tree.request_focus(target.owner);
295                tree.dispatch_event_to(target.owner, &WidgetEvent::SetTextSelection { anchor, focus });
296            }
297            Action::ScrollIntoView => {
298                if !tree.reveal(target.owner, target.rect) {
299                    return false;
300                }
301            }
302            _ => return false,
303        }
304        return true;
305    }
306
307    let el_id = node_id_to_element_id(request.target);
308    match request.action {
309        Action::Focus => {
310            tree.request_focus(el_id);
311        }
312        Action::Click => {
313            let center = center_from_semantics(semantics, el_id).unwrap_or(fallback_center);
314            let data = PointerData::new(center, now_ms);
315            tree.request_focus(el_id);
316            tree.dispatch_event(&WidgetEvent::PointerDown(data), center);
317            tree.dispatch_event(&WidgetEvent::PointerUp(data), center);
318        }
319        Action::SetValue => {
320            // 按 ElementId 反查语义角色 → 定向投递给目标控件;
321            // state 改值后走各自 on_change,自然写回对应的 Signal
322            let role = semantics.iter().find(|(id, _)| *id == el_id).map(|(_, sd)| sd.role);
323            let event = match (role, request.data.clone()) {
324                (Some(SemanticsRole::TextInput), Some(ActionData::Value(s))) => {
325                    Some(WidgetEvent::SetText(s.to_string()))
326                }
327                (Some(SemanticsRole::Slider | SemanticsRole::Splitter), Some(ActionData::NumericValue(v))) => {
328                    Some(WidgetEvent::SetValue((v as f32).clamp(0.0, 1.0)))
329                }
330                // Windows UIA ValuePattern 回传字符串形式的 Value,
331                // 而非 NumericValue;不接这条,SRAI 设值在 Win 上无效
332                (Some(SemanticsRole::Slider | SemanticsRole::Splitter), Some(ActionData::Value(s))) => {
333                    s.parse::<f64>().ok().map(|v| WidgetEvent::SetValue((v as f32).clamp(0.0, 1.0)))
334                }
335                (Some(role), data) => {
336                    log::debug!("AccessKit SetValue ignored: role={role:?} data={data:?}");
337                    None
338                }
339                (None, _) => {
340                    log::debug!("AccessKit SetValue: target {el_id:?} not in semantics tree");
341                    None
342                }
343            };
344            let Some(event) = event else { return false };
345            if !tree.dispatch_event_to(el_id, &event) {
346                log::debug!("AccessKit SetValue: target {el_id:?} is no longer active");
347                return false;
348            }
349        }
350        Action::SetTextSelection => {
351            let Some(ActionData::SetTextSelection(selection)) = request.data.as_ref() else {
352                return false;
353            };
354            let Some((anchor, focus)) = map_text_selection(semantics, el_id, selection) else {
355                log::debug!("AccessKit SetTextSelection: 无法映射文本位置到 {el_id:?}");
356                return false;
357            };
358            tree.request_focus(el_id);
359            if !tree.dispatch_event_to(el_id, &WidgetEvent::SetTextSelection { anchor, focus }) {
360                log::debug!("AccessKit SetTextSelection: target {el_id:?} is no longer active");
361                return false;
362            }
363        }
364        Action::ScrollIntoView => {
365            let Some(bounds) = semantics.iter().find(|(id, _)| *id == el_id).map(|(_, sd)| sd.bounds) else {
366                log::debug!("AccessKit ScrollIntoView: target {el_id:?} not in semantics tree");
367                return false;
368            };
369            if !tree.reveal(el_id, bounds) {
370                log::debug!("AccessKit ScrollIntoView: no scroll container for {el_id:?}");
371                return false;
372            }
373        }
374        other => {
375            log::debug!("AccessKit unhandled action {other:?} on {el_id:?}");
376            return false;
377        }
378    }
379    true
380}
381
382/// 建树时为 TextRun 虚拟项分配的节点信息(跨行选区/动作映射用)。
383struct TextRunNode {
384    node: NodeId,
385    start_char: usize,
386    char_count: usize,
387}
388
389/// 虚拟项节点构建(前序分配 id,bounds 逐级累加)。
390fn push_virtual_nodes(
391    items: &[mgui_core::VirtualSemanticItem],
392    origin: Point,
393    dpr: f32,
394    counter: &mut u64,
395    nodes: &mut Vec<(NodeId, Node)>,
396    out: &mut Vec<NodeId>,
397    text_runs: &mut Vec<TextRunNode>,
398) {
399    for item in items {
400        let left = origin.x + item.bounds.x;
401        let top = origin.y + item.bounds.y;
402        let vid = NodeId(VIRTUAL_NODE_ID_BASE - *counter);
403        *counter += 1;
404
405        let mut vnode = Node::new(to_accesskit_role(item.role));
406        if item.role == SemanticsRole::TextRun {
407            // TextRun 的文本放在 value 属性(而不是 label);空行也要写空串
408            vnode.set_value(Box::<str>::from(item.label.as_str()));
409            if let Some(run) = &item.text_run {
410                vnode.set_character_lengths(run.character_lengths.clone());
411                if let Some(positions) = &run.character_positions {
412                    vnode.set_character_positions(positions.clone());
413                }
414                if let Some(widths) = &run.character_widths {
415                    vnode.set_character_widths(widths.clone());
416                }
417                vnode.set_text_direction(if run.rtl { TextDirection::RightToLeft } else { TextDirection::LeftToRight });
418                if item.enabled {
419                    vnode.add_action(Action::SetTextSelection);
420                }
421                text_runs.push(TextRunNode {
422                    node: vid,
423                    start_char: run.start_char,
424                    char_count: run.character_lengths.len(),
425                });
426            }
427        } else if !item.label.is_empty() {
428            vnode.set_label(Box::<str>::from(item.label.as_str()));
429        }
430        if let Some(selected) = item.selected {
431            vnode.set_selected(selected);
432        }
433        if let Some(expanded) = item.expanded {
434            vnode.set_expanded(expanded);
435        }
436        if !item.enabled {
437            vnode.set_disabled();
438        } else {
439            if matches!(
440                item.role,
441                SemanticsRole::Button
442                    | SemanticsRole::TreeItem
443                    | SemanticsRole::ListItem
444                    | SemanticsRole::MenuItem
445                    | SemanticsRole::RadioButton
446                    | SemanticsRole::Tab
447                    | SemanticsRole::GridRow
448                    | SemanticsRole::GridCell
449            ) {
450                // 点击由 dispatch_action 反推 (owner, bounds) 后合成指针事件
451                vnode.add_action(Action::Click);
452            }
453            // 树节点按展开状态暴露 Expand/Collapse
454            if item.role == SemanticsRole::TreeItem {
455                match item.expanded {
456                    Some(true) => vnode.add_action(Action::Collapse),
457                    Some(false) => vnode.add_action(Action::Expand),
458                    None => {}
459                }
460            }
461            vnode.add_action(Action::ScrollIntoView);
462        }
463        vnode.set_bounds(accesskit::Rect::new(
464            left as f64 * dpr as f64,
465            top as f64 * dpr as f64,
466            (left + item.bounds.width) as f64 * dpr as f64,
467            (top + item.bounds.height) as f64 * dpr as f64,
468        ));
469
470        let mut children = Vec::new();
471        push_virtual_nodes(&item.children, Point::new(left, top), dpr, counter, nodes, &mut children, text_runs);
472        vnode.set_children(children);
473        nodes.push((vid, vnode));
474        out.push(vid);
475    }
476}
477
478/// 字符索引 → 所在行 TextRun 节点(边界取后一行,行尾硬换行归前一行)。
479fn locate_text_run(runs: &[TextRunNode], char_index: usize) -> Option<(NodeId, usize)> {
480    let chosen = runs
481        .iter()
482        .filter(|run| run.start_char <= char_index)
483        .max_by_key(|run| run.start_char)
484        .or_else(|| runs.first())?;
485    let local = char_index.saturating_sub(chosen.start_char).min(chosen.char_count);
486    Some((chosen.node, local))
487}
488
489/// 按建树顺序重建所有 TextRun 节点(NodeId + 宿主 + 全局字符范围)。
490fn text_run_nodes(semantics: &[(ElementId, SemanticsData)]) -> Vec<(ElementId, TextRunNode)> {
491    fn walk(
492        items: &[mgui_core::VirtualSemanticItem],
493        owner: ElementId,
494        counter: &mut u64,
495        out: &mut Vec<(ElementId, TextRunNode)>,
496    ) {
497        for item in items {
498            let vid = NodeId(VIRTUAL_NODE_ID_BASE - *counter);
499            *counter += 1;
500            if let Some(run) = &item.text_run {
501                out.push((
502                    owner,
503                    TextRunNode { node: vid, start_char: run.start_char, char_count: run.character_lengths.len() },
504                ));
505            }
506            walk(&item.children, owner, counter, out);
507        }
508    }
509
510    let mut counter = 0;
511    let mut out = Vec::new();
512    for (owner, sd) in semantics {
513        walk(&sd.virtual_items, *owner, &mut counter, &mut out);
514    }
515    out
516}
517
518/// AccessKit 文本位置 → 宿主文本的全局字符索引。
519fn map_text_selection(
520    semantics: &[(ElementId, SemanticsData)],
521    owner: ElementId,
522    selection: &TextSelection,
523) -> Option<(usize, usize)> {
524    let runs = text_run_nodes(semantics);
525    let resolve = |pos: TextPosition| -> Option<usize> {
526        if let Some((_, run)) = runs.iter().find(|(o, run)| *o == owner && run.node == pos.node) {
527            return Some(run.start_char + pos.character_index.min(run.char_count));
528        }
529        // 位置直接引用宿主节点:按全局字符索引处理
530        if pos.node == to_node_id(owner) {
531            return Some(pos.character_index);
532        }
533        None
534    };
535    Some((resolve(selection.anchor)?, resolve(selection.focus)?))
536}
537
538struct VirtualItemTarget {
539    owner: ElementId,
540    rect: Rect,
541    id: u64,
542    role: SemanticsRole,
543    expanded: Option<bool>,
544}
545
546/// 虚拟子项 NodeId 起点;[`ElementId::A11Y_ROOT`] 占用 NodeId(u64::MAX)。
547const VIRTUAL_NODE_ID_BASE: u64 = u64::MAX - 1;
548
549/// 按建树时的确定性顺序,把虚拟项 NodeId 反推为宿主元素与行信息。
550///
551/// `build_tree_update` 从 `VIRTUAL_NODE_ID_BASE` 递减分配虚拟 NodeId,顺序与语义快照一致;
552/// 动作路由用同一顺序复算即可,无需额外注册表。
553fn virtual_item_target(semantics: &[(ElementId, SemanticsData)], target: NodeId) -> Option<VirtualItemTarget> {
554    fn find(
555        items: &[mgui_core::VirtualSemanticItem],
556        origin: Point,
557        target: NodeId,
558        counter: &mut u64,
559    ) -> Option<(Rect, u64, SemanticsRole, Option<bool>)> {
560        for item in items {
561            let left = origin.x + item.bounds.x;
562            let top = origin.y + item.bounds.y;
563            let vid = NodeId(VIRTUAL_NODE_ID_BASE - *counter);
564            *counter += 1;
565            if vid == target {
566                return Some((
567                    Rect::new(left, top, item.bounds.width, item.bounds.height),
568                    item.id,
569                    item.role,
570                    item.expanded,
571                ));
572            }
573            if let Some(found) = find(&item.children, Point::new(left, top), target, counter) {
574                return Some(found);
575            }
576        }
577        None
578    }
579
580    let mut counter: u64 = 0;
581    for (owner, sd) in semantics {
582        if let Some((rect, id, role, expanded)) =
583            find(&sd.virtual_items, Point::new(sd.bounds.x, sd.bounds.y), target, &mut counter)
584        {
585            return Some(VirtualItemTarget { owner: *owner, rect, id, role, expanded });
586        }
587    }
588    None
589}
590
591// =============================================================================
592// 单元测试
593// =============================================================================
594
595#[cfg(test)]
596mod tests {
597    use super::*;
598    use std::cell::RefCell;
599    use std::rc::Rc;
600
601    use mgui_core::render_object::RRectRenderObject;
602    use mgui_core::widget::{State, Widget};
603    use mgui_core::{Color, ElementTree, Rect, Size, WidgetNode};
604
605    #[derive(Debug)]
606    struct RecorderWidget {
607        log: Rc<RefCell<Vec<WidgetEvent>>>,
608    }
609
610    impl Widget for RecorderWidget {
611        fn as_any(&self) -> &dyn std::any::Any {
612            self
613        }
614        fn is_stateful(&self) -> bool {
615            true
616        }
617        fn create_state(&self) -> Option<Box<dyn State>> {
618            Some(Box::new(RecorderState { current: None, log: Rc::clone(&self.log) }))
619        }
620        fn create_render_object(&self) -> Box<dyn mgui_core::render_object::RenderObject> {
621            Box::new(RRectRenderObject::new(Size::new(100.0, 100.0), Color::WHITE, 0.0))
622        }
623    }
624
625    struct RecorderState {
626        current: Option<WidgetNode>,
627        log: Rc<RefCell<Vec<WidgetEvent>>>,
628    }
629
630    impl State for RecorderState {
631        fn as_any(&self) -> &dyn std::any::Any {
632            self
633        }
634        fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
635            self
636        }
637        fn widget(&self) -> &WidgetNode {
638            self.current.as_ref().expect("widget set")
639        }
640        fn set_widget(&mut self, widget: WidgetNode) {
641            self.current = Some(widget);
642        }
643        fn handle_event(&mut self, event: &WidgetEvent, _local_pos: Point) {
644            self.log.borrow_mut().push(event.clone());
645        }
646    }
647
648    fn make_semantics(role: SemanticsRole, id: u64, bounds: Rect) -> SemanticsData {
649        SemanticsData {
650            role,
651            label: Some(format!("node-{id}")),
652            value: None,
653            toggled: None,
654            expanded: None,
655            selected: None,
656            modal: false,
657            live: None,
658            virtual_items: Vec::new(),
659            text_selection: None,
660            read_only: false,
661            enabled: true,
662            focusable: role == SemanticsRole::Button || role == SemanticsRole::CheckBox,
663            numeric: None,
664            bounds,
665            children: vec![],
666        }
667    }
668
669    #[test]
670    fn virtual_node_ids_avoid_synthetic_root_collision() {
671        let mut cd = make_semantics(SemanticsRole::List, 7, Rect::new(0.0, 0.0, 200.0, 100.0));
672        cd.virtual_items = vec![mgui_core::VirtualSemanticItem {
673            id: 0,
674            role: SemanticsRole::ListItem,
675            label: "first".into(),
676            selected: None,
677            expanded: None,
678            enabled: true,
679            bounds: Rect::new(0.0, 0.0, 200.0, 50.0),
680            children: vec![],
681            text_run: None,
682        }];
683        let semantics = vec![(ElementId::A11Y_ROOT, cd)];
684        let update = build_tree_update(&semantics, None, 1.0, true);
685        let root_id = update.tree.as_ref().expect("initial tree").root;
686        assert_eq!(root_id, NodeId(u64::MAX), "A11Y_ROOT 映射到 u64::MAX");
687        let virtual_id = NodeId(VIRTUAL_NODE_ID_BASE);
688        assert_ne!(root_id, virtual_id);
689        assert!(update.nodes.iter().any(|(id, _)| *id == virtual_id));
690        assert_eq!(update.nodes.iter().filter(|(id, _)| *id == root_id).count(), 1);
691    }
692
693    #[test]
694    fn filtered_tree_keeps_navigation_and_content_branches() {
695        let root_id = ElementId::A11Y_ROOT;
696        let two = ElementId::from_ffi(2);
697        let six = ElementId::from_ffi(6);
698        let seven = ElementId::from_ffi(7);
699        let nine = ElementId::from_ffi(9);
700        let ten = ElementId::from_ffi(10);
701
702        let mut root = make_semantics(SemanticsRole::Container, 0, Rect::new(0.0, 0.0, 960.0, 700.0));
703        root.children = vec![two];
704        let mut mid = make_semantics(SemanticsRole::Container, 2, Rect::new(0.0, 0.0, 960.0, 700.0));
705        mid.children = vec![six, nine];
706        let mut nav_box = make_semantics(SemanticsRole::Container, 6, Rect::new(0.0, 0.0, 220.0, 700.0));
707        nav_box.children = vec![seven];
708        let mut nav = make_semantics(SemanticsRole::List, 7, Rect::new(0.0, 0.0, 220.0, 1260.0));
709        nav.virtual_items = vec![mgui_core::VirtualSemanticItem {
710            id: 0,
711            role: SemanticsRole::ListItem,
712            label: "Button".into(),
713            selected: Some(true),
714            expanded: None,
715            enabled: true,
716            bounds: Rect::new(0.0, 0.0, 220.0, 44.0),
717            children: vec![],
718            text_run: None,
719        }];
720        let mut panel = make_semantics(SemanticsRole::TabPanel, 9, Rect::new(220.0, 0.0, 740.0, 506.0));
721        panel.children = vec![ten];
722        let content = make_semantics(SemanticsRole::Label, 10, Rect::new(220.0, 0.0, 740.0, 16.0));
723
724        let semantics = vec![(root_id, root), (two, mid), (six, nav_box), (seven, nav), (nine, panel), (ten, content)];
725        let update = build_tree_update(&semantics, None, 1.0, true);
726        let tree = accesskit_consumer::Tree::new(update, false);
727        let root = tree.state().root();
728        let children: Vec<_> =
729            root.filtered_children(accesskit_consumer::common_filter).map(|node| (node.role(), node.label())).collect();
730        assert!(
731            children.iter().any(|(role, _)| *role == Role::List),
732            "Navigation List 应出现在根过滤子节点: {children:?}"
733        );
734        assert!(
735            children.iter().any(|(role, _)| *role == Role::TabPanel),
736            "TabPanel 内容分支应出现在根过滤子节点: {children:?}"
737        );
738        // UIA Navigate(NextSibling) 走 following_filtered_siblings;nav 的祖先
739        // 是 GenericContainer(被过滤),必须能跨过祖先找到 TabPanel。
740        let nav_node = root
741            .filtered_children(accesskit_consumer::common_filter)
742            .find(|node| node.role() == Role::List)
743            .expect("Navigation List");
744        let next = nav_node.following_filtered_siblings(accesskit_consumer::common_filter).next();
745        assert_eq!(next.map(|node| node.role()), Some(Role::TabPanel), "List 的下一个过滤兄弟应为 TabPanel");
746    }
747
748    #[test]
749    fn virtual_item_target_roundtrip() {
750        let mut sd = make_semantics(SemanticsRole::Grid, 9, Rect::new(10.0, 20.0, 100.0, 80.0));
751        sd.virtual_items = vec![mgui_core::VirtualSemanticItem {
752            id: 1,
753            role: SemanticsRole::GridRow,
754            label: "row".into(),
755            selected: Some(true),
756            expanded: None,
757            enabled: true,
758            bounds: Rect::new(0.0, 24.0, 100.0, 24.0),
759            children: vec![mgui_core::VirtualSemanticItem {
760                id: 2,
761                role: SemanticsRole::GridCell,
762                label: "cell".into(),
763                selected: None,
764                expanded: None,
765                enabled: true,
766                bounds: Rect::new(10.0, 0.0, 50.0, 24.0),
767                children: Vec::new(),
768                text_run: None,
769            }],
770            text_run: None,
771        }];
772        let owner = ElementId::from_ffi(9);
773        let semantics = vec![(owner, sd)];
774        let got = virtual_item_target(&semantics, NodeId(VIRTUAL_NODE_ID_BASE)).expect("virtual target");
775        assert_eq!(got.owner, owner);
776        assert_eq!(got.rect, Rect::new(10.0, 44.0, 100.0, 24.0));
777        assert_eq!((got.id, got.role), (1, SemanticsRole::GridRow));
778
779        // 嵌套子项:前序第二个 id,bounds 逐级累加
780        let got = virtual_item_target(&semantics, NodeId(VIRTUAL_NODE_ID_BASE - 1)).expect("nested target");
781        assert_eq!(got.owner, owner);
782        assert_eq!(got.rect, Rect::new(20.0, 44.0, 50.0, 24.0));
783        assert_eq!((got.id, got.role), (2, SemanticsRole::GridCell));
784    }
785
786    #[test]
787    fn virtual_tree_items_expose_expand_collapse_and_grid_cells_click() {
788        let mut tree_sd = make_semantics(SemanticsRole::Tree, 1, Rect::new(0.0, 0.0, 200.0, 120.0));
789        tree_sd.virtual_items = vec![
790            mgui_core::VirtualSemanticItem {
791                id: 1,
792                role: SemanticsRole::TreeItem,
793                label: "collapsed".into(),
794                selected: Some(false),
795                expanded: Some(false),
796                enabled: true,
797                bounds: Rect::new(0.0, 0.0, 200.0, 24.0),
798                children: Vec::new(),
799                text_run: None,
800            },
801            mgui_core::VirtualSemanticItem {
802                id: 2,
803                role: SemanticsRole::TreeItem,
804                label: "expanded".into(),
805                selected: Some(false),
806                expanded: Some(true),
807                enabled: true,
808                bounds: Rect::new(0.0, 24.0, 200.0, 24.0),
809                children: Vec::new(),
810                text_run: None,
811            },
812            mgui_core::VirtualSemanticItem {
813                id: 3,
814                role: SemanticsRole::TreeItem,
815                label: "leaf".into(),
816                selected: Some(false),
817                expanded: None,
818                enabled: true,
819                bounds: Rect::new(0.0, 48.0, 200.0, 24.0),
820                children: Vec::new(),
821                text_run: None,
822            },
823        ];
824        let semantics = vec![(ElementId::from_ffi(1), tree_sd)];
825        let update = build_tree_update(&semantics, None, 1.0, true);
826        let node = |offset: u64| {
827            update
828                .nodes
829                .iter()
830                .find(|(nid, _)| *nid == NodeId(VIRTUAL_NODE_ID_BASE - offset))
831                .map(|(_, node)| node)
832                .expect("virtual node")
833        };
834        assert!(node(0).supports_action(Action::Expand), "折叠节点暴露 Expand");
835        assert!(!node(0).supports_action(Action::Collapse));
836        assert!(node(1).supports_action(Action::Collapse), "展开节点暴露 Collapse");
837        assert!(!node(1).supports_action(Action::Expand));
838        assert!(!node(2).supports_action(Action::Expand), "叶子无展开动作");
839        assert!(!node(2).supports_action(Action::Collapse));
840        assert!(node(2).supports_action(Action::Click), "树节点仍可点击选择");
841
842        let mut grid_sd = make_semantics(SemanticsRole::Grid, 2, Rect::new(0.0, 0.0, 200.0, 80.0));
843        grid_sd.virtual_items = vec![mgui_core::VirtualSemanticItem {
844            id: 7,
845            role: SemanticsRole::GridRow,
846            label: "row".into(),
847            selected: Some(false),
848            expanded: None,
849            enabled: true,
850            bounds: Rect::new(0.0, 0.0, 200.0, 24.0),
851            children: vec![mgui_core::VirtualSemanticItem {
852                id: 0,
853                role: SemanticsRole::GridCell,
854                label: "cell".into(),
855                selected: None,
856                expanded: None,
857                enabled: true,
858                bounds: Rect::new(0.0, 0.0, 100.0, 24.0),
859                children: Vec::new(),
860                text_run: None,
861            }],
862            text_run: None,
863        }];
864        let semantics = vec![(ElementId::from_ffi(2), grid_sd)];
865        let update = build_tree_update(&semantics, None, 1.0, true);
866        let cell = update
867            .nodes
868            .iter()
869            .find(|(nid, _)| *nid == NodeId(VIRTUAL_NODE_ID_BASE - 1))
870            .map(|(_, node)| node)
871            .expect("grid cell node");
872        assert!(cell.supports_action(Action::Click), "GridCell 点击应路由到行");
873    }
874
875    fn text_input_with_two_runs(id: u64) -> SemanticsData {
876        let mut sd = make_semantics(SemanticsRole::TextInput, id, Rect::new(0.0, 0.0, 200.0, 40.0));
877        sd.value = Some("ab\ncd".into());
878        sd.text_selection = Some((1, 4));
879        sd.virtual_items = vec![
880            mgui_core::VirtualSemanticItem {
881                id: 0,
882                role: SemanticsRole::TextRun,
883                label: "ab\n".into(),
884                selected: None,
885                expanded: None,
886                enabled: true,
887                bounds: Rect::new(10.0, 0.0, 20.0, 20.0),
888                children: Vec::new(),
889                text_run: Some(mgui_core::VirtualTextRun {
890                    character_lengths: vec![1, 1, 1],
891                    start_char: 0,
892                    character_positions: Some(vec![0.0, 8.0, 16.0]),
893                    character_widths: Some(vec![8.0, 8.0, 0.0]),
894                    rtl: false,
895                }),
896            },
897            mgui_core::VirtualSemanticItem {
898                id: 1,
899                role: SemanticsRole::TextRun,
900                label: "cd".into(),
901                selected: None,
902                expanded: None,
903                enabled: true,
904                bounds: Rect::new(10.0, 20.0, 20.0, 20.0),
905                children: Vec::new(),
906                text_run: Some(mgui_core::VirtualTextRun {
907                    character_lengths: vec![1, 1],
908                    start_char: 3,
909                    character_positions: Some(vec![0.0, 8.0]),
910                    character_widths: Some(vec![8.0, 8.0]),
911                    rtl: false,
912                }),
913            },
914        ];
915        sd
916    }
917
918    #[test]
919    fn text_input_exposes_line_runs_and_host_selection() {
920        let owner = ElementId::from_ffi(7);
921        let semantics = vec![(owner, text_input_with_two_runs(7))];
922        let update = build_tree_update(&semantics, None, 1.0, true);
923
924        let host = update
925            .nodes
926            .iter()
927            .find(|(nid, _)| *nid == to_node_id(owner))
928            .map(|(_, node)| node)
929            .expect("text input host");
930        let selection = host.text_selection().expect("选区挂在文本框宿主上");
931        assert_eq!(selection.anchor.node, NodeId(VIRTUAL_NODE_ID_BASE));
932        assert_eq!(selection.anchor.character_index, 1);
933        assert_eq!(selection.focus.node, NodeId(VIRTUAL_NODE_ID_BASE - 1), "focus 应映射到第二行");
934        assert_eq!(selection.focus.character_index, 1);
935        assert!(host.supports_action(Action::SetTextSelection));
936
937        let first = update
938            .nodes
939            .iter()
940            .find(|(nid, _)| *nid == NodeId(VIRTUAL_NODE_ID_BASE))
941            .map(|(_, node)| node)
942            .expect("first line");
943        assert_eq!(first.role(), Role::TextRun);
944        assert_eq!(first.value(), Some("ab\n"));
945        assert_eq!(first.character_lengths(), &[1, 1, 1]);
946        assert_eq!(first.character_positions(), Some(&[0.0, 8.0, 16.0][..]));
947        assert_eq!(first.character_widths(), Some(&[8.0, 8.0, 0.0][..]));
948        assert_eq!(first.text_direction(), Some(TextDirection::LeftToRight));
949        assert!(first.text_selection().is_none(), "选区不再挂在行节点");
950
951        let second = update
952            .nodes
953            .iter()
954            .find(|(nid, _)| *nid == NodeId(VIRTUAL_NODE_ID_BASE - 1))
955            .map(|(_, node)| node)
956            .expect("second line");
957        assert_eq!(second.value(), Some("cd"));
958        assert_eq!(second.character_lengths(), &[1, 1]);
959    }
960
961    #[test]
962    fn set_text_selection_on_host_maps_across_runs() {
963        let log = Rc::new(RefCell::new(Vec::<WidgetEvent>::new()));
964        let mut tree = ElementTree::new();
965        tree.mount(WidgetNode::new(RecorderWidget { log: Rc::clone(&log) }));
966        let owner = tree.root_id().expect("root element");
967
968        let semantics = vec![(owner, text_input_with_two_runs(8))];
969        let selection = TextSelection {
970            anchor: TextPosition { node: NodeId(VIRTUAL_NODE_ID_BASE), character_index: 1 },
971            focus: TextPosition { node: NodeId(VIRTUAL_NODE_ID_BASE - 1), character_index: 2 },
972        };
973        let request = ActionRequest {
974            action: Action::SetTextSelection,
975            target: to_node_id(owner),
976            data: Some(ActionData::SetTextSelection(selection)),
977        };
978        assert!(dispatch_action(&mut tree, &semantics, &request, 0, Point::ZERO));
979        assert!(
980            matches!(log.borrow().last(), Some(WidgetEvent::SetTextSelection { anchor: 1, focus: 5 })),
981            "跨行选区应转换为全局字符索引: {:?}",
982            log.borrow()
983        );
984    }
985
986    #[test]
987    fn set_text_selection_on_run_target_maps_to_global_chars() {
988        let log = Rc::new(RefCell::new(Vec::<WidgetEvent>::new()));
989        let mut tree = ElementTree::new();
990        tree.mount(WidgetNode::new(RecorderWidget { log: Rc::clone(&log) }));
991        let owner = tree.root_id().expect("root element");
992
993        let semantics = vec![(owner, text_input_with_two_runs(9))];
994        let selection = TextSelection {
995            anchor: TextPosition { node: NodeId(VIRTUAL_NODE_ID_BASE), character_index: 0 },
996            focus: TextPosition { node: NodeId(VIRTUAL_NODE_ID_BASE - 1), character_index: 1 },
997        };
998        let request = ActionRequest {
999            action: Action::SetTextSelection,
1000            target: NodeId(VIRTUAL_NODE_ID_BASE - 1),
1001            data: Some(ActionData::SetTextSelection(selection)),
1002        };
1003        assert!(dispatch_action(&mut tree, &semantics, &request, 0, Point::ZERO));
1004        assert!(
1005            matches!(log.borrow().last(), Some(WidgetEvent::SetTextSelection { anchor: 0, focus: 4 })),
1006            "行节点动作也应换算为全局字符索引: {:?}",
1007            log.borrow()
1008        );
1009    }
1010
1011    #[test]
1012    fn expand_action_routes_set_expanded_to_owner() {
1013        let log = Rc::new(RefCell::new(Vec::<WidgetEvent>::new()));
1014        let mut tree = ElementTree::new();
1015        tree.mount(WidgetNode::new(RecorderWidget { log: Rc::clone(&log) }));
1016        let owner = tree.root_id().expect("root element");
1017
1018        let mut sd = make_semantics(SemanticsRole::Tree, 1, Rect::new(0.0, 0.0, 200.0, 100.0));
1019        sd.virtual_items = vec![mgui_core::VirtualSemanticItem {
1020            id: 42,
1021            role: SemanticsRole::TreeItem,
1022            label: "src".into(),
1023            selected: Some(false),
1024            expanded: Some(false),
1025            enabled: true,
1026            bounds: Rect::new(0.0, 0.0, 200.0, 24.0),
1027            children: Vec::new(),
1028            text_run: None,
1029        }];
1030        let mut semantics = vec![(owner, sd)];
1031        let expand = ActionRequest { action: Action::Expand, target: NodeId(VIRTUAL_NODE_ID_BASE), data: None };
1032        assert!(dispatch_action(&mut tree, &semantics, &expand, 0, Point::ZERO));
1033        assert!(
1034            matches!(log.borrow().last(), Some(WidgetEvent::SetExpanded { item: Some(42), expanded: true })),
1035            "Expand 应定向投递 SetExpanded: {:?}",
1036            log.borrow()
1037        );
1038
1039        semantics[0].1.virtual_items[0].expanded = Some(true);
1040        let collapse = ActionRequest { action: Action::Collapse, target: NodeId(VIRTUAL_NODE_ID_BASE), data: None };
1041        assert!(dispatch_action(&mut tree, &semantics, &collapse, 0, Point::ZERO));
1042        assert!(
1043            matches!(log.borrow().last(), Some(WidgetEvent::SetExpanded { item: Some(42), expanded: false })),
1044            "Collapse 应定向投递 SetExpanded"
1045        );
1046    }
1047
1048    fn sample_tree() -> Vec<(ElementId, SemanticsData)> {
1049        let root = (0.0, 0.0, 800.0, 600.0);
1050        let btn = (100.0, 100.0, 200.0, 48.0);
1051        let label = (100.0, 100.0, 120.0, 20.0);
1052        let cb = (100.0, 200.0, 24.0, 24.0);
1053
1054        vec![
1055            (
1056                ElementId::from_ffi(1),
1057                make_semantics(SemanticsRole::Container, 1, Rect::new(root.0, root.1, root.2, root.3)),
1058            ),
1059            (ElementId::from_ffi(2), make_semantics(SemanticsRole::Button, 2, Rect::new(btn.0, btn.1, btn.2, btn.3))),
1060            (
1061                ElementId::from_ffi(3),
1062                make_semantics(SemanticsRole::Label, 3, Rect::new(label.0, label.1, label.2, label.3)),
1063            ),
1064            (ElementId::from_ffi(4), make_semantics(SemanticsRole::CheckBox, 4, Rect::new(cb.0, cb.1, cb.2, cb.3))),
1065        ]
1066    }
1067
1068    #[test]
1069    fn role_mapping_smoke() {
1070        assert_eq!(to_accesskit_role(SemanticsRole::Button), Role::Button);
1071        assert_eq!(to_accesskit_role(SemanticsRole::CheckBox), Role::CheckBox);
1072        assert_eq!(to_accesskit_role(SemanticsRole::Slider), Role::Slider);
1073        assert_eq!(to_accesskit_role(SemanticsRole::TextInput), Role::TextInput);
1074        assert_eq!(to_accesskit_role(SemanticsRole::Label), Role::Label);
1075        assert_eq!(to_accesskit_role(SemanticsRole::Image), Role::Image);
1076        assert_eq!(to_accesskit_role(SemanticsRole::Container), Role::GenericContainer);
1077        assert_eq!(to_accesskit_role(SemanticsRole::Unknown), Role::Unknown);
1078        assert_eq!(to_accesskit_role(SemanticsRole::Menu), Role::Menu);
1079        assert_eq!(to_accesskit_role(SemanticsRole::MenuItem), Role::MenuItem);
1080        assert_eq!(to_accesskit_role(SemanticsRole::ComboBox), Role::ComboBox);
1081        assert_eq!(to_accesskit_role(SemanticsRole::RadioGroup), Role::RadioGroup);
1082        assert_eq!(to_accesskit_role(SemanticsRole::RadioButton), Role::RadioButton);
1083        assert_eq!(to_accesskit_role(SemanticsRole::Tooltip), Role::Tooltip);
1084        assert_eq!(to_accesskit_role(SemanticsRole::Splitter), Role::Splitter);
1085    }
1086
1087    #[test]
1088    fn tree_build_has_all_nodes() {
1089        let tree = sample_tree();
1090        let update = build_tree_update(&tree, None, 1.0, true);
1091        assert_eq!(update.nodes.len(), 4);
1092        assert!(update.tree.is_some());
1093    }
1094
1095    #[test]
1096    fn bounds_scaled_by_dpr() {
1097        let tree = sample_tree();
1098        let update = build_tree_update(&tree, None, 2.0, true);
1099        for (nid, node) in &update.nodes {
1100            if nid.0 == 2 {
1101                let b = node.bounds().unwrap();
1102                assert_eq!(b.x0, 200.0);
1103                assert_eq!(b.y0, 200.0);
1104                assert_eq!(b.x1, 600.0);
1105                assert_eq!(b.y1, 296.0);
1106            }
1107        }
1108    }
1109
1110    #[test]
1111    fn focus_mapping() {
1112        let tree = sample_tree();
1113        let btn_el = tree[1].0;
1114        let update = build_tree_update(&tree, Some(btn_el), 1.0, true);
1115        assert_eq!(update.focus, to_node_id(btn_el));
1116
1117        let u2 = build_tree_update(&tree, None, 1.0, true);
1118        assert_eq!(u2.focus, to_node_id(tree[0].0));
1119    }
1120
1121    #[test]
1122    fn non_focusable_no_focus_action() {
1123        let tree = sample_tree();
1124        let u = build_tree_update(&tree, None, 1.0, true);
1125        for (nid, node) in &u.nodes {
1126            if nid.0 == 3 {
1127                assert!(!node.supports_action(Action::Focus));
1128            }
1129            if nid.0 == 2 {
1130                assert!(node.supports_action(Action::Focus));
1131                assert!(node.supports_action(Action::Click));
1132            }
1133        }
1134    }
1135
1136    #[test]
1137    fn read_only_text_input_exposes_read_only_without_set_value() {
1138        let id = ElementId::from_ffi(9);
1139        let mut sd = make_semantics(SemanticsRole::TextInput, 9, Rect::new(0.0, 0.0, 200.0, 32.0));
1140        sd.read_only = true;
1141        sd.focusable = true;
1142        let u = build_tree_update(&[(id, sd)], None, 1.0, true);
1143        let (_, node) = u.nodes.iter().find(|(nid, _)| *nid == to_node_id(id)).expect("text input");
1144        assert!(node.is_read_only());
1145        assert!(!node.supports_action(Action::SetValue), "只读不应暴露 SetValue");
1146        assert!(node.supports_action(Action::Focus), "只读仍可聚焦");
1147    }
1148
1149    #[test]
1150    fn disabled_nodes_expose_no_actions() {
1151        let mut tree = sample_tree();
1152        tree[1].1.enabled = false;
1153        let u = build_tree_update(&tree, None, 1.0, true);
1154        let btn_nid = to_node_id(tree[1].0);
1155        let (_, node) = u.nodes.iter().find(|(nid, _)| *nid == btn_nid).expect("button node");
1156        assert!(!node.supports_action(Action::Focus));
1157        assert!(!node.supports_action(Action::Click));
1158    }
1159
1160    #[test]
1161    fn numeric_domain_published_for_slider() {
1162        let mut tree = sample_tree();
1163        let slider_id = ElementId::from_ffi(5);
1164        let mut sd = make_semantics(SemanticsRole::Slider, 5, Rect::new(0.0, 0.0, 200.0, 20.0));
1165        sd.numeric = Some(mgui_core::SemanticsNumericValue { value: 0.25, min: 0.0, max: 1.0, step: 0.01 });
1166        tree.push((slider_id, sd));
1167
1168        let u = build_tree_update(&tree, None, 1.0, true);
1169        let (_, node) = u.nodes.iter().find(|(nid, _)| *nid == to_node_id(slider_id)).expect("slider node");
1170        assert_eq!(node.numeric_value(), Some(0.25));
1171        assert_eq!(node.min_numeric_value(), Some(0.0));
1172        assert_eq!(node.max_numeric_value(), Some(1.0));
1173        assert_eq!(node.numeric_value_step(), Some(0.01));
1174        assert!(node.supports_action(Action::SetValue));
1175    }
1176
1177    #[test]
1178    fn splitter_exposes_focus_and_set_value() {
1179        let mut tree = sample_tree();
1180        let id = ElementId::from_ffi(6);
1181        let mut sd = make_semantics(SemanticsRole::Splitter, 6, Rect::new(200.0, 0.0, 8.0, 400.0));
1182        sd.focusable = true;
1183        sd.numeric = Some(mgui_core::SemanticsNumericValue { value: 0.4, min: 0.0, max: 1.0, step: 0.02 });
1184        tree.push((id, sd));
1185
1186        let u = build_tree_update(&tree, None, 1.0, true);
1187        let (_, node) = u.nodes.iter().find(|(nid, _)| *nid == to_node_id(id)).expect("splitter node");
1188        assert!(node.supports_action(Action::Focus));
1189        assert!(node.supports_action(Action::SetValue));
1190        assert_eq!(node.numeric_value(), Some(0.4));
1191    }
1192
1193    #[test]
1194    fn initial_vs_subsequent() {
1195        let tree = sample_tree();
1196        assert!(build_tree_update(&tree, None, 1.0, true).tree.is_some());
1197        assert!(build_tree_update(&tree, None, 1.0, false).tree.is_none());
1198    }
1199
1200    #[test]
1201    fn node_id_roundtrip() {
1202        let el = ElementId::from_ffi(0xDEADBEEF);
1203        let nid = to_node_id(el);
1204        assert_eq!(node_id_to_element_id(nid), el);
1205    }
1206
1207    #[test]
1208    fn extended_roles_modal_live_expand_selected_and_actions() {
1209        let rect = Rect::new(0.0, 0.0, 100.0, 40.0);
1210        let mut tree = vec![
1211            (ElementId::from_ffi(10), make_semantics(SemanticsRole::Dialog, 10, rect)),
1212            (ElementId::from_ffi(11), make_semantics(SemanticsRole::TreeItem, 11, rect)),
1213            (ElementId::from_ffi(12), make_semantics(SemanticsRole::Toast, 12, rect)),
1214            (ElementId::from_ffi(13), make_semantics(SemanticsRole::Progress, 13, rect)),
1215            (ElementId::from_ffi(14), make_semantics(SemanticsRole::Grid, 14, rect)),
1216            (ElementId::from_ffi(15), make_semantics(SemanticsRole::TabPanel, 15, rect)),
1217        ];
1218        tree[0].1.modal = true;
1219        tree[0].1.focusable = false;
1220        tree[1].1.expanded = Some(true);
1221        tree[1].1.selected = Some(true);
1222        tree[1].1.focusable = true;
1223        tree[2].1.live = Some(LiveRegion::Assertive);
1224        tree[2].1.focusable = false;
1225        tree[3].1.numeric = Some(mgui_core::SemanticsNumericValue { value: 0.5, min: 0.0, max: 1.0, step: 0.01 });
1226        tree[4].1.focusable = true;
1227
1228        let update = build_tree_update(&tree, None, 1.0, true);
1229        let node = |el: ElementId| {
1230            let nid = to_node_id(el);
1231            update.nodes.iter().find(|(id, _)| *id == nid).map(|(_, n)| n).expect("node")
1232        };
1233
1234        let dialog = node(ElementId::from_ffi(10));
1235        assert_eq!(dialog.role(), Role::Dialog);
1236        assert!(dialog.is_modal());
1237        assert!(!dialog.supports_action(Action::Focus));
1238
1239        let item = node(ElementId::from_ffi(11));
1240        assert_eq!(item.role(), Role::TreeItem);
1241        assert_eq!(item.is_expanded(), Some(true));
1242        assert_eq!(item.is_selected(), Some(true));
1243        assert!(item.supports_action(Action::Click), "TreeItem 可激活");
1244
1245        let toast = node(ElementId::from_ffi(12));
1246        assert_eq!(toast.role(), Role::Alert);
1247        assert_eq!(toast.live(), Some(accesskit::Live::Assertive), "Toast 应作为 assertive live region");
1248
1249        let progress = node(ElementId::from_ffi(13));
1250        assert_eq!(progress.role(), Role::ProgressIndicator);
1251        assert_eq!(progress.numeric_value(), Some(0.5));
1252
1253        assert_eq!(node(ElementId::from_ffi(14)).role(), Role::Grid);
1254        assert!(node(ElementId::from_ffi(14)).supports_action(Action::Focus));
1255        assert_eq!(node(ElementId::from_ffi(15)).role(), Role::TabPanel);
1256    }
1257
1258    #[test]
1259    fn dispatch_action_focuses_and_rejects_unsupported_targets() {
1260        use mgui_core::{Color, RRectWidget, Size, WidgetNode};
1261
1262        let mut tree = ElementTree::new();
1263        tree.mount(WidgetNode::new(RRectWidget::new(Size::new(40.0, 20.0), Color::WHITE, 0.0)));
1264        let id = tree.root_id().expect("root");
1265
1266        let focus = ActionRequest { action: Action::Focus, target: to_node_id(id), data: None };
1267        assert!(dispatch_action(&mut tree, &[], &focus, 0, Point::ZERO));
1268        assert_eq!(tree.focused_element(), Some(id), "Focus action 应更新树焦点");
1269
1270        // 语义快照里没有目标 → SetValue 不应对不存在/未知角色做任何事
1271        let set_value = ActionRequest {
1272            action: Action::SetValue,
1273            target: to_node_id(id),
1274            data: Some(ActionData::Value("x".into())),
1275        };
1276        assert!(!dispatch_action(&mut tree, &[], &set_value, 0, Point::ZERO));
1277    }
1278}