mgui-runtime 0.1.0

mgui 运行时:AppRunner、GPU/软件渲染后端、窗口/无障碍/异步任务集成
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
//! 无障碍语义树 — 平台无关的 AccessKit 数据转换与 action 路由。
//!
//! winit Adapter 的创建(activator / action channel / deactivator)在
//! `mgui-shell-desktop::a11y`;本模块只做 `ElementTree` 语义快照 →
//! `accesskit::TreeUpdate` 的转换与 Focus/Click/SetValue 分发,
//! 因此依赖树中没有 winit / accesskit_winit。

use std::collections::HashMap;

use accesskit::{
    Action, ActionData, ActionRequest, Node, NodeId, Role, TextDirection, TextPosition, TextSelection, Tree, TreeUpdate,
};

use mgui_core::{
    ElementId, ElementTree, Key as SlotKey, LiveRegion, Point, PointerData, Rect, SemanticsData, SemanticsRole,
    WidgetEvent,
};

// =============================================================================
// 辅助:SemanticsRole → accesskit Role
// =============================================================================

fn to_accesskit_role(role: SemanticsRole) -> Role {
    match role {
        SemanticsRole::Button => Role::Button,
        SemanticsRole::CheckBox => Role::CheckBox,
        SemanticsRole::Slider => Role::Slider,
        SemanticsRole::TextInput => Role::TextInput,
        SemanticsRole::TextRun => Role::TextRun,
        SemanticsRole::Label => Role::Label,
        SemanticsRole::Image => Role::Image,
        SemanticsRole::Container => Role::GenericContainer,
        SemanticsRole::Unknown => Role::Unknown,
        SemanticsRole::Dialog => Role::Dialog,
        SemanticsRole::Tab => Role::Tab,
        SemanticsRole::TabList => Role::TabList,
        SemanticsRole::TabPanel => Role::TabPanel,
        SemanticsRole::List => Role::List,
        SemanticsRole::ListItem => Role::ListItem,
        SemanticsRole::ListOption => Role::MenuListOption,
        SemanticsRole::Grid => Role::Grid,
        SemanticsRole::GridRow => Role::Row,
        SemanticsRole::GridCell => Role::Cell,
        SemanticsRole::Tree => Role::Tree,
        SemanticsRole::TreeItem => Role::TreeItem,
        SemanticsRole::Progress => Role::ProgressIndicator,
        SemanticsRole::Toast => Role::Alert,
        SemanticsRole::Menu => Role::Menu,
        SemanticsRole::MenuItem => Role::MenuItem,
        SemanticsRole::ComboBox => Role::ComboBox,
        SemanticsRole::RadioGroup => Role::RadioGroup,
        SemanticsRole::RadioButton => Role::RadioButton,
        SemanticsRole::Tooltip => Role::Tooltip,
        SemanticsRole::Splitter => Role::Splitter,
    }
}

// =============================================================================
// ElementId → NodeId(公开给 main.rs)
// =============================================================================

pub fn to_node_id(id: ElementId) -> NodeId {
    // slotmap::KeyData.as_ffi() → u64
    NodeId(id.data().as_ffi())
}

// =============================================================================
// 语义树 → TreeUpdate(公开给 main.rs)
// =============================================================================

/// 把 `build_accessibility_tree()` 输出的语义快照转成 accesskit::TreeUpdate。
///
/// - `tree`:core 产出的 Vec<(ElementId, SemanticsData)>
/// - `focus`:当前焦点 ElementId(可能 None)
/// - `dpr`:设备像素比 — bounds 从逻辑像素乘 DPR 转物理像素
/// - `is_initial`:true 时包含 Tree 元信息(首次推树时必须提供)
pub fn build_tree_update(
    tree: &[(ElementId, SemanticsData)],
    focus: Option<ElementId>,
    dpr: f32,
    is_initial: bool,
) -> TreeUpdate {
    let sem_map: HashMap<ElementId, &SemanticsData> = tree.iter().map(|(id, s)| (*id, s)).collect();

    // core 会在首位插入合成根(A11Y_ROOT);手工构造的旧格式数组仍回退到 first()
    let root_element_id = tree
        .iter()
        .find(|(id, _)| *id == ElementId::A11Y_ROOT)
        .map(|(id, _)| *id)
        .or_else(|| tree.first().map(|(id, _)| *id));
    let root_node_id = root_element_id.map(to_node_id);

    let mut nodes: Vec<(NodeId, Node)> = Vec::with_capacity(tree.len());
    // 虚拟子项使用独立 id 空间(从 u64::MAX 递减),避免与元素 id 冲突
    let mut virtual_counter: u64 = 0;

    for (el_id, sd) in tree {
        let nid = to_node_id(*el_id);
        let mut node = Node::new(to_accesskit_role(sd.role));

        if let Some(label) = &sd.label {
            if !label.is_empty() {
                node.set_label(Box::<str>::from(label.as_str()));
            }
        }
        if let Some(value) = &sd.value {
            node.set_value(value.clone());
        }
        if let Some(toggled) = sd.toggled {
            node.set_toggled(if toggled { accesskit::Toggled::True } else { accesskit::Toggled::False });
        }
        if let Some(expanded) = sd.expanded {
            node.set_expanded(expanded);
        }
        if let Some(selected) = sd.selected {
            node.set_selected(selected);
        }
        if sd.modal {
            node.set_modal();
        }
        if let Some(live) = sd.live {
            node.set_live(match live {
                LiveRegion::Polite => accesskit::Live::Polite,
                LiveRegion::Assertive => accesskit::Live::Assertive,
            });
        }

        let bounds = accesskit::Rect::new(
            sd.bounds.x as f64 * dpr as f64,
            sd.bounds.y as f64 * dpr as f64,
            (sd.bounds.x + sd.bounds.width) as f64 * dpr as f64,
            (sd.bounds.y + sd.bounds.height) as f64 * dpr as f64,
        );
        node.set_bounds(bounds);

        if let Some(nv) = sd.numeric {
            node.set_min_numeric_value(nv.min);
            node.set_max_numeric_value(nv.max);
            node.set_numeric_value_step(nv.step);
            node.set_numeric_value(nv.value);
        }

        if !sd.enabled {
            node.set_disabled();
        }
        // 禁用节点暴露 action 会让 SR 允许用户触发无效操作
        if sd.enabled {
            if sd.focusable {
                node.add_action(Action::Focus);
            }
            match sd.role {
                SemanticsRole::Button => node.add_action(Action::Click),
                SemanticsRole::CheckBox => node.add_action(Action::Click),
                SemanticsRole::Slider | SemanticsRole::Splitter => node.add_action(Action::SetValue),
                SemanticsRole::TextInput => node.add_action(Action::SetValue),
                SemanticsRole::Tab | SemanticsRole::ListItem | SemanticsRole::TreeItem => {
                    node.add_action(Action::Click)
                }
                SemanticsRole::MenuItem
                | SemanticsRole::ComboBox
                | SemanticsRole::RadioButton
                | SemanticsRole::ListOption => node.add_action(Action::Click),
                _ => {}
            }
        }

        // 虚拟子项(单 RO 列表/菜单的行语义):递归构建,行/单元格均可暴露
        let mut virtual_children: Vec<NodeId> = Vec::new();
        push_virtual_nodes(
            &sd.virtual_items,
            Point::new(sd.bounds.x, sd.bounds.y),
            dpr,
            &mut virtual_counter,
            &mut nodes,
            &mut virtual_children,
        );

        let mut ak_children: Vec<NodeId> =
            sd.children.iter().filter(|cid| sem_map.contains_key(cid)).map(|cid| to_node_id(*cid)).collect();
        ak_children.extend(virtual_children);
        node.set_children(ak_children);
        nodes.push((nid, node));
    }

    let focus_node_id = match focus {
        Some(fid) if sem_map.contains_key(&fid) => to_node_id(fid),
        _ => root_node_id.unwrap_or(NodeId(0u64)),
    };

    let tree_info = if is_initial {
        Some(Tree {
            root: root_node_id.unwrap_or(NodeId(0u64)),
            toolkit_name: Some("mgui".into()),
            toolkit_version: Some(env!("CARGO_PKG_VERSION").into()),
        })
    } else {
        None
    };

    TreeUpdate { nodes, tree: tree_info, focus: focus_node_id }
}

// =============================================================================
// Action 解析辅助(NodeId → ElementId)
// =============================================================================

/// 把 NodeId 转回 ElementId(accesskit NodeId.0 = slotmap KeyData.as_ffi())
pub fn node_id_to_element_id(nid: NodeId) -> ElementId {
    ElementId::from_ffi(nid.0)
}

/// 从语义快照中取元素的中心点(逻辑像素);找不到返回 None。
pub fn center_from_semantics(semantics: &[(ElementId, SemanticsData)], el_id: ElementId) -> Option<Point> {
    semantics
        .iter()
        .find(|(id, _)| *id == el_id)
        .map(|(_, sd)| Point::new(sd.bounds.x + sd.bounds.width / 2.0, sd.bounds.y + sd.bounds.height / 2.0))
}

/// 平台无关的 AccessKit 动作路由(Focus / Click / SetValue)。
///
/// desktop 单/多窗口 host 共用同一份逻辑,避免 SetValue 角色映射、now_ms、
/// 目标失效处理各自漂移。返回值 = 是否已消费。
pub fn dispatch_action(
    tree: &mut ElementTree,
    semantics: &[(ElementId, SemanticsData)],
    request: &ActionRequest,
    now_ms: u64,
    fallback_center: Point,
) -> bool {
    // 虚拟语义子项:NodeId 不在元素空间,按建树时的确定性分配反推归属元素与行 bounds
    if let Some(target) = virtual_item_target(semantics, request.target) {
        match request.action {
            Action::Click => {
                let rect = target.rect;
                let center = Point::new(rect.x + rect.width * 0.5, rect.y + rect.height * 0.5);
                let data = PointerData::new(center, now_ms);
                tree.request_focus(target.owner);
                tree.dispatch_event(&WidgetEvent::PointerDown(data), center);
                tree.dispatch_event(&WidgetEvent::PointerUp(data), center);
            }
            Action::Focus => tree.request_focus(target.owner),
            Action::Expand if target.role == SemanticsRole::TreeItem && target.expanded == Some(false) => {
                tree.request_focus(target.owner);
                tree.dispatch_event_to(
                    target.owner,
                    &WidgetEvent::SetExpanded { item: Some(target.id), expanded: true },
                );
            }
            Action::Collapse if target.role == SemanticsRole::TreeItem && target.expanded == Some(true) => {
                tree.request_focus(target.owner);
                tree.dispatch_event_to(
                    target.owner,
                    &WidgetEvent::SetExpanded { item: Some(target.id), expanded: false },
                );
            }
            Action::SetTextSelection if target.role == SemanticsRole::TextRun => {
                let Some(ActionData::SetTextSelection(selection)) = request.data.as_ref() else {
                    return false;
                };
                tree.request_focus(target.owner);
                tree.dispatch_event_to(
                    target.owner,
                    &WidgetEvent::SetTextSelection {
                        anchor: selection.anchor.character_index,
                        focus: selection.focus.character_index,
                    },
                );
            }
            _ => return false,
        }
        return true;
    }

    let el_id = node_id_to_element_id(request.target);
    match request.action {
        Action::Focus => {
            tree.request_focus(el_id);
        }
        Action::Click => {
            let center = center_from_semantics(semantics, el_id).unwrap_or(fallback_center);
            let data = PointerData::new(center, now_ms);
            tree.request_focus(el_id);
            tree.dispatch_event(&WidgetEvent::PointerDown(data), center);
            tree.dispatch_event(&WidgetEvent::PointerUp(data), center);
        }
        Action::SetValue => {
            // 按 ElementId 反查语义角色 → 定向投递给目标控件;
            // state 改值后走各自 on_change,自然写回对应的 Signal
            let role = semantics.iter().find(|(id, _)| *id == el_id).map(|(_, sd)| sd.role);
            let event = match (role, request.data.clone()) {
                (Some(SemanticsRole::TextInput), Some(ActionData::Value(s))) => {
                    Some(WidgetEvent::SetText(s.to_string()))
                }
                (Some(SemanticsRole::Slider | SemanticsRole::Splitter), Some(ActionData::NumericValue(v))) => {
                    Some(WidgetEvent::SetValue((v as f32).clamp(0.0, 1.0)))
                }
                // Windows UIA ValuePattern 回传字符串形式的 Value,
                // 而非 NumericValue;不接这条,SRAI 设值在 Win 上无效
                (Some(SemanticsRole::Slider | SemanticsRole::Splitter), Some(ActionData::Value(s))) => {
                    s.parse::<f64>().ok().map(|v| WidgetEvent::SetValue((v as f32).clamp(0.0, 1.0)))
                }
                (Some(role), data) => {
                    log::debug!("AccessKit SetValue ignored: role={role:?} data={data:?}");
                    None
                }
                (None, _) => {
                    log::debug!("AccessKit SetValue: target {el_id:?} not in semantics tree");
                    None
                }
            };
            let Some(event) = event else { return false };
            if !tree.dispatch_event_to(el_id, &event) {
                log::debug!("AccessKit SetValue: target {el_id:?} is no longer active");
                return false;
            }
        }
        other => {
            log::debug!("AccessKit unhandled action {other:?} on {el_id:?}");
            return false;
        }
    }
    true
}

/// 虚拟项节点构建(前序分配 id,bounds 逐级累加)。
fn push_virtual_nodes(
    items: &[mgui_core::VirtualSemanticItem],
    origin: Point,
    dpr: f32,
    counter: &mut u64,
    nodes: &mut Vec<(NodeId, Node)>,
    out: &mut Vec<NodeId>,
) {
    for item in items {
        let left = origin.x + item.bounds.x;
        let top = origin.y + item.bounds.y;
        let vid = NodeId(u64::MAX - *counter);
        *counter += 1;

        let mut vnode = Node::new(to_accesskit_role(item.role));
        if item.role == SemanticsRole::TextRun {
            // TextRun 的文本放在 value 属性(而不是 label)
            if !item.label.is_empty() {
                vnode.set_value(Box::<str>::from(item.label.as_str()));
            }
            if let Some(run) = &item.text_run {
                vnode.set_character_lengths(run.character_lengths.clone());
                if let Some(positions) = &run.character_positions {
                    vnode.set_character_positions(positions.clone());
                }
                if let Some(widths) = &run.character_widths {
                    vnode.set_character_widths(widths.clone());
                }
                vnode.set_text_direction(if run.rtl { TextDirection::RightToLeft } else { TextDirection::LeftToRight });
                if let Some((anchor, focus)) = run.selection {
                    vnode.set_text_selection(TextSelection {
                        anchor: TextPosition { node: vid, character_index: anchor },
                        focus: TextPosition { node: vid, character_index: focus },
                    });
                }
                if item.enabled {
                    vnode.add_action(Action::SetTextSelection);
                }
            }
        } else if !item.label.is_empty() {
            vnode.set_label(Box::<str>::from(item.label.as_str()));
        }
        if let Some(selected) = item.selected {
            vnode.set_selected(selected);
        }
        if let Some(expanded) = item.expanded {
            vnode.set_expanded(expanded);
        }
        if !item.enabled {
            vnode.set_disabled();
        } else {
            if matches!(
                item.role,
                SemanticsRole::TreeItem
                    | SemanticsRole::ListItem
                    | SemanticsRole::MenuItem
                    | SemanticsRole::RadioButton
                    | SemanticsRole::Tab
                    | SemanticsRole::GridRow
                    | SemanticsRole::GridCell
            ) {
                // 点击由 dispatch_action 反推 (owner, bounds) 后合成指针事件
                vnode.add_action(Action::Click);
            }
            // 树节点按展开状态暴露 Expand/Collapse
            if item.role == SemanticsRole::TreeItem {
                match item.expanded {
                    Some(true) => vnode.add_action(Action::Collapse),
                    Some(false) => vnode.add_action(Action::Expand),
                    None => {}
                }
            }
        }
        vnode.set_bounds(accesskit::Rect::new(
            left as f64 * dpr as f64,
            top as f64 * dpr as f64,
            (left + item.bounds.width) as f64 * dpr as f64,
            (top + item.bounds.height) as f64 * dpr as f64,
        ));

        let mut children = Vec::new();
        push_virtual_nodes(&item.children, Point::new(left, top), dpr, counter, nodes, &mut children);
        vnode.set_children(children);
        nodes.push((vid, vnode));
        out.push(vid);
    }
}

struct VirtualItemTarget {
    owner: ElementId,
    rect: Rect,
    id: u64,
    role: SemanticsRole,
    expanded: Option<bool>,
}

/// 按建树时的确定性顺序,把虚拟项 NodeId 反推为宿主元素与行信息。
///
/// `build_tree_update` 从 `u64::MAX` 递减分配虚拟 NodeId,顺序与语义快照一致;
/// 动作路由用同一顺序复算即可,无需额外注册表。
fn virtual_item_target(semantics: &[(ElementId, SemanticsData)], target: NodeId) -> Option<VirtualItemTarget> {
    fn find(
        items: &[mgui_core::VirtualSemanticItem],
        origin: Point,
        target: NodeId,
        counter: &mut u64,
    ) -> Option<(Rect, u64, SemanticsRole, Option<bool>)> {
        for item in items {
            let left = origin.x + item.bounds.x;
            let top = origin.y + item.bounds.y;
            let vid = NodeId(u64::MAX - *counter);
            *counter += 1;
            if vid == target {
                return Some((
                    Rect::new(left, top, item.bounds.width, item.bounds.height),
                    item.id,
                    item.role,
                    item.expanded,
                ));
            }
            if let Some(found) = find(&item.children, Point::new(left, top), target, counter) {
                return Some(found);
            }
        }
        None
    }

    let mut counter: u64 = 0;
    for (owner, sd) in semantics {
        if let Some((rect, id, role, expanded)) =
            find(&sd.virtual_items, Point::new(sd.bounds.x, sd.bounds.y), target, &mut counter)
        {
            return Some(VirtualItemTarget { owner: *owner, rect, id, role, expanded });
        }
    }
    None
}

// =============================================================================
// 单元测试
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::RefCell;
    use std::rc::Rc;

    use mgui_core::render_object::RRectRenderObject;
    use mgui_core::widget::{State, Widget};
    use mgui_core::{Color, ElementTree, Rect, Size, WidgetNode};

    #[derive(Debug)]
    struct RecorderWidget {
        log: Rc<RefCell<Vec<WidgetEvent>>>,
    }

    impl Widget for RecorderWidget {
        fn as_any(&self) -> &dyn std::any::Any {
            self
        }
        fn is_stateful(&self) -> bool {
            true
        }
        fn create_state(&self) -> Option<Box<dyn State>> {
            Some(Box::new(RecorderState { current: None, log: Rc::clone(&self.log) }))
        }
        fn create_render_object(&self) -> Box<dyn mgui_core::render_object::RenderObject> {
            Box::new(RRectRenderObject::new(Size::new(100.0, 100.0), Color::WHITE, 0.0))
        }
    }

    struct RecorderState {
        current: Option<WidgetNode>,
        log: Rc<RefCell<Vec<WidgetEvent>>>,
    }

    impl State for RecorderState {
        fn as_any(&self) -> &dyn std::any::Any {
            self
        }
        fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
            self
        }
        fn widget(&self) -> &WidgetNode {
            self.current.as_ref().expect("widget set")
        }
        fn set_widget(&mut self, widget: WidgetNode) {
            self.current = Some(widget);
        }
        fn handle_event(&mut self, event: &WidgetEvent, _local_pos: Point) {
            self.log.borrow_mut().push(event.clone());
        }
    }

    fn make_semantics(role: SemanticsRole, id: u64, bounds: Rect) -> SemanticsData {
        SemanticsData {
            role,
            label: Some(format!("node-{id}")),
            value: None,
            toggled: None,
            expanded: None,
            selected: None,
            modal: false,
            live: None,
            virtual_items: Vec::new(),
            enabled: true,
            focusable: role == SemanticsRole::Button || role == SemanticsRole::CheckBox,
            numeric: None,
            bounds,
            children: vec![],
        }
    }

    #[test]
    fn virtual_item_target_roundtrip() {
        let mut sd = make_semantics(SemanticsRole::Grid, 9, Rect::new(10.0, 20.0, 100.0, 80.0));
        sd.virtual_items = vec![mgui_core::VirtualSemanticItem {
            id: 1,
            role: SemanticsRole::GridRow,
            label: "row".into(),
            selected: Some(true),
            expanded: None,
            enabled: true,
            bounds: Rect::new(0.0, 24.0, 100.0, 24.0),
            children: vec![mgui_core::VirtualSemanticItem {
                id: 2,
                role: SemanticsRole::GridCell,
                label: "cell".into(),
                selected: None,
                expanded: None,
                enabled: true,
                bounds: Rect::new(10.0, 0.0, 50.0, 24.0),
                children: Vec::new(),
                text_run: None,
            }],
            text_run: None,
        }];
        let owner = ElementId::from_ffi(9);
        let semantics = vec![(owner, sd)];
        let got = virtual_item_target(&semantics, NodeId(u64::MAX)).expect("virtual target");
        assert_eq!(got.owner, owner);
        assert_eq!(got.rect, Rect::new(10.0, 44.0, 100.0, 24.0));
        assert_eq!((got.id, got.role), (1, SemanticsRole::GridRow));

        // 嵌套子项:前序第二个 id,bounds 逐级累加
        let got = virtual_item_target(&semantics, NodeId(u64::MAX - 1)).expect("nested target");
        assert_eq!(got.owner, owner);
        assert_eq!(got.rect, Rect::new(20.0, 44.0, 50.0, 24.0));
        assert_eq!((got.id, got.role), (2, SemanticsRole::GridCell));
    }

    #[test]
    fn virtual_tree_items_expose_expand_collapse_and_grid_cells_click() {
        let mut tree_sd = make_semantics(SemanticsRole::Tree, 1, Rect::new(0.0, 0.0, 200.0, 120.0));
        tree_sd.virtual_items = vec![
            mgui_core::VirtualSemanticItem {
                id: 1,
                role: SemanticsRole::TreeItem,
                label: "collapsed".into(),
                selected: Some(false),
                expanded: Some(false),
                enabled: true,
                bounds: Rect::new(0.0, 0.0, 200.0, 24.0),
                children: Vec::new(),
                text_run: None,
            },
            mgui_core::VirtualSemanticItem {
                id: 2,
                role: SemanticsRole::TreeItem,
                label: "expanded".into(),
                selected: Some(false),
                expanded: Some(true),
                enabled: true,
                bounds: Rect::new(0.0, 24.0, 200.0, 24.0),
                children: Vec::new(),
                text_run: None,
            },
            mgui_core::VirtualSemanticItem {
                id: 3,
                role: SemanticsRole::TreeItem,
                label: "leaf".into(),
                selected: Some(false),
                expanded: None,
                enabled: true,
                bounds: Rect::new(0.0, 48.0, 200.0, 24.0),
                children: Vec::new(),
                text_run: None,
            },
        ];
        let semantics = vec![(ElementId::from_ffi(1), tree_sd)];
        let update = build_tree_update(&semantics, None, 1.0, true);
        let node = |offset: u64| {
            update
                .nodes
                .iter()
                .find(|(nid, _)| *nid == NodeId(u64::MAX - offset))
                .map(|(_, node)| node)
                .expect("virtual node")
        };
        assert!(node(0).supports_action(Action::Expand), "折叠节点暴露 Expand");
        assert!(!node(0).supports_action(Action::Collapse));
        assert!(node(1).supports_action(Action::Collapse), "展开节点暴露 Collapse");
        assert!(!node(1).supports_action(Action::Expand));
        assert!(!node(2).supports_action(Action::Expand), "叶子无展开动作");
        assert!(!node(2).supports_action(Action::Collapse));
        assert!(node(2).supports_action(Action::Click), "树节点仍可点击选择");

        let mut grid_sd = make_semantics(SemanticsRole::Grid, 2, Rect::new(0.0, 0.0, 200.0, 80.0));
        grid_sd.virtual_items = vec![mgui_core::VirtualSemanticItem {
            id: 7,
            role: SemanticsRole::GridRow,
            label: "row".into(),
            selected: Some(false),
            expanded: None,
            enabled: true,
            bounds: Rect::new(0.0, 0.0, 200.0, 24.0),
            children: vec![mgui_core::VirtualSemanticItem {
                id: 0,
                role: SemanticsRole::GridCell,
                label: "cell".into(),
                selected: None,
                expanded: None,
                enabled: true,
                bounds: Rect::new(0.0, 0.0, 100.0, 24.0),
                children: Vec::new(),
                text_run: None,
            }],
            text_run: None,
        }];
        let semantics = vec![(ElementId::from_ffi(2), grid_sd)];
        let update = build_tree_update(&semantics, None, 1.0, true);
        let cell = update
            .nodes
            .iter()
            .find(|(nid, _)| *nid == NodeId(u64::MAX - 1))
            .map(|(_, node)| node)
            .expect("grid cell node");
        assert!(cell.supports_action(Action::Click), "GridCell 点击应路由到行");
    }

    #[test]
    fn text_input_exposes_text_run_and_selection_action() {
        let mut sd = make_semantics(SemanticsRole::TextInput, 7, Rect::new(0.0, 0.0, 200.0, 40.0));
        sd.virtual_items = vec![mgui_core::VirtualSemanticItem {
            id: 0,
            role: SemanticsRole::TextRun,
            label: "héllo".into(),
            selected: None,
            expanded: None,
            enabled: true,
            bounds: Rect::new(0.0, 0.0, 200.0, 40.0),
            children: Vec::new(),
            text_run: Some(mgui_core::VirtualTextRun {
                character_lengths: vec![1, 2, 1, 1, 1],
                selection: Some((0, 2)),
                character_positions: Some(vec![0.0, 8.0, 16.0, 24.0, 32.0]),
                character_widths: Some(vec![8.0; 5]),
                rtl: false,
            }),
        }];
        let owner = ElementId::from_ffi(7);
        let semantics = vec![(owner, sd)];
        let update = build_tree_update(&semantics, None, 1.0, true);
        let text_run =
            update.nodes.iter().find(|(nid, _)| *nid == NodeId(u64::MAX)).map(|(_, node)| node).expect("text run node");
        assert_eq!(text_run.role(), Role::TextRun);
        assert_eq!(text_run.character_lengths(), &[1, 2, 1, 1, 1]);
        assert_eq!(text_run.value(), Some("héllo"));
        assert_eq!(text_run.character_positions(), Some(&[0.0, 8.0, 16.0, 24.0, 32.0][..]));
        assert_eq!(text_run.character_widths(), Some(&[8.0; 5][..]));
        assert_eq!(text_run.text_direction(), Some(TextDirection::LeftToRight));
        assert_eq!(
            text_run.text_selection().map(|s| (s.anchor.character_index, s.focus.character_index)),
            Some((0, 2))
        );
        assert!(text_run.supports_action(Action::SetTextSelection));
    }

    #[test]
    fn set_text_selection_action_routes_character_range_to_owner() {
        let log = Rc::new(RefCell::new(Vec::<WidgetEvent>::new()));
        let mut tree = ElementTree::new();
        tree.mount(WidgetNode::new(RecorderWidget { log: Rc::clone(&log) }));
        let owner = tree.root_id().expect("root element");

        let mut sd = make_semantics(SemanticsRole::TextInput, 8, Rect::new(0.0, 0.0, 200.0, 40.0));
        sd.virtual_items = vec![mgui_core::VirtualSemanticItem {
            id: 0,
            role: SemanticsRole::TextRun,
            label: "héllo".into(),
            selected: None,
            expanded: None,
            enabled: true,
            bounds: Rect::new(0.0, 0.0, 200.0, 40.0),
            children: Vec::new(),
            text_run: Some(mgui_core::VirtualTextRun {
                character_lengths: vec![1, 2, 1, 1, 1],
                selection: Some((0, 2)),
                character_positions: None,
                character_widths: None,
                rtl: false,
            }),
        }];
        let semantics = vec![(owner, sd)];
        let selection = TextSelection {
            anchor: TextPosition { node: NodeId(u64::MAX), character_index: 1 },
            focus: TextPosition { node: NodeId(u64::MAX), character_index: 4 },
        };
        let request = ActionRequest {
            action: Action::SetTextSelection,
            target: NodeId(u64::MAX),
            data: Some(ActionData::SetTextSelection(selection)),
        };
        assert!(dispatch_action(&mut tree, &semantics, &request, 0, Point::ZERO));
        assert!(
            matches!(log.borrow().last(), Some(WidgetEvent::SetTextSelection { anchor: 1, focus: 4 })),
            "SetTextSelection 应投递字符索引: {:?}",
            log.borrow()
        );
    }

    #[test]
    fn expand_action_routes_set_expanded_to_owner() {
        let log = Rc::new(RefCell::new(Vec::<WidgetEvent>::new()));
        let mut tree = ElementTree::new();
        tree.mount(WidgetNode::new(RecorderWidget { log: Rc::clone(&log) }));
        let owner = tree.root_id().expect("root element");

        let mut sd = make_semantics(SemanticsRole::Tree, 1, Rect::new(0.0, 0.0, 200.0, 100.0));
        sd.virtual_items = vec![mgui_core::VirtualSemanticItem {
            id: 42,
            role: SemanticsRole::TreeItem,
            label: "src".into(),
            selected: Some(false),
            expanded: Some(false),
            enabled: true,
            bounds: Rect::new(0.0, 0.0, 200.0, 24.0),
            children: Vec::new(),
            text_run: None,
        }];
        let mut semantics = vec![(owner, sd)];
        let expand = ActionRequest { action: Action::Expand, target: NodeId(u64::MAX), data: None };
        assert!(dispatch_action(&mut tree, &semantics, &expand, 0, Point::ZERO));
        assert!(
            matches!(log.borrow().last(), Some(WidgetEvent::SetExpanded { item: Some(42), expanded: true })),
            "Expand 应定向投递 SetExpanded: {:?}",
            log.borrow()
        );

        semantics[0].1.virtual_items[0].expanded = Some(true);
        let collapse = ActionRequest { action: Action::Collapse, target: NodeId(u64::MAX), data: None };
        assert!(dispatch_action(&mut tree, &semantics, &collapse, 0, Point::ZERO));
        assert!(
            matches!(log.borrow().last(), Some(WidgetEvent::SetExpanded { item: Some(42), expanded: false })),
            "Collapse 应定向投递 SetExpanded"
        );
    }

    fn sample_tree() -> Vec<(ElementId, SemanticsData)> {
        let root = (0.0, 0.0, 800.0, 600.0);
        let btn = (100.0, 100.0, 200.0, 48.0);
        let label = (100.0, 100.0, 120.0, 20.0);
        let cb = (100.0, 200.0, 24.0, 24.0);

        vec![
            (
                ElementId::from_ffi(1),
                make_semantics(SemanticsRole::Container, 1, Rect::new(root.0, root.1, root.2, root.3)),
            ),
            (ElementId::from_ffi(2), make_semantics(SemanticsRole::Button, 2, Rect::new(btn.0, btn.1, btn.2, btn.3))),
            (
                ElementId::from_ffi(3),
                make_semantics(SemanticsRole::Label, 3, Rect::new(label.0, label.1, label.2, label.3)),
            ),
            (ElementId::from_ffi(4), make_semantics(SemanticsRole::CheckBox, 4, Rect::new(cb.0, cb.1, cb.2, cb.3))),
        ]
    }

    #[test]
    fn role_mapping_smoke() {
        assert_eq!(to_accesskit_role(SemanticsRole::Button), Role::Button);
        assert_eq!(to_accesskit_role(SemanticsRole::CheckBox), Role::CheckBox);
        assert_eq!(to_accesskit_role(SemanticsRole::Slider), Role::Slider);
        assert_eq!(to_accesskit_role(SemanticsRole::TextInput), Role::TextInput);
        assert_eq!(to_accesskit_role(SemanticsRole::Label), Role::Label);
        assert_eq!(to_accesskit_role(SemanticsRole::Image), Role::Image);
        assert_eq!(to_accesskit_role(SemanticsRole::Container), Role::GenericContainer);
        assert_eq!(to_accesskit_role(SemanticsRole::Unknown), Role::Unknown);
        assert_eq!(to_accesskit_role(SemanticsRole::Menu), Role::Menu);
        assert_eq!(to_accesskit_role(SemanticsRole::MenuItem), Role::MenuItem);
        assert_eq!(to_accesskit_role(SemanticsRole::ComboBox), Role::ComboBox);
        assert_eq!(to_accesskit_role(SemanticsRole::RadioGroup), Role::RadioGroup);
        assert_eq!(to_accesskit_role(SemanticsRole::RadioButton), Role::RadioButton);
        assert_eq!(to_accesskit_role(SemanticsRole::Tooltip), Role::Tooltip);
        assert_eq!(to_accesskit_role(SemanticsRole::Splitter), Role::Splitter);
    }

    #[test]
    fn tree_build_has_all_nodes() {
        let tree = sample_tree();
        let update = build_tree_update(&tree, None, 1.0, true);
        assert_eq!(update.nodes.len(), 4);
        assert!(update.tree.is_some());
    }

    #[test]
    fn bounds_scaled_by_dpr() {
        let tree = sample_tree();
        let update = build_tree_update(&tree, None, 2.0, true);
        for (nid, node) in &update.nodes {
            if nid.0 == 2 {
                let b = node.bounds().unwrap();
                assert_eq!(b.x0, 200.0);
                assert_eq!(b.y0, 200.0);
                assert_eq!(b.x1, 600.0);
                assert_eq!(b.y1, 296.0);
            }
        }
    }

    #[test]
    fn focus_mapping() {
        let tree = sample_tree();
        let btn_el = tree[1].0;
        let update = build_tree_update(&tree, Some(btn_el), 1.0, true);
        assert_eq!(update.focus, to_node_id(btn_el));

        let u2 = build_tree_update(&tree, None, 1.0, true);
        assert_eq!(u2.focus, to_node_id(tree[0].0));
    }

    #[test]
    fn non_focusable_no_focus_action() {
        let tree = sample_tree();
        let u = build_tree_update(&tree, None, 1.0, true);
        for (nid, node) in &u.nodes {
            if nid.0 == 3 {
                assert!(!node.supports_action(Action::Focus));
            }
            if nid.0 == 2 {
                assert!(node.supports_action(Action::Focus));
                assert!(node.supports_action(Action::Click));
            }
        }
    }

    #[test]
    fn disabled_nodes_expose_no_actions() {
        let mut tree = sample_tree();
        tree[1].1.enabled = false;
        let u = build_tree_update(&tree, None, 1.0, true);
        let btn_nid = to_node_id(tree[1].0);
        let (_, node) = u.nodes.iter().find(|(nid, _)| *nid == btn_nid).expect("button node");
        assert!(!node.supports_action(Action::Focus));
        assert!(!node.supports_action(Action::Click));
    }

    #[test]
    fn numeric_domain_published_for_slider() {
        let mut tree = sample_tree();
        let slider_id = ElementId::from_ffi(5);
        let mut sd = make_semantics(SemanticsRole::Slider, 5, Rect::new(0.0, 0.0, 200.0, 20.0));
        sd.numeric = Some(mgui_core::SemanticsNumericValue { value: 0.25, min: 0.0, max: 1.0, step: 0.01 });
        tree.push((slider_id, sd));

        let u = build_tree_update(&tree, None, 1.0, true);
        let (_, node) = u.nodes.iter().find(|(nid, _)| *nid == to_node_id(slider_id)).expect("slider node");
        assert_eq!(node.numeric_value(), Some(0.25));
        assert_eq!(node.min_numeric_value(), Some(0.0));
        assert_eq!(node.max_numeric_value(), Some(1.0));
        assert_eq!(node.numeric_value_step(), Some(0.01));
        assert!(node.supports_action(Action::SetValue));
    }

    #[test]
    fn splitter_exposes_focus_and_set_value() {
        let mut tree = sample_tree();
        let id = ElementId::from_ffi(6);
        let mut sd = make_semantics(SemanticsRole::Splitter, 6, Rect::new(200.0, 0.0, 8.0, 400.0));
        sd.focusable = true;
        sd.numeric = Some(mgui_core::SemanticsNumericValue { value: 0.4, min: 0.0, max: 1.0, step: 0.02 });
        tree.push((id, sd));

        let u = build_tree_update(&tree, None, 1.0, true);
        let (_, node) = u.nodes.iter().find(|(nid, _)| *nid == to_node_id(id)).expect("splitter node");
        assert!(node.supports_action(Action::Focus));
        assert!(node.supports_action(Action::SetValue));
        assert_eq!(node.numeric_value(), Some(0.4));
    }

    #[test]
    fn initial_vs_subsequent() {
        let tree = sample_tree();
        assert!(build_tree_update(&tree, None, 1.0, true).tree.is_some());
        assert!(build_tree_update(&tree, None, 1.0, false).tree.is_none());
    }

    #[test]
    fn node_id_roundtrip() {
        let el = ElementId::from_ffi(0xDEADBEEF);
        let nid = to_node_id(el);
        assert_eq!(node_id_to_element_id(nid), el);
    }

    #[test]
    fn extended_roles_modal_live_expand_selected_and_actions() {
        let rect = Rect::new(0.0, 0.0, 100.0, 40.0);
        let mut tree = vec![
            (ElementId::from_ffi(10), make_semantics(SemanticsRole::Dialog, 10, rect)),
            (ElementId::from_ffi(11), make_semantics(SemanticsRole::TreeItem, 11, rect)),
            (ElementId::from_ffi(12), make_semantics(SemanticsRole::Toast, 12, rect)),
            (ElementId::from_ffi(13), make_semantics(SemanticsRole::Progress, 13, rect)),
            (ElementId::from_ffi(14), make_semantics(SemanticsRole::Grid, 14, rect)),
            (ElementId::from_ffi(15), make_semantics(SemanticsRole::TabPanel, 15, rect)),
        ];
        tree[0].1.modal = true;
        tree[0].1.focusable = false;
        tree[1].1.expanded = Some(true);
        tree[1].1.selected = Some(true);
        tree[1].1.focusable = true;
        tree[2].1.live = Some(LiveRegion::Assertive);
        tree[2].1.focusable = false;
        tree[3].1.numeric = Some(mgui_core::SemanticsNumericValue { value: 0.5, min: 0.0, max: 1.0, step: 0.01 });
        tree[4].1.focusable = true;

        let update = build_tree_update(&tree, None, 1.0, true);
        let node = |el: ElementId| {
            let nid = to_node_id(el);
            update.nodes.iter().find(|(id, _)| *id == nid).map(|(_, n)| n).expect("node")
        };

        let dialog = node(ElementId::from_ffi(10));
        assert_eq!(dialog.role(), Role::Dialog);
        assert!(dialog.is_modal());
        assert!(!dialog.supports_action(Action::Focus));

        let item = node(ElementId::from_ffi(11));
        assert_eq!(item.role(), Role::TreeItem);
        assert_eq!(item.is_expanded(), Some(true));
        assert_eq!(item.is_selected(), Some(true));
        assert!(item.supports_action(Action::Click), "TreeItem 可激活");

        let toast = node(ElementId::from_ffi(12));
        assert_eq!(toast.role(), Role::Alert);
        assert_eq!(toast.live(), Some(accesskit::Live::Assertive), "Toast 应作为 assertive live region");

        let progress = node(ElementId::from_ffi(13));
        assert_eq!(progress.role(), Role::ProgressIndicator);
        assert_eq!(progress.numeric_value(), Some(0.5));

        assert_eq!(node(ElementId::from_ffi(14)).role(), Role::Grid);
        assert!(node(ElementId::from_ffi(14)).supports_action(Action::Focus));
        assert_eq!(node(ElementId::from_ffi(15)).role(), Role::TabPanel);
    }

    #[test]
    fn dispatch_action_focuses_and_rejects_unsupported_targets() {
        use mgui_core::{Color, RRectWidget, Size, WidgetNode};

        let mut tree = ElementTree::new();
        tree.mount(WidgetNode::new(RRectWidget::new(Size::new(40.0, 20.0), Color::WHITE, 0.0)));
        let id = tree.root_id().expect("root");

        let focus = ActionRequest { action: Action::Focus, target: to_node_id(id), data: None };
        assert!(dispatch_action(&mut tree, &[], &focus, 0, Point::ZERO));
        assert_eq!(tree.focused_element(), Some(id), "Focus action 应更新树焦点");

        // 语义快照里没有目标 → SetValue 不应对不存在/未知角色做任何事
        let set_value = ActionRequest {
            action: Action::SetValue,
            target: to_node_id(id),
            data: Some(ActionData::Value("x".into())),
        };
        assert!(!dispatch_action(&mut tree, &[], &set_value, 0, Point::ZERO));
    }
}