use std::ops::Range;
use accesskit::{
Action, ActionRequest, Node, NodeId, Rect, Role, TextPosition, TextSelection, Toggled, TreeId,
TreeInfo, TreeUpdate,
};
use super::focus::{self, Scope};
use super::widgets::{MASK, WidgetKind, WidgetState};
use super::{Content, KeySource, NodeKey, ROOT_KEY, Ui};
use crate::style::PseudoClasses;
impl Ui {
#[must_use]
pub fn accessibility_update(&self) -> TreeUpdate {
let root = NodeId(ROOT_KEY.0);
let mut window = Node::new(Role::Window);
let mut nodes = Vec::with_capacity(self.nodes.len() + 1);
for index in 0..self.nodes.len() {
if self.nodes[index].parent.is_none() {
self.push_accessible(index, &mut window, &mut nodes);
}
}
let focus = self
.focused()
.map(|key| NodeId(key.0))
.filter(|focused| nodes.iter().any(|(id, _)| id == focused))
.unwrap_or(root);
nodes.push((root, window));
TreeUpdate {
nodes,
tree: Some(TreeInfo::new(root)),
tree_id: TreeId::ROOT,
focus,
}
}
pub fn accessibility_action(&mut self, request: &ActionRequest) -> bool {
if request.target_tree != TreeId::ROOT {
return false;
}
let key = NodeKey(request.target_node.0);
let Some(node) = self.store.by_key(key) else {
return false;
};
match request.action {
Action::Focus if node.behavior.is_focusable() => {
self.set_focus(key);
true
}
Action::Blur if self.focused() == Some(key) => {
self.clear_focus();
true
}
Action::Click if clickable(node.behavior) => {
self.requested_click = Some(key);
true
}
_ => false,
}
}
pub fn set_accessible_label(&mut self, key: NodeKey, label: &str) {
self.accessible_labels.insert(key, label.to_owned());
}
pub fn set_accessible_text_input(
&mut self,
key: NodeKey,
value: &str,
selection: Range<usize>,
) {
let char_at = |byte: usize| {
assert!(
value.is_char_boundary(byte),
"byte {byte} of a {}-byte value is not between characters",
value.len()
);
value[..byte].chars().count()
};
let field = TextField {
value: value.to_owned(),
anchor: char_at(selection.start),
focus: char_at(selection.end),
};
self.accessible_text_inputs.insert(key, field);
}
pub(super) fn resolve_requested_click(&mut self) -> Option<NodeKey> {
let key = self.requested_click.take()?;
let slot = self.store.find(key)?;
let node = self.store.get_mut(slot);
if !clickable(node.behavior) {
return None;
}
node.interaction.clicked = true;
Some(key)
}
fn push_accessible(&self, index: usize, parent: &mut Node, out: &mut Vec<(NodeId, Node)>) {
let frame = &self.nodes[index];
let stored = self.store.get(frame.slot);
let kind = stored.kind;
if kind == WidgetKind::Decoration {
return;
}
let id = NodeId(frame.key.0);
parent.push_child(id);
let mut node = Node::new(role_of(frame.content, kind));
let (min, max) = stored.rect;
node.set_bounds(Rect {
x0: f64::from(min.x),
y0: f64::from(min.y),
x1: f64::from(max.x),
y1: f64::from(max.y),
});
if !stored.hittable {
node.set_hidden();
}
if stored.behavior.disabled {
node.set_disabled();
}
if stored.behavior.scope == Scope::Modal {
node.set_modal();
}
if stored.behavior.is_focusable() {
node.add_action(Action::Focus);
}
if self.focused() == Some(frame.key) {
node.add_action(Action::Blur);
}
if clickable(stored.behavior) {
node.add_action(Action::Click);
}
if let Content::Text { start, end } | Content::Run { start, end } = frame.content {
node.set_value(&self.text[start..end]);
}
let state = stored.state;
match kind {
WidgetKind::Checkbox => node.set_toggled(if state.contains(PseudoClasses::CHECKED) {
Toggled::True
} else {
Toggled::False
}),
WidgetKind::Disclosure | WidgetKind::Select => {
node.set_expanded(state.contains(PseudoClasses::OPEN));
}
WidgetKind::MenuItem if stored.widget == WidgetState::MenuBranch => {
node.set_expanded(state.contains(PseudoClasses::OPEN));
}
WidgetKind::TreeRow | WidgetKind::OutlinerRow => {
if let WidgetState::TreeItem {
open, branch: true, ..
} = stored.widget
{
node.set_expanded(open);
}
}
_ => {}
}
if matches!(
kind,
WidgetKind::Tab | WidgetKind::SelectOption | WidgetKind::OutlinerRow
) {
node.set_selected(state.contains(PseudoClasses::CHECKED));
}
if kind == (WidgetKind::ListRow { selectable: true }) {
node.set_selected(state.contains(PseudoClasses::CHECKED));
}
let label = self.accessible_labels.get(&frame.key);
let marked = self.accessible_text_inputs.get(&frame.key);
if is_whole(kind) {
self.name_from_contents(index, kind, &mut node);
} else {
let mut held = false;
let mut next = frame.first_child;
while let Some(child) = next {
let is_text = matches!(
self.nodes[child].content,
Content::Text { .. } | Content::Run { .. }
);
if (label.is_none() && marked.is_none()) || !is_text {
self.push_accessible(child, &mut node, out);
held = true;
}
next = self.nodes[child].next_sibling;
}
if label.is_some()
&& marked.is_none()
&& !held
&& frame.content == Content::Block
&& kind == WidgetKind::None
{
node.set_role(Role::Label);
}
}
if let Some(field) = marked {
node.set_role(Role::TextInput);
node.set_value(field.value.as_str());
}
if let Some(label) = label {
if node.role() == Role::Label {
node.set_value(label.as_str());
} else {
node.set_label(label.as_str());
}
}
let field = marked
.cloned()
.or_else(|| self.built_field(frame.key, kind));
if let Some(field) = field {
push_text_run(frame.key, &field, &mut node, out);
}
out.push((id, node));
}
fn built_field(&self, key: NodeKey, kind: WidgetKind) -> Option<TextField> {
let WidgetKind::TextInput { masked } = kind else {
return None;
};
let line = self.edits.get(&key)?.line();
let value = if masked {
String::from_iter(std::iter::repeat_n(MASK, line.len()))
} else {
line.text().to_owned()
};
Some(TextField {
value,
anchor: line.anchor(),
focus: line.caret(),
})
}
fn name_from_contents(&self, index: usize, kind: WidgetKind, node: &mut Node) {
let mut text = String::new();
self.gather_text(index, &mut text);
let key = self.nodes[index].key;
match kind {
WidgetKind::TextInput { masked } => {
let value = self
.edits
.get(&key)
.map(|state| state.text())
.unwrap_or_default();
if masked {
node.set_value(String::from_iter(std::iter::repeat_n(
MASK,
value.chars().count(),
)));
} else {
node.set_value(value);
}
if value.is_empty() && !text.is_empty() {
node.set_placeholder(text);
}
}
WidgetKind::DragValue => {
let typed = self
.store
.by_key(key)
.is_some_and(|stored| stored.widget.is_typed_number());
match self.edits.get(&key).filter(|_| typed) {
Some(state) => node.set_value(state.text()),
None => node.set_value(text),
}
}
WidgetKind::Select => node.set_value(text),
_ if !text.is_empty() => node.set_label(text),
_ => {}
}
}
fn gather_text(&self, index: usize, out: &mut String) {
let mut next = self.nodes[index].first_child;
while let Some(child) = next {
let node = &self.nodes[child];
if self.store.get(node.slot).kind != WidgetKind::Decoration {
if let Content::Text { start, end } | Content::Run { start, end } = node.content {
let text = self.text[start..end].trim();
if !text.is_empty() {
if !out.is_empty() {
out.push(' ');
}
out.push_str(text);
}
}
self.gather_text(child, out);
}
next = node.next_sibling;
}
}
}
#[derive(Clone, Debug)]
pub(super) struct TextField {
value: String,
anchor: usize,
focus: usize,
}
fn push_text_run(key: NodeKey, field: &TextField, node: &mut Node, out: &mut Vec<(NodeId, Node)>) {
let id = NodeId(Ui::key_under(key, KeySource::TextRun).0);
let mut run = Node::new(Role::TextRun);
run.set_value(field.value.as_str());
let lengths: Vec<u8> = field
.value
.chars()
.map(|c| u8::try_from(c.len_utf8()).expect("a char is at most four bytes"))
.collect();
run.set_character_lengths(lengths);
if let Some(bounds) = node.bounds() {
run.set_bounds(bounds);
}
let at = |character_index| TextPosition {
node: id,
character_index,
};
node.set_text_selection(TextSelection {
anchor: at(field.anchor),
focus: at(field.focus),
});
node.push_child(id);
out.push((id, run));
}
fn clickable(behavior: focus::Behavior) -> bool {
behavior.role != focus::Role::None && !behavior.disabled
}
const fn role_of(content: Content, kind: WidgetKind) -> Role {
match kind {
WidgetKind::None | WidgetKind::Decoration => match content {
Content::Block => Role::GenericContainer,
Content::Text { .. } | Content::Run { .. } => Role::Label,
Content::Paragraph => Role::Paragraph,
Content::Image(_) => Role::Image,
},
WidgetKind::Button | WidgetKind::Disclosure => Role::Button,
WidgetKind::Checkbox => Role::CheckBox,
WidgetKind::Slider => Role::Slider,
WidgetKind::DragValue => Role::SpinButton,
WidgetKind::TextInput { masked: false } => Role::TextInput,
WidgetKind::TextInput { masked: true } => Role::PasswordInput,
WidgetKind::Select => Role::ComboBox,
WidgetKind::SelectList => Role::ListBox,
WidgetKind::SelectOption => Role::ListBoxOption,
WidgetKind::TreeRow | WidgetKind::OutlinerRow => Role::TreeItem,
WidgetKind::Outliner => Role::Tree,
WidgetKind::OutlinerToggle => Role::DisclosureTriangle,
WidgetKind::List { selectable: false } => Role::List,
WidgetKind::List { selectable: true } => Role::ListBox,
WidgetKind::ListRow { selectable: false } => Role::ListItem,
WidgetKind::ListRow { selectable: true } => Role::ListBoxOption,
WidgetKind::TabStrip => Role::TabList,
WidgetKind::Tab => Role::Tab,
WidgetKind::TabPanel => Role::TabPanel,
WidgetKind::Splitter => Role::Splitter,
WidgetKind::Pane => Role::Pane,
WidgetKind::ScrollBar => Role::ScrollBar,
WidgetKind::Popup => Role::Dialog,
WidgetKind::Menu => Role::Menu,
WidgetKind::MenuItem => Role::MenuItem,
WidgetKind::Tooltip => Role::Tooltip,
WidgetKind::Inspector => Role::Group,
}
}
const fn is_whole(kind: WidgetKind) -> bool {
matches!(
kind,
WidgetKind::Button
| WidgetKind::Checkbox
| WidgetKind::Slider
| WidgetKind::DragValue
| WidgetKind::TextInput { .. }
| WidgetKind::Select
| WidgetKind::SelectOption
| WidgetKind::Disclosure
| WidgetKind::TreeRow
| WidgetKind::Tab
| WidgetKind::MenuItem
| WidgetKind::Splitter
| WidgetKind::OutlinerToggle
)
}