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 递减),避免与元素 id 冲突
95    let mut virtual_counter: u64 = 0;
96
97    for (el_id, sd) in tree {
98        let nid = to_node_id(*el_id);
99        let mut node = Node::new(to_accesskit_role(sd.role));
100
101        if let Some(label) = &sd.label {
102            if !label.is_empty() {
103                node.set_label(Box::<str>::from(label.as_str()));
104            }
105        }
106        if let Some(value) = &sd.value {
107            node.set_value(value.clone());
108        }
109        if let Some(toggled) = sd.toggled {
110            node.set_toggled(if toggled { accesskit::Toggled::True } else { accesskit::Toggled::False });
111        }
112        if let Some(expanded) = sd.expanded {
113            node.set_expanded(expanded);
114        }
115        if let Some(selected) = sd.selected {
116            node.set_selected(selected);
117        }
118        if sd.modal {
119            node.set_modal();
120        }
121        if let Some(live) = sd.live {
122            node.set_live(match live {
123                LiveRegion::Polite => accesskit::Live::Polite,
124                LiveRegion::Assertive => accesskit::Live::Assertive,
125            });
126        }
127
128        let bounds = accesskit::Rect::new(
129            sd.bounds.x as f64 * dpr as f64,
130            sd.bounds.y as f64 * dpr as f64,
131            (sd.bounds.x + sd.bounds.width) as f64 * dpr as f64,
132            (sd.bounds.y + sd.bounds.height) as f64 * dpr as f64,
133        );
134        node.set_bounds(bounds);
135
136        if let Some(nv) = sd.numeric {
137            node.set_min_numeric_value(nv.min);
138            node.set_max_numeric_value(nv.max);
139            node.set_numeric_value_step(nv.step);
140            node.set_numeric_value(nv.value);
141        }
142
143        if !sd.enabled {
144            node.set_disabled();
145        }
146        // 禁用节点暴露 action 会让 SR 允许用户触发无效操作
147        if sd.enabled {
148            if sd.focusable {
149                node.add_action(Action::Focus);
150            }
151            match sd.role {
152                SemanticsRole::Button => node.add_action(Action::Click),
153                SemanticsRole::CheckBox => node.add_action(Action::Click),
154                SemanticsRole::Slider | SemanticsRole::Splitter => node.add_action(Action::SetValue),
155                SemanticsRole::TextInput => node.add_action(Action::SetValue),
156                SemanticsRole::Tab | SemanticsRole::ListItem | SemanticsRole::TreeItem => {
157                    node.add_action(Action::Click)
158                }
159                SemanticsRole::MenuItem
160                | SemanticsRole::ComboBox
161                | SemanticsRole::RadioButton
162                | SemanticsRole::ListOption => node.add_action(Action::Click),
163                _ => {}
164            }
165        }
166
167        // 虚拟子项(单 RO 列表/菜单的行语义):递归构建,行/单元格均可暴露
168        let mut virtual_children: Vec<NodeId> = Vec::new();
169        push_virtual_nodes(
170            &sd.virtual_items,
171            Point::new(sd.bounds.x, sd.bounds.y),
172            dpr,
173            &mut virtual_counter,
174            &mut nodes,
175            &mut virtual_children,
176        );
177
178        let mut ak_children: Vec<NodeId> =
179            sd.children.iter().filter(|cid| sem_map.contains_key(cid)).map(|cid| to_node_id(*cid)).collect();
180        ak_children.extend(virtual_children);
181        node.set_children(ak_children);
182        nodes.push((nid, node));
183    }
184
185    let focus_node_id = match focus {
186        Some(fid) if sem_map.contains_key(&fid) => to_node_id(fid),
187        _ => root_node_id.unwrap_or(NodeId(0u64)),
188    };
189
190    let tree_info = if is_initial {
191        Some(Tree {
192            root: root_node_id.unwrap_or(NodeId(0u64)),
193            toolkit_name: Some("mgui".into()),
194            toolkit_version: Some(env!("CARGO_PKG_VERSION").into()),
195        })
196    } else {
197        None
198    };
199
200    TreeUpdate { nodes, tree: tree_info, focus: focus_node_id }
201}
202
203// =============================================================================
204// Action 解析辅助(NodeId → ElementId)
205// =============================================================================
206
207/// 把 NodeId 转回 ElementId(accesskit NodeId.0 = slotmap KeyData.as_ffi())
208pub fn node_id_to_element_id(nid: NodeId) -> ElementId {
209    ElementId::from_ffi(nid.0)
210}
211
212/// 从语义快照中取元素的中心点(逻辑像素);找不到返回 None。
213pub fn center_from_semantics(semantics: &[(ElementId, SemanticsData)], el_id: ElementId) -> Option<Point> {
214    semantics
215        .iter()
216        .find(|(id, _)| *id == el_id)
217        .map(|(_, sd)| Point::new(sd.bounds.x + sd.bounds.width / 2.0, sd.bounds.y + sd.bounds.height / 2.0))
218}
219
220/// 平台无关的 AccessKit 动作路由(Focus / Click / SetValue)。
221///
222/// desktop 单/多窗口 host 共用同一份逻辑,避免 SetValue 角色映射、now_ms、
223/// 目标失效处理各自漂移。返回值 = 是否已消费。
224pub fn dispatch_action(
225    tree: &mut ElementTree,
226    semantics: &[(ElementId, SemanticsData)],
227    request: &ActionRequest,
228    now_ms: u64,
229    fallback_center: Point,
230) -> bool {
231    // 虚拟语义子项:NodeId 不在元素空间,按建树时的确定性分配反推归属元素与行 bounds
232    if let Some(target) = virtual_item_target(semantics, request.target) {
233        match request.action {
234            Action::Click => {
235                let rect = target.rect;
236                let center = Point::new(rect.x + rect.width * 0.5, rect.y + rect.height * 0.5);
237                let data = PointerData::new(center, now_ms);
238                tree.request_focus(target.owner);
239                tree.dispatch_event(&WidgetEvent::PointerDown(data), center);
240                tree.dispatch_event(&WidgetEvent::PointerUp(data), center);
241            }
242            Action::Focus => tree.request_focus(target.owner),
243            Action::Expand if target.role == SemanticsRole::TreeItem && target.expanded == Some(false) => {
244                tree.request_focus(target.owner);
245                tree.dispatch_event_to(
246                    target.owner,
247                    &WidgetEvent::SetExpanded { item: Some(target.id), expanded: true },
248                );
249            }
250            Action::Collapse if target.role == SemanticsRole::TreeItem && target.expanded == Some(true) => {
251                tree.request_focus(target.owner);
252                tree.dispatch_event_to(
253                    target.owner,
254                    &WidgetEvent::SetExpanded { item: Some(target.id), expanded: false },
255                );
256            }
257            Action::SetTextSelection if target.role == SemanticsRole::TextRun => {
258                let Some(ActionData::SetTextSelection(selection)) = request.data.as_ref() else {
259                    return false;
260                };
261                tree.request_focus(target.owner);
262                tree.dispatch_event_to(
263                    target.owner,
264                    &WidgetEvent::SetTextSelection {
265                        anchor: selection.anchor.character_index,
266                        focus: selection.focus.character_index,
267                    },
268                );
269            }
270            _ => return false,
271        }
272        return true;
273    }
274
275    let el_id = node_id_to_element_id(request.target);
276    match request.action {
277        Action::Focus => {
278            tree.request_focus(el_id);
279        }
280        Action::Click => {
281            let center = center_from_semantics(semantics, el_id).unwrap_or(fallback_center);
282            let data = PointerData::new(center, now_ms);
283            tree.request_focus(el_id);
284            tree.dispatch_event(&WidgetEvent::PointerDown(data), center);
285            tree.dispatch_event(&WidgetEvent::PointerUp(data), center);
286        }
287        Action::SetValue => {
288            // 按 ElementId 反查语义角色 → 定向投递给目标控件;
289            // state 改值后走各自 on_change,自然写回对应的 Signal
290            let role = semantics.iter().find(|(id, _)| *id == el_id).map(|(_, sd)| sd.role);
291            let event = match (role, request.data.clone()) {
292                (Some(SemanticsRole::TextInput), Some(ActionData::Value(s))) => {
293                    Some(WidgetEvent::SetText(s.to_string()))
294                }
295                (Some(SemanticsRole::Slider | SemanticsRole::Splitter), Some(ActionData::NumericValue(v))) => {
296                    Some(WidgetEvent::SetValue((v as f32).clamp(0.0, 1.0)))
297                }
298                // Windows UIA ValuePattern 回传字符串形式的 Value,
299                // 而非 NumericValue;不接这条,SRAI 设值在 Win 上无效
300                (Some(SemanticsRole::Slider | SemanticsRole::Splitter), Some(ActionData::Value(s))) => {
301                    s.parse::<f64>().ok().map(|v| WidgetEvent::SetValue((v as f32).clamp(0.0, 1.0)))
302                }
303                (Some(role), data) => {
304                    log::debug!("AccessKit SetValue ignored: role={role:?} data={data:?}");
305                    None
306                }
307                (None, _) => {
308                    log::debug!("AccessKit SetValue: target {el_id:?} not in semantics tree");
309                    None
310                }
311            };
312            let Some(event) = event else { return false };
313            if !tree.dispatch_event_to(el_id, &event) {
314                log::debug!("AccessKit SetValue: target {el_id:?} is no longer active");
315                return false;
316            }
317        }
318        other => {
319            log::debug!("AccessKit unhandled action {other:?} on {el_id:?}");
320            return false;
321        }
322    }
323    true
324}
325
326/// 虚拟项节点构建(前序分配 id,bounds 逐级累加)。
327fn push_virtual_nodes(
328    items: &[mgui_core::VirtualSemanticItem],
329    origin: Point,
330    dpr: f32,
331    counter: &mut u64,
332    nodes: &mut Vec<(NodeId, Node)>,
333    out: &mut Vec<NodeId>,
334) {
335    for item in items {
336        let left = origin.x + item.bounds.x;
337        let top = origin.y + item.bounds.y;
338        let vid = NodeId(u64::MAX - *counter);
339        *counter += 1;
340
341        let mut vnode = Node::new(to_accesskit_role(item.role));
342        if item.role == SemanticsRole::TextRun {
343            // TextRun 的文本放在 value 属性(而不是 label)
344            if !item.label.is_empty() {
345                vnode.set_value(Box::<str>::from(item.label.as_str()));
346            }
347            if let Some(run) = &item.text_run {
348                vnode.set_character_lengths(run.character_lengths.clone());
349                if let Some(positions) = &run.character_positions {
350                    vnode.set_character_positions(positions.clone());
351                }
352                if let Some(widths) = &run.character_widths {
353                    vnode.set_character_widths(widths.clone());
354                }
355                vnode.set_text_direction(if run.rtl { TextDirection::RightToLeft } else { TextDirection::LeftToRight });
356                if let Some((anchor, focus)) = run.selection {
357                    vnode.set_text_selection(TextSelection {
358                        anchor: TextPosition { node: vid, character_index: anchor },
359                        focus: TextPosition { node: vid, character_index: focus },
360                    });
361                }
362                if item.enabled {
363                    vnode.add_action(Action::SetTextSelection);
364                }
365            }
366        } else if !item.label.is_empty() {
367            vnode.set_label(Box::<str>::from(item.label.as_str()));
368        }
369        if let Some(selected) = item.selected {
370            vnode.set_selected(selected);
371        }
372        if let Some(expanded) = item.expanded {
373            vnode.set_expanded(expanded);
374        }
375        if !item.enabled {
376            vnode.set_disabled();
377        } else {
378            if matches!(
379                item.role,
380                SemanticsRole::TreeItem
381                    | SemanticsRole::ListItem
382                    | SemanticsRole::MenuItem
383                    | SemanticsRole::RadioButton
384                    | SemanticsRole::Tab
385                    | SemanticsRole::GridRow
386                    | SemanticsRole::GridCell
387            ) {
388                // 点击由 dispatch_action 反推 (owner, bounds) 后合成指针事件
389                vnode.add_action(Action::Click);
390            }
391            // 树节点按展开状态暴露 Expand/Collapse
392            if item.role == SemanticsRole::TreeItem {
393                match item.expanded {
394                    Some(true) => vnode.add_action(Action::Collapse),
395                    Some(false) => vnode.add_action(Action::Expand),
396                    None => {}
397                }
398            }
399        }
400        vnode.set_bounds(accesskit::Rect::new(
401            left as f64 * dpr as f64,
402            top as f64 * dpr as f64,
403            (left + item.bounds.width) as f64 * dpr as f64,
404            (top + item.bounds.height) as f64 * dpr as f64,
405        ));
406
407        let mut children = Vec::new();
408        push_virtual_nodes(&item.children, Point::new(left, top), dpr, counter, nodes, &mut children);
409        vnode.set_children(children);
410        nodes.push((vid, vnode));
411        out.push(vid);
412    }
413}
414
415struct VirtualItemTarget {
416    owner: ElementId,
417    rect: Rect,
418    id: u64,
419    role: SemanticsRole,
420    expanded: Option<bool>,
421}
422
423/// 按建树时的确定性顺序,把虚拟项 NodeId 反推为宿主元素与行信息。
424///
425/// `build_tree_update` 从 `u64::MAX` 递减分配虚拟 NodeId,顺序与语义快照一致;
426/// 动作路由用同一顺序复算即可,无需额外注册表。
427fn virtual_item_target(semantics: &[(ElementId, SemanticsData)], target: NodeId) -> Option<VirtualItemTarget> {
428    fn find(
429        items: &[mgui_core::VirtualSemanticItem],
430        origin: Point,
431        target: NodeId,
432        counter: &mut u64,
433    ) -> Option<(Rect, u64, SemanticsRole, Option<bool>)> {
434        for item in items {
435            let left = origin.x + item.bounds.x;
436            let top = origin.y + item.bounds.y;
437            let vid = NodeId(u64::MAX - *counter);
438            *counter += 1;
439            if vid == target {
440                return Some((
441                    Rect::new(left, top, item.bounds.width, item.bounds.height),
442                    item.id,
443                    item.role,
444                    item.expanded,
445                ));
446            }
447            if let Some(found) = find(&item.children, Point::new(left, top), target, counter) {
448                return Some(found);
449            }
450        }
451        None
452    }
453
454    let mut counter: u64 = 0;
455    for (owner, sd) in semantics {
456        if let Some((rect, id, role, expanded)) =
457            find(&sd.virtual_items, Point::new(sd.bounds.x, sd.bounds.y), target, &mut counter)
458        {
459            return Some(VirtualItemTarget { owner: *owner, rect, id, role, expanded });
460        }
461    }
462    None
463}
464
465// =============================================================================
466// 单元测试
467// =============================================================================
468
469#[cfg(test)]
470mod tests {
471    use super::*;
472    use std::cell::RefCell;
473    use std::rc::Rc;
474
475    use mgui_core::render_object::RRectRenderObject;
476    use mgui_core::widget::{State, Widget};
477    use mgui_core::{Color, ElementTree, Rect, Size, WidgetNode};
478
479    #[derive(Debug)]
480    struct RecorderWidget {
481        log: Rc<RefCell<Vec<WidgetEvent>>>,
482    }
483
484    impl Widget for RecorderWidget {
485        fn as_any(&self) -> &dyn std::any::Any {
486            self
487        }
488        fn is_stateful(&self) -> bool {
489            true
490        }
491        fn create_state(&self) -> Option<Box<dyn State>> {
492            Some(Box::new(RecorderState { current: None, log: Rc::clone(&self.log) }))
493        }
494        fn create_render_object(&self) -> Box<dyn mgui_core::render_object::RenderObject> {
495            Box::new(RRectRenderObject::new(Size::new(100.0, 100.0), Color::WHITE, 0.0))
496        }
497    }
498
499    struct RecorderState {
500        current: Option<WidgetNode>,
501        log: Rc<RefCell<Vec<WidgetEvent>>>,
502    }
503
504    impl State for RecorderState {
505        fn as_any(&self) -> &dyn std::any::Any {
506            self
507        }
508        fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
509            self
510        }
511        fn widget(&self) -> &WidgetNode {
512            self.current.as_ref().expect("widget set")
513        }
514        fn set_widget(&mut self, widget: WidgetNode) {
515            self.current = Some(widget);
516        }
517        fn handle_event(&mut self, event: &WidgetEvent, _local_pos: Point) {
518            self.log.borrow_mut().push(event.clone());
519        }
520    }
521
522    fn make_semantics(role: SemanticsRole, id: u64, bounds: Rect) -> SemanticsData {
523        SemanticsData {
524            role,
525            label: Some(format!("node-{id}")),
526            value: None,
527            toggled: None,
528            expanded: None,
529            selected: None,
530            modal: false,
531            live: None,
532            virtual_items: Vec::new(),
533            enabled: true,
534            focusable: role == SemanticsRole::Button || role == SemanticsRole::CheckBox,
535            numeric: None,
536            bounds,
537            children: vec![],
538        }
539    }
540
541    #[test]
542    fn virtual_item_target_roundtrip() {
543        let mut sd = make_semantics(SemanticsRole::Grid, 9, Rect::new(10.0, 20.0, 100.0, 80.0));
544        sd.virtual_items = vec![mgui_core::VirtualSemanticItem {
545            id: 1,
546            role: SemanticsRole::GridRow,
547            label: "row".into(),
548            selected: Some(true),
549            expanded: None,
550            enabled: true,
551            bounds: Rect::new(0.0, 24.0, 100.0, 24.0),
552            children: vec![mgui_core::VirtualSemanticItem {
553                id: 2,
554                role: SemanticsRole::GridCell,
555                label: "cell".into(),
556                selected: None,
557                expanded: None,
558                enabled: true,
559                bounds: Rect::new(10.0, 0.0, 50.0, 24.0),
560                children: Vec::new(),
561                text_run: None,
562            }],
563            text_run: None,
564        }];
565        let owner = ElementId::from_ffi(9);
566        let semantics = vec![(owner, sd)];
567        let got = virtual_item_target(&semantics, NodeId(u64::MAX)).expect("virtual target");
568        assert_eq!(got.owner, owner);
569        assert_eq!(got.rect, Rect::new(10.0, 44.0, 100.0, 24.0));
570        assert_eq!((got.id, got.role), (1, SemanticsRole::GridRow));
571
572        // 嵌套子项:前序第二个 id,bounds 逐级累加
573        let got = virtual_item_target(&semantics, NodeId(u64::MAX - 1)).expect("nested target");
574        assert_eq!(got.owner, owner);
575        assert_eq!(got.rect, Rect::new(20.0, 44.0, 50.0, 24.0));
576        assert_eq!((got.id, got.role), (2, SemanticsRole::GridCell));
577    }
578
579    #[test]
580    fn virtual_tree_items_expose_expand_collapse_and_grid_cells_click() {
581        let mut tree_sd = make_semantics(SemanticsRole::Tree, 1, Rect::new(0.0, 0.0, 200.0, 120.0));
582        tree_sd.virtual_items = vec![
583            mgui_core::VirtualSemanticItem {
584                id: 1,
585                role: SemanticsRole::TreeItem,
586                label: "collapsed".into(),
587                selected: Some(false),
588                expanded: Some(false),
589                enabled: true,
590                bounds: Rect::new(0.0, 0.0, 200.0, 24.0),
591                children: Vec::new(),
592                text_run: None,
593            },
594            mgui_core::VirtualSemanticItem {
595                id: 2,
596                role: SemanticsRole::TreeItem,
597                label: "expanded".into(),
598                selected: Some(false),
599                expanded: Some(true),
600                enabled: true,
601                bounds: Rect::new(0.0, 24.0, 200.0, 24.0),
602                children: Vec::new(),
603                text_run: None,
604            },
605            mgui_core::VirtualSemanticItem {
606                id: 3,
607                role: SemanticsRole::TreeItem,
608                label: "leaf".into(),
609                selected: Some(false),
610                expanded: None,
611                enabled: true,
612                bounds: Rect::new(0.0, 48.0, 200.0, 24.0),
613                children: Vec::new(),
614                text_run: None,
615            },
616        ];
617        let semantics = vec![(ElementId::from_ffi(1), tree_sd)];
618        let update = build_tree_update(&semantics, None, 1.0, true);
619        let node = |offset: u64| {
620            update
621                .nodes
622                .iter()
623                .find(|(nid, _)| *nid == NodeId(u64::MAX - offset))
624                .map(|(_, node)| node)
625                .expect("virtual node")
626        };
627        assert!(node(0).supports_action(Action::Expand), "折叠节点暴露 Expand");
628        assert!(!node(0).supports_action(Action::Collapse));
629        assert!(node(1).supports_action(Action::Collapse), "展开节点暴露 Collapse");
630        assert!(!node(1).supports_action(Action::Expand));
631        assert!(!node(2).supports_action(Action::Expand), "叶子无展开动作");
632        assert!(!node(2).supports_action(Action::Collapse));
633        assert!(node(2).supports_action(Action::Click), "树节点仍可点击选择");
634
635        let mut grid_sd = make_semantics(SemanticsRole::Grid, 2, Rect::new(0.0, 0.0, 200.0, 80.0));
636        grid_sd.virtual_items = vec![mgui_core::VirtualSemanticItem {
637            id: 7,
638            role: SemanticsRole::GridRow,
639            label: "row".into(),
640            selected: Some(false),
641            expanded: None,
642            enabled: true,
643            bounds: Rect::new(0.0, 0.0, 200.0, 24.0),
644            children: vec![mgui_core::VirtualSemanticItem {
645                id: 0,
646                role: SemanticsRole::GridCell,
647                label: "cell".into(),
648                selected: None,
649                expanded: None,
650                enabled: true,
651                bounds: Rect::new(0.0, 0.0, 100.0, 24.0),
652                children: Vec::new(),
653                text_run: None,
654            }],
655            text_run: None,
656        }];
657        let semantics = vec![(ElementId::from_ffi(2), grid_sd)];
658        let update = build_tree_update(&semantics, None, 1.0, true);
659        let cell = update
660            .nodes
661            .iter()
662            .find(|(nid, _)| *nid == NodeId(u64::MAX - 1))
663            .map(|(_, node)| node)
664            .expect("grid cell node");
665        assert!(cell.supports_action(Action::Click), "GridCell 点击应路由到行");
666    }
667
668    #[test]
669    fn text_input_exposes_text_run_and_selection_action() {
670        let mut sd = make_semantics(SemanticsRole::TextInput, 7, Rect::new(0.0, 0.0, 200.0, 40.0));
671        sd.virtual_items = vec![mgui_core::VirtualSemanticItem {
672            id: 0,
673            role: SemanticsRole::TextRun,
674            label: "héllo".into(),
675            selected: None,
676            expanded: None,
677            enabled: true,
678            bounds: Rect::new(0.0, 0.0, 200.0, 40.0),
679            children: Vec::new(),
680            text_run: Some(mgui_core::VirtualTextRun {
681                character_lengths: vec![1, 2, 1, 1, 1],
682                selection: Some((0, 2)),
683                character_positions: Some(vec![0.0, 8.0, 16.0, 24.0, 32.0]),
684                character_widths: Some(vec![8.0; 5]),
685                rtl: false,
686            }),
687        }];
688        let owner = ElementId::from_ffi(7);
689        let semantics = vec![(owner, sd)];
690        let update = build_tree_update(&semantics, None, 1.0, true);
691        let text_run =
692            update.nodes.iter().find(|(nid, _)| *nid == NodeId(u64::MAX)).map(|(_, node)| node).expect("text run node");
693        assert_eq!(text_run.role(), Role::TextRun);
694        assert_eq!(text_run.character_lengths(), &[1, 2, 1, 1, 1]);
695        assert_eq!(text_run.value(), Some("héllo"));
696        assert_eq!(text_run.character_positions(), Some(&[0.0, 8.0, 16.0, 24.0, 32.0][..]));
697        assert_eq!(text_run.character_widths(), Some(&[8.0; 5][..]));
698        assert_eq!(text_run.text_direction(), Some(TextDirection::LeftToRight));
699        assert_eq!(
700            text_run.text_selection().map(|s| (s.anchor.character_index, s.focus.character_index)),
701            Some((0, 2))
702        );
703        assert!(text_run.supports_action(Action::SetTextSelection));
704    }
705
706    #[test]
707    fn set_text_selection_action_routes_character_range_to_owner() {
708        let log = Rc::new(RefCell::new(Vec::<WidgetEvent>::new()));
709        let mut tree = ElementTree::new();
710        tree.mount(WidgetNode::new(RecorderWidget { log: Rc::clone(&log) }));
711        let owner = tree.root_id().expect("root element");
712
713        let mut sd = make_semantics(SemanticsRole::TextInput, 8, Rect::new(0.0, 0.0, 200.0, 40.0));
714        sd.virtual_items = vec![mgui_core::VirtualSemanticItem {
715            id: 0,
716            role: SemanticsRole::TextRun,
717            label: "héllo".into(),
718            selected: None,
719            expanded: None,
720            enabled: true,
721            bounds: Rect::new(0.0, 0.0, 200.0, 40.0),
722            children: Vec::new(),
723            text_run: Some(mgui_core::VirtualTextRun {
724                character_lengths: vec![1, 2, 1, 1, 1],
725                selection: Some((0, 2)),
726                character_positions: None,
727                character_widths: None,
728                rtl: false,
729            }),
730        }];
731        let semantics = vec![(owner, sd)];
732        let selection = TextSelection {
733            anchor: TextPosition { node: NodeId(u64::MAX), character_index: 1 },
734            focus: TextPosition { node: NodeId(u64::MAX), character_index: 4 },
735        };
736        let request = ActionRequest {
737            action: Action::SetTextSelection,
738            target: NodeId(u64::MAX),
739            data: Some(ActionData::SetTextSelection(selection)),
740        };
741        assert!(dispatch_action(&mut tree, &semantics, &request, 0, Point::ZERO));
742        assert!(
743            matches!(log.borrow().last(), Some(WidgetEvent::SetTextSelection { anchor: 1, focus: 4 })),
744            "SetTextSelection 应投递字符索引: {:?}",
745            log.borrow()
746        );
747    }
748
749    #[test]
750    fn expand_action_routes_set_expanded_to_owner() {
751        let log = Rc::new(RefCell::new(Vec::<WidgetEvent>::new()));
752        let mut tree = ElementTree::new();
753        tree.mount(WidgetNode::new(RecorderWidget { log: Rc::clone(&log) }));
754        let owner = tree.root_id().expect("root element");
755
756        let mut sd = make_semantics(SemanticsRole::Tree, 1, Rect::new(0.0, 0.0, 200.0, 100.0));
757        sd.virtual_items = vec![mgui_core::VirtualSemanticItem {
758            id: 42,
759            role: SemanticsRole::TreeItem,
760            label: "src".into(),
761            selected: Some(false),
762            expanded: Some(false),
763            enabled: true,
764            bounds: Rect::new(0.0, 0.0, 200.0, 24.0),
765            children: Vec::new(),
766            text_run: None,
767        }];
768        let mut semantics = vec![(owner, sd)];
769        let expand = ActionRequest { action: Action::Expand, target: NodeId(u64::MAX), data: None };
770        assert!(dispatch_action(&mut tree, &semantics, &expand, 0, Point::ZERO));
771        assert!(
772            matches!(log.borrow().last(), Some(WidgetEvent::SetExpanded { item: Some(42), expanded: true })),
773            "Expand 应定向投递 SetExpanded: {:?}",
774            log.borrow()
775        );
776
777        semantics[0].1.virtual_items[0].expanded = Some(true);
778        let collapse = ActionRequest { action: Action::Collapse, target: NodeId(u64::MAX), data: None };
779        assert!(dispatch_action(&mut tree, &semantics, &collapse, 0, Point::ZERO));
780        assert!(
781            matches!(log.borrow().last(), Some(WidgetEvent::SetExpanded { item: Some(42), expanded: false })),
782            "Collapse 应定向投递 SetExpanded"
783        );
784    }
785
786    fn sample_tree() -> Vec<(ElementId, SemanticsData)> {
787        let root = (0.0, 0.0, 800.0, 600.0);
788        let btn = (100.0, 100.0, 200.0, 48.0);
789        let label = (100.0, 100.0, 120.0, 20.0);
790        let cb = (100.0, 200.0, 24.0, 24.0);
791
792        vec![
793            (
794                ElementId::from_ffi(1),
795                make_semantics(SemanticsRole::Container, 1, Rect::new(root.0, root.1, root.2, root.3)),
796            ),
797            (ElementId::from_ffi(2), make_semantics(SemanticsRole::Button, 2, Rect::new(btn.0, btn.1, btn.2, btn.3))),
798            (
799                ElementId::from_ffi(3),
800                make_semantics(SemanticsRole::Label, 3, Rect::new(label.0, label.1, label.2, label.3)),
801            ),
802            (ElementId::from_ffi(4), make_semantics(SemanticsRole::CheckBox, 4, Rect::new(cb.0, cb.1, cb.2, cb.3))),
803        ]
804    }
805
806    #[test]
807    fn role_mapping_smoke() {
808        assert_eq!(to_accesskit_role(SemanticsRole::Button), Role::Button);
809        assert_eq!(to_accesskit_role(SemanticsRole::CheckBox), Role::CheckBox);
810        assert_eq!(to_accesskit_role(SemanticsRole::Slider), Role::Slider);
811        assert_eq!(to_accesskit_role(SemanticsRole::TextInput), Role::TextInput);
812        assert_eq!(to_accesskit_role(SemanticsRole::Label), Role::Label);
813        assert_eq!(to_accesskit_role(SemanticsRole::Image), Role::Image);
814        assert_eq!(to_accesskit_role(SemanticsRole::Container), Role::GenericContainer);
815        assert_eq!(to_accesskit_role(SemanticsRole::Unknown), Role::Unknown);
816        assert_eq!(to_accesskit_role(SemanticsRole::Menu), Role::Menu);
817        assert_eq!(to_accesskit_role(SemanticsRole::MenuItem), Role::MenuItem);
818        assert_eq!(to_accesskit_role(SemanticsRole::ComboBox), Role::ComboBox);
819        assert_eq!(to_accesskit_role(SemanticsRole::RadioGroup), Role::RadioGroup);
820        assert_eq!(to_accesskit_role(SemanticsRole::RadioButton), Role::RadioButton);
821        assert_eq!(to_accesskit_role(SemanticsRole::Tooltip), Role::Tooltip);
822        assert_eq!(to_accesskit_role(SemanticsRole::Splitter), Role::Splitter);
823    }
824
825    #[test]
826    fn tree_build_has_all_nodes() {
827        let tree = sample_tree();
828        let update = build_tree_update(&tree, None, 1.0, true);
829        assert_eq!(update.nodes.len(), 4);
830        assert!(update.tree.is_some());
831    }
832
833    #[test]
834    fn bounds_scaled_by_dpr() {
835        let tree = sample_tree();
836        let update = build_tree_update(&tree, None, 2.0, true);
837        for (nid, node) in &update.nodes {
838            if nid.0 == 2 {
839                let b = node.bounds().unwrap();
840                assert_eq!(b.x0, 200.0);
841                assert_eq!(b.y0, 200.0);
842                assert_eq!(b.x1, 600.0);
843                assert_eq!(b.y1, 296.0);
844            }
845        }
846    }
847
848    #[test]
849    fn focus_mapping() {
850        let tree = sample_tree();
851        let btn_el = tree[1].0;
852        let update = build_tree_update(&tree, Some(btn_el), 1.0, true);
853        assert_eq!(update.focus, to_node_id(btn_el));
854
855        let u2 = build_tree_update(&tree, None, 1.0, true);
856        assert_eq!(u2.focus, to_node_id(tree[0].0));
857    }
858
859    #[test]
860    fn non_focusable_no_focus_action() {
861        let tree = sample_tree();
862        let u = build_tree_update(&tree, None, 1.0, true);
863        for (nid, node) in &u.nodes {
864            if nid.0 == 3 {
865                assert!(!node.supports_action(Action::Focus));
866            }
867            if nid.0 == 2 {
868                assert!(node.supports_action(Action::Focus));
869                assert!(node.supports_action(Action::Click));
870            }
871        }
872    }
873
874    #[test]
875    fn disabled_nodes_expose_no_actions() {
876        let mut tree = sample_tree();
877        tree[1].1.enabled = false;
878        let u = build_tree_update(&tree, None, 1.0, true);
879        let btn_nid = to_node_id(tree[1].0);
880        let (_, node) = u.nodes.iter().find(|(nid, _)| *nid == btn_nid).expect("button node");
881        assert!(!node.supports_action(Action::Focus));
882        assert!(!node.supports_action(Action::Click));
883    }
884
885    #[test]
886    fn numeric_domain_published_for_slider() {
887        let mut tree = sample_tree();
888        let slider_id = ElementId::from_ffi(5);
889        let mut sd = make_semantics(SemanticsRole::Slider, 5, Rect::new(0.0, 0.0, 200.0, 20.0));
890        sd.numeric = Some(mgui_core::SemanticsNumericValue { value: 0.25, min: 0.0, max: 1.0, step: 0.01 });
891        tree.push((slider_id, sd));
892
893        let u = build_tree_update(&tree, None, 1.0, true);
894        let (_, node) = u.nodes.iter().find(|(nid, _)| *nid == to_node_id(slider_id)).expect("slider node");
895        assert_eq!(node.numeric_value(), Some(0.25));
896        assert_eq!(node.min_numeric_value(), Some(0.0));
897        assert_eq!(node.max_numeric_value(), Some(1.0));
898        assert_eq!(node.numeric_value_step(), Some(0.01));
899        assert!(node.supports_action(Action::SetValue));
900    }
901
902    #[test]
903    fn splitter_exposes_focus_and_set_value() {
904        let mut tree = sample_tree();
905        let id = ElementId::from_ffi(6);
906        let mut sd = make_semantics(SemanticsRole::Splitter, 6, Rect::new(200.0, 0.0, 8.0, 400.0));
907        sd.focusable = true;
908        sd.numeric = Some(mgui_core::SemanticsNumericValue { value: 0.4, min: 0.0, max: 1.0, step: 0.02 });
909        tree.push((id, sd));
910
911        let u = build_tree_update(&tree, None, 1.0, true);
912        let (_, node) = u.nodes.iter().find(|(nid, _)| *nid == to_node_id(id)).expect("splitter node");
913        assert!(node.supports_action(Action::Focus));
914        assert!(node.supports_action(Action::SetValue));
915        assert_eq!(node.numeric_value(), Some(0.4));
916    }
917
918    #[test]
919    fn initial_vs_subsequent() {
920        let tree = sample_tree();
921        assert!(build_tree_update(&tree, None, 1.0, true).tree.is_some());
922        assert!(build_tree_update(&tree, None, 1.0, false).tree.is_none());
923    }
924
925    #[test]
926    fn node_id_roundtrip() {
927        let el = ElementId::from_ffi(0xDEADBEEF);
928        let nid = to_node_id(el);
929        assert_eq!(node_id_to_element_id(nid), el);
930    }
931
932    #[test]
933    fn extended_roles_modal_live_expand_selected_and_actions() {
934        let rect = Rect::new(0.0, 0.0, 100.0, 40.0);
935        let mut tree = vec![
936            (ElementId::from_ffi(10), make_semantics(SemanticsRole::Dialog, 10, rect)),
937            (ElementId::from_ffi(11), make_semantics(SemanticsRole::TreeItem, 11, rect)),
938            (ElementId::from_ffi(12), make_semantics(SemanticsRole::Toast, 12, rect)),
939            (ElementId::from_ffi(13), make_semantics(SemanticsRole::Progress, 13, rect)),
940            (ElementId::from_ffi(14), make_semantics(SemanticsRole::Grid, 14, rect)),
941            (ElementId::from_ffi(15), make_semantics(SemanticsRole::TabPanel, 15, rect)),
942        ];
943        tree[0].1.modal = true;
944        tree[0].1.focusable = false;
945        tree[1].1.expanded = Some(true);
946        tree[1].1.selected = Some(true);
947        tree[1].1.focusable = true;
948        tree[2].1.live = Some(LiveRegion::Assertive);
949        tree[2].1.focusable = false;
950        tree[3].1.numeric = Some(mgui_core::SemanticsNumericValue { value: 0.5, min: 0.0, max: 1.0, step: 0.01 });
951        tree[4].1.focusable = true;
952
953        let update = build_tree_update(&tree, None, 1.0, true);
954        let node = |el: ElementId| {
955            let nid = to_node_id(el);
956            update.nodes.iter().find(|(id, _)| *id == nid).map(|(_, n)| n).expect("node")
957        };
958
959        let dialog = node(ElementId::from_ffi(10));
960        assert_eq!(dialog.role(), Role::Dialog);
961        assert!(dialog.is_modal());
962        assert!(!dialog.supports_action(Action::Focus));
963
964        let item = node(ElementId::from_ffi(11));
965        assert_eq!(item.role(), Role::TreeItem);
966        assert_eq!(item.is_expanded(), Some(true));
967        assert_eq!(item.is_selected(), Some(true));
968        assert!(item.supports_action(Action::Click), "TreeItem 可激活");
969
970        let toast = node(ElementId::from_ffi(12));
971        assert_eq!(toast.role(), Role::Alert);
972        assert_eq!(toast.live(), Some(accesskit::Live::Assertive), "Toast 应作为 assertive live region");
973
974        let progress = node(ElementId::from_ffi(13));
975        assert_eq!(progress.role(), Role::ProgressIndicator);
976        assert_eq!(progress.numeric_value(), Some(0.5));
977
978        assert_eq!(node(ElementId::from_ffi(14)).role(), Role::Grid);
979        assert!(node(ElementId::from_ffi(14)).supports_action(Action::Focus));
980        assert_eq!(node(ElementId::from_ffi(15)).role(), Role::TabPanel);
981    }
982
983    #[test]
984    fn dispatch_action_focuses_and_rejects_unsupported_targets() {
985        use mgui_core::{Color, RRectWidget, Size, WidgetNode};
986
987        let mut tree = ElementTree::new();
988        tree.mount(WidgetNode::new(RRectWidget::new(Size::new(40.0, 20.0), Color::WHITE, 0.0)));
989        let id = tree.root_id().expect("root");
990
991        let focus = ActionRequest { action: Action::Focus, target: to_node_id(id), data: None };
992        assert!(dispatch_action(&mut tree, &[], &focus, 0, Point::ZERO));
993        assert_eq!(tree.focused_element(), Some(id), "Focus action 应更新树焦点");
994
995        // 语义快照里没有目标 → SetValue 不应对不存在/未知角色做任何事
996        let set_value = ActionRequest {
997            action: Action::SetValue,
998            target: to_node_id(id),
999            data: Some(ActionData::Value("x".into())),
1000        };
1001        assert!(!dispatch_action(&mut tree, &[], &set_value, 0, Point::ZERO));
1002    }
1003}