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,
};
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,
}
}
pub fn to_node_id(id: ElementId) -> NodeId {
NodeId(id.data().as_ffi())
}
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();
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());
let mut virtual_counter: u64 = 0;
for (el_id, sd) in tree {
let nid = to_node_id(*el_id);
let role = if *el_id == ElementId::A11Y_ROOT { Role::Window } else { to_accesskit_role(sd.role) };
let mut node = Node::new(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();
}
if sd.read_only {
node.set_read_only();
}
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 if !sd.read_only => 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),
_ => {}
}
node.add_action(Action::ScrollIntoView);
}
let mut virtual_children: Vec<NodeId> = Vec::new();
let mut text_runs: Vec<TextRunNode> = 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,
&mut text_runs,
);
if let Some((anchor, focus)) = sd.text_selection {
if let (Some((anchor_node, anchor_index)), Some((focus_node, focus_index))) =
(locate_text_run(&text_runs, anchor), locate_text_run(&text_runs, focus))
{
node.set_text_selection(TextSelection {
anchor: TextPosition { node: anchor_node, character_index: anchor_index },
focus: TextPosition { node: focus_node, character_index: focus_index },
});
}
}
if sd.enabled && sd.role == SemanticsRole::TextInput && !text_runs.is_empty() {
node.add_action(Action::SetTextSelection);
}
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 }
}
pub fn node_id_to_element_id(nid: NodeId) -> ElementId {
ElementId::from_ffi(nid.0)
}
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))
}
pub fn dispatch_action(
tree: &mut ElementTree,
semantics: &[(ElementId, SemanticsData)],
request: &ActionRequest,
now_ms: u64,
fallback_center: Point,
) -> bool {
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;
};
let Some((anchor, focus)) = map_text_selection(semantics, target.owner, selection) else {
log::debug!("AccessKit SetTextSelection: 无法映射文本位置到宿主 {:?}", target.owner);
return false;
};
tree.request_focus(target.owner);
tree.dispatch_event_to(target.owner, &WidgetEvent::SetTextSelection { anchor, focus });
}
Action::ScrollIntoView => {
if !tree.reveal(target.owner, target.rect) {
return false;
}
}
_ => 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 => {
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)))
}
(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;
}
}
Action::SetTextSelection => {
let Some(ActionData::SetTextSelection(selection)) = request.data.as_ref() else {
return false;
};
let Some((anchor, focus)) = map_text_selection(semantics, el_id, selection) else {
log::debug!("AccessKit SetTextSelection: 无法映射文本位置到 {el_id:?}");
return false;
};
tree.request_focus(el_id);
if !tree.dispatch_event_to(el_id, &WidgetEvent::SetTextSelection { anchor, focus }) {
log::debug!("AccessKit SetTextSelection: target {el_id:?} is no longer active");
return false;
}
}
Action::ScrollIntoView => {
let Some(bounds) = semantics.iter().find(|(id, _)| *id == el_id).map(|(_, sd)| sd.bounds) else {
log::debug!("AccessKit ScrollIntoView: target {el_id:?} not in semantics tree");
return false;
};
if !tree.reveal(el_id, bounds) {
log::debug!("AccessKit ScrollIntoView: no scroll container for {el_id:?}");
return false;
}
}
other => {
log::debug!("AccessKit unhandled action {other:?} on {el_id:?}");
return false;
}
}
true
}
struct TextRunNode {
node: NodeId,
start_char: usize,
char_count: usize,
}
fn push_virtual_nodes(
items: &[mgui_core::VirtualSemanticItem],
origin: Point,
dpr: f32,
counter: &mut u64,
nodes: &mut Vec<(NodeId, Node)>,
out: &mut Vec<NodeId>,
text_runs: &mut Vec<TextRunNode>,
) {
for item in items {
let left = origin.x + item.bounds.x;
let top = origin.y + item.bounds.y;
let vid = NodeId(VIRTUAL_NODE_ID_BASE - *counter);
*counter += 1;
let mut vnode = Node::new(to_accesskit_role(item.role));
if item.role == SemanticsRole::TextRun {
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 item.enabled {
vnode.add_action(Action::SetTextSelection);
}
text_runs.push(TextRunNode {
node: vid,
start_char: run.start_char,
char_count: run.character_lengths.len(),
});
}
} 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::Button
| SemanticsRole::TreeItem
| SemanticsRole::ListItem
| SemanticsRole::MenuItem
| SemanticsRole::RadioButton
| SemanticsRole::Tab
| SemanticsRole::GridRow
| SemanticsRole::GridCell
) {
vnode.add_action(Action::Click);
}
if item.role == SemanticsRole::TreeItem {
match item.expanded {
Some(true) => vnode.add_action(Action::Collapse),
Some(false) => vnode.add_action(Action::Expand),
None => {}
}
}
vnode.add_action(Action::ScrollIntoView);
}
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, text_runs);
vnode.set_children(children);
nodes.push((vid, vnode));
out.push(vid);
}
}
fn locate_text_run(runs: &[TextRunNode], char_index: usize) -> Option<(NodeId, usize)> {
let chosen = runs
.iter()
.filter(|run| run.start_char <= char_index)
.max_by_key(|run| run.start_char)
.or_else(|| runs.first())?;
let local = char_index.saturating_sub(chosen.start_char).min(chosen.char_count);
Some((chosen.node, local))
}
fn text_run_nodes(semantics: &[(ElementId, SemanticsData)]) -> Vec<(ElementId, TextRunNode)> {
fn walk(
items: &[mgui_core::VirtualSemanticItem],
owner: ElementId,
counter: &mut u64,
out: &mut Vec<(ElementId, TextRunNode)>,
) {
for item in items {
let vid = NodeId(VIRTUAL_NODE_ID_BASE - *counter);
*counter += 1;
if let Some(run) = &item.text_run {
out.push((
owner,
TextRunNode { node: vid, start_char: run.start_char, char_count: run.character_lengths.len() },
));
}
walk(&item.children, owner, counter, out);
}
}
let mut counter = 0;
let mut out = Vec::new();
for (owner, sd) in semantics {
walk(&sd.virtual_items, *owner, &mut counter, &mut out);
}
out
}
fn map_text_selection(
semantics: &[(ElementId, SemanticsData)],
owner: ElementId,
selection: &TextSelection,
) -> Option<(usize, usize)> {
let runs = text_run_nodes(semantics);
let resolve = |pos: TextPosition| -> Option<usize> {
if let Some((_, run)) = runs.iter().find(|(o, run)| *o == owner && run.node == pos.node) {
return Some(run.start_char + pos.character_index.min(run.char_count));
}
if pos.node == to_node_id(owner) {
return Some(pos.character_index);
}
None
};
Some((resolve(selection.anchor)?, resolve(selection.focus)?))
}
struct VirtualItemTarget {
owner: ElementId,
rect: Rect,
id: u64,
role: SemanticsRole,
expanded: Option<bool>,
}
const VIRTUAL_NODE_ID_BASE: u64 = u64::MAX - 1;
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(VIRTUAL_NODE_ID_BASE - *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(),
text_selection: None,
read_only: false,
enabled: true,
focusable: role == SemanticsRole::Button || role == SemanticsRole::CheckBox,
numeric: None,
bounds,
children: vec![],
}
}
#[test]
fn virtual_node_ids_avoid_synthetic_root_collision() {
let mut cd = make_semantics(SemanticsRole::List, 7, Rect::new(0.0, 0.0, 200.0, 100.0));
cd.virtual_items = vec![mgui_core::VirtualSemanticItem {
id: 0,
role: SemanticsRole::ListItem,
label: "first".into(),
selected: None,
expanded: None,
enabled: true,
bounds: Rect::new(0.0, 0.0, 200.0, 50.0),
children: vec![],
text_run: None,
}];
let semantics = vec![(ElementId::A11Y_ROOT, cd)];
let update = build_tree_update(&semantics, None, 1.0, true);
let root_id = update.tree.as_ref().expect("initial tree").root;
assert_eq!(root_id, NodeId(u64::MAX), "A11Y_ROOT 映射到 u64::MAX");
let virtual_id = NodeId(VIRTUAL_NODE_ID_BASE);
assert_ne!(root_id, virtual_id);
assert!(update.nodes.iter().any(|(id, _)| *id == virtual_id));
assert_eq!(update.nodes.iter().filter(|(id, _)| *id == root_id).count(), 1);
}
#[test]
fn filtered_tree_keeps_navigation_and_content_branches() {
let root_id = ElementId::A11Y_ROOT;
let two = ElementId::from_ffi(2);
let six = ElementId::from_ffi(6);
let seven = ElementId::from_ffi(7);
let nine = ElementId::from_ffi(9);
let ten = ElementId::from_ffi(10);
let mut root = make_semantics(SemanticsRole::Container, 0, Rect::new(0.0, 0.0, 960.0, 700.0));
root.children = vec![two];
let mut mid = make_semantics(SemanticsRole::Container, 2, Rect::new(0.0, 0.0, 960.0, 700.0));
mid.children = vec![six, nine];
let mut nav_box = make_semantics(SemanticsRole::Container, 6, Rect::new(0.0, 0.0, 220.0, 700.0));
nav_box.children = vec![seven];
let mut nav = make_semantics(SemanticsRole::List, 7, Rect::new(0.0, 0.0, 220.0, 1260.0));
nav.virtual_items = vec![mgui_core::VirtualSemanticItem {
id: 0,
role: SemanticsRole::ListItem,
label: "Button".into(),
selected: Some(true),
expanded: None,
enabled: true,
bounds: Rect::new(0.0, 0.0, 220.0, 44.0),
children: vec![],
text_run: None,
}];
let mut panel = make_semantics(SemanticsRole::TabPanel, 9, Rect::new(220.0, 0.0, 740.0, 506.0));
panel.children = vec![ten];
let content = make_semantics(SemanticsRole::Label, 10, Rect::new(220.0, 0.0, 740.0, 16.0));
let semantics = vec![(root_id, root), (two, mid), (six, nav_box), (seven, nav), (nine, panel), (ten, content)];
let update = build_tree_update(&semantics, None, 1.0, true);
let tree = accesskit_consumer::Tree::new(update, false);
let root = tree.state().root();
let children: Vec<_> =
root.filtered_children(accesskit_consumer::common_filter).map(|node| (node.role(), node.label())).collect();
assert!(
children.iter().any(|(role, _)| *role == Role::List),
"Navigation List 应出现在根过滤子节点: {children:?}"
);
assert!(
children.iter().any(|(role, _)| *role == Role::TabPanel),
"TabPanel 内容分支应出现在根过滤子节点: {children:?}"
);
let nav_node = root
.filtered_children(accesskit_consumer::common_filter)
.find(|node| node.role() == Role::List)
.expect("Navigation List");
let next = nav_node.following_filtered_siblings(accesskit_consumer::common_filter).next();
assert_eq!(next.map(|node| node.role()), Some(Role::TabPanel), "List 的下一个过滤兄弟应为 TabPanel");
}
#[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(VIRTUAL_NODE_ID_BASE)).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));
let got = virtual_item_target(&semantics, NodeId(VIRTUAL_NODE_ID_BASE - 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(VIRTUAL_NODE_ID_BASE - 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(VIRTUAL_NODE_ID_BASE - 1))
.map(|(_, node)| node)
.expect("grid cell node");
assert!(cell.supports_action(Action::Click), "GridCell 点击应路由到行");
}
fn text_input_with_two_runs(id: u64) -> SemanticsData {
let mut sd = make_semantics(SemanticsRole::TextInput, id, Rect::new(0.0, 0.0, 200.0, 40.0));
sd.value = Some("ab\ncd".into());
sd.text_selection = Some((1, 4));
sd.virtual_items = vec![
mgui_core::VirtualSemanticItem {
id: 0,
role: SemanticsRole::TextRun,
label: "ab\n".into(),
selected: None,
expanded: None,
enabled: true,
bounds: Rect::new(10.0, 0.0, 20.0, 20.0),
children: Vec::new(),
text_run: Some(mgui_core::VirtualTextRun {
character_lengths: vec![1, 1, 1],
start_char: 0,
character_positions: Some(vec![0.0, 8.0, 16.0]),
character_widths: Some(vec![8.0, 8.0, 0.0]),
rtl: false,
}),
},
mgui_core::VirtualSemanticItem {
id: 1,
role: SemanticsRole::TextRun,
label: "cd".into(),
selected: None,
expanded: None,
enabled: true,
bounds: Rect::new(10.0, 20.0, 20.0, 20.0),
children: Vec::new(),
text_run: Some(mgui_core::VirtualTextRun {
character_lengths: vec![1, 1],
start_char: 3,
character_positions: Some(vec![0.0, 8.0]),
character_widths: Some(vec![8.0, 8.0]),
rtl: false,
}),
},
];
sd
}
#[test]
fn text_input_exposes_line_runs_and_host_selection() {
let owner = ElementId::from_ffi(7);
let semantics = vec![(owner, text_input_with_two_runs(7))];
let update = build_tree_update(&semantics, None, 1.0, true);
let host = update
.nodes
.iter()
.find(|(nid, _)| *nid == to_node_id(owner))
.map(|(_, node)| node)
.expect("text input host");
let selection = host.text_selection().expect("选区挂在文本框宿主上");
assert_eq!(selection.anchor.node, NodeId(VIRTUAL_NODE_ID_BASE));
assert_eq!(selection.anchor.character_index, 1);
assert_eq!(selection.focus.node, NodeId(VIRTUAL_NODE_ID_BASE - 1), "focus 应映射到第二行");
assert_eq!(selection.focus.character_index, 1);
assert!(host.supports_action(Action::SetTextSelection));
let first = update
.nodes
.iter()
.find(|(nid, _)| *nid == NodeId(VIRTUAL_NODE_ID_BASE))
.map(|(_, node)| node)
.expect("first line");
assert_eq!(first.role(), Role::TextRun);
assert_eq!(first.value(), Some("ab\n"));
assert_eq!(first.character_lengths(), &[1, 1, 1]);
assert_eq!(first.character_positions(), Some(&[0.0, 8.0, 16.0][..]));
assert_eq!(first.character_widths(), Some(&[8.0, 8.0, 0.0][..]));
assert_eq!(first.text_direction(), Some(TextDirection::LeftToRight));
assert!(first.text_selection().is_none(), "选区不再挂在行节点");
let second = update
.nodes
.iter()
.find(|(nid, _)| *nid == NodeId(VIRTUAL_NODE_ID_BASE - 1))
.map(|(_, node)| node)
.expect("second line");
assert_eq!(second.value(), Some("cd"));
assert_eq!(second.character_lengths(), &[1, 1]);
}
#[test]
fn set_text_selection_on_host_maps_across_runs() {
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 semantics = vec![(owner, text_input_with_two_runs(8))];
let selection = TextSelection {
anchor: TextPosition { node: NodeId(VIRTUAL_NODE_ID_BASE), character_index: 1 },
focus: TextPosition { node: NodeId(VIRTUAL_NODE_ID_BASE - 1), character_index: 2 },
};
let request = ActionRequest {
action: Action::SetTextSelection,
target: to_node_id(owner),
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: 5 })),
"跨行选区应转换为全局字符索引: {:?}",
log.borrow()
);
}
#[test]
fn set_text_selection_on_run_target_maps_to_global_chars() {
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 semantics = vec![(owner, text_input_with_two_runs(9))];
let selection = TextSelection {
anchor: TextPosition { node: NodeId(VIRTUAL_NODE_ID_BASE), character_index: 0 },
focus: TextPosition { node: NodeId(VIRTUAL_NODE_ID_BASE - 1), character_index: 1 },
};
let request = ActionRequest {
action: Action::SetTextSelection,
target: NodeId(VIRTUAL_NODE_ID_BASE - 1),
data: Some(ActionData::SetTextSelection(selection)),
};
assert!(dispatch_action(&mut tree, &semantics, &request, 0, Point::ZERO));
assert!(
matches!(log.borrow().last(), Some(WidgetEvent::SetTextSelection { anchor: 0, focus: 4 })),
"行节点动作也应换算为全局字符索引: {:?}",
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(VIRTUAL_NODE_ID_BASE), 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(VIRTUAL_NODE_ID_BASE), 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 read_only_text_input_exposes_read_only_without_set_value() {
let id = ElementId::from_ffi(9);
let mut sd = make_semantics(SemanticsRole::TextInput, 9, Rect::new(0.0, 0.0, 200.0, 32.0));
sd.read_only = true;
sd.focusable = true;
let u = build_tree_update(&[(id, sd)], None, 1.0, true);
let (_, node) = u.nodes.iter().find(|(nid, _)| *nid == to_node_id(id)).expect("text input");
assert!(node.is_read_only());
assert!(!node.supports_action(Action::SetValue), "只读不应暴露 SetValue");
assert!(node.supports_action(Action::Focus), "只读仍可聚焦");
}
#[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 应更新树焦点");
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));
}
}