Skip to main content

mitsuami_core/ui/
accessibility.rs

1//! The computed accessibility tree.
2
3use crate::a11y::{A11yNode, Role};
4use crate::geometry::{Point, Rect};
5use crate::widget::{NodeId, Prop, RowKey, WidgetKind};
6
7use super::{Inner, Ui};
8
9impl Ui {
10    /// The computed accessibility tree of a window.
11    pub fn a11y_tree(&self, window: NodeId) -> Option<A11yNode> {
12        let inner = self.inner.borrow();
13        let mut nodes = inner.a11y(window, Point::ZERO);
14        (nodes.len() == 1).then(|| nodes.remove(0))
15    }
16}
17
18impl Inner {
19    fn text_of(&self, id: NodeId) -> Option<String> {
20        let node = self.nodes.get(&id)?;
21        crate::find_prop!(node.props, Text).or_else(|| crate::find_prop!(node.props, Label))
22    }
23
24    fn a11y(&self, id: NodeId, parent_origin: Point) -> Vec<A11yNode> {
25        let node = &self.nodes[&id];
26        // Custom widgets bring their own semantics; the app's overrides win.
27        let a11y = match node.custom() {
28            Some(custom) => custom.a11y().overridden_by(&node.a11y),
29            None => node.a11y.clone(),
30        };
31        if a11y.hidden || node.style.is_hidden() || self.is_hidden_page(id) {
32            return Vec::new();
33        }
34        let frame =
35            if node.kind == WidgetKind::Window { node.frame } else { self.placed_frame(id).offset(parent_origin) };
36        let origin = Inner::child_origin(node, frame);
37        // A window's sidebar reads first, as it's on the leading side.
38        let mut native_children = node.native_children.clone();
39        native_children.sort_by_key(|c| self.nodes[c].kind != WidgetKind::Sidebar);
40        let mut children: Vec<A11yNode> = native_children.iter().flat_map(|c| self.a11y(*c, origin)).collect();
41        if node.kind == WidgetKind::Sidebar {
42            children = self.sidebar_items(id, frame);
43        }
44        // A tab view's tabs come before the page shown.
45        if node.kind == WidgetKind::Tabs {
46            children.splice(0..0, self.tabs(id, frame));
47        }
48        if node.kind == WidgetKind::RadioGroup {
49            children = self.radio_buttons(id, frame);
50        }
51        // A table's headers, then its cells in rows.
52        if node.kind == WidgetKind::Table {
53            children = self.table_children(id, frame, children);
54        }
55
56        let labelled = a11y.label.is_some() || a11y.labelled_by.is_some();
57        let row = crate::find_prop!(node.props, Row);
58        let cell = crate::find_prop!(node.props, Cell);
59        let role = a11y.role.unwrap_or(match node.kind {
60            WidgetKind::Window => Role::Window,
61            WidgetKind::Container if row.is_some() => Role::ListItem,
62            WidgetKind::Container if cell.is_some() => Role::Cell,
63            WidgetKind::Container if labelled => Role::Group,
64            WidgetKind::Container | WidgetKind::ToolbarItem | WidgetKind::Fragment => Role::None,
65            WidgetKind::ScrollView => Role::ScrollArea,
66            WidgetKind::List | WidgetKind::Sidebar => Role::List,
67            WidgetKind::Table => Role::Table,
68            WidgetKind::Tabs => Role::TabGroup,
69            // Named by its heading, as a fieldset by its legend.
70            WidgetKind::Group => Role::Group,
71            WidgetKind::Text => Role::StaticText,
72            WidgetKind::Button => Role::Button,
73            WidgetKind::ToggleButton => Role::ToggleButton,
74            WidgetKind::MenuButton => Role::MenuButton,
75            // A text field that hides its text, as every platform exposes
76            // one (AppKit's secure subrole, Qt's and UIA's password flag).
77            WidgetKind::TextInput | WidgetKind::PasswordInput => Role::TextField,
78            WidgetKind::SearchInput => Role::SearchField,
79            WidgetKind::TextArea => Role::TextArea,
80            WidgetKind::Checkbox => Role::Checkbox,
81            WidgetKind::Switch => Role::Switch,
82            WidgetKind::Select => Role::ComboBox,
83            WidgetKind::RadioGroup => Role::RadioGroup,
84            WidgetKind::Slider => Role::Slider,
85            WidgetKind::NumberInput => Role::SpinButton,
86            // A spinner reads as a progress bar without a value, as in ARIA.
87            WidgetKind::Progress | WidgetKind::Spinner => Role::ProgressBar,
88            WidgetKind::Separator => Role::Separator,
89            // What the app draws there is a picture to assistive technology.
90            WidgetKind::Image | WidgetKind::Icon | WidgetKind::FileIcon | WidgetKind::GpuSurface => Role::Image,
91            WidgetKind::Custom(_) | WidgetKind::Native => Role::Group,
92        });
93        if role == Role::None {
94            return children;
95        }
96        let props = &node.props;
97        let name =
98            a11y.label.clone().or_else(|| a11y.labelled_by.and_then(|l| self.text_of(l))).or_else(|| match node.kind {
99                WidgetKind::Window => crate::find_prop!(props, Title),
100                WidgetKind::Group => crate::find_prop!(props, Title).filter(|t| !t.is_empty()),
101                WidgetKind::Text => crate::find_prop!(props, Text),
102                WidgetKind::Button
103                | WidgetKind::ToggleButton
104                | WidgetKind::MenuButton
105                | WidgetKind::Checkbox
106                | WidgetKind::Switch
107                | WidgetKind::Select
108                | WidgetKind::RadioGroup
109                | WidgetKind::Tabs
110                | WidgetKind::Slider
111                | WidgetKind::NumberInput
112                | WidgetKind::Progress
113                | WidgetKind::Spinner
114                | WidgetKind::Image
115                | WidgetKind::Icon
116                | WidgetKind::FileIcon
117                | WidgetKind::GpuSurface => crate::find_prop!(props, Label),
118                WidgetKind::TextInput | WidgetKind::PasswordInput | WidgetKind::SearchInput | WidgetKind::TextArea => {
119                    crate::find_prop!(props, Placeholder)
120                }
121                // Rows and cells read as their text, as screen readers read
122                // native rows and cells.
123                WidgetKind::Container if row.is_some() || cell.is_some() => text_in(&children),
124                _ => None,
125            });
126        let selected = row.map(|key| {
127            let list = node.native_parent.and_then(|p| self.nodes.get(&p));
128            // Looked at in place: a copy per row of a long selection adds up.
129            list.and_then(|l| {
130                l.props.iter().find_map(|p| match p {
131                    Prop::Selected(selected) => Some(selected.contains(&key)),
132                    _ => None,
133                })
134            })
135            .unwrap_or(false)
136        });
137        vec![A11yNode {
138            id,
139            role,
140            name,
141            // A tooltip is read as the description, as every platform
142            // reads one, unless the app gave its own.
143            description: a11y.description.or_else(|| crate::find_prop!(props, Tooltip).filter(|t| !t.is_empty())),
144            value: match node.kind {
145                WidgetKind::TextInput | WidgetKind::SearchInput | WidgetKind::TextArea => {
146                    Some(crate::find_prop!(props, Value).unwrap_or_default())
147                }
148                // Never read out.
149                WidgetKind::PasswordInput => None,
150                // The chosen option; empty without options.
151                WidgetKind::Select => {
152                    let options = crate::find_prop!(props, Options).unwrap_or_default();
153                    let chosen = crate::find_prop!(props, SelectedIndex).flatten();
154                    Some(chosen.and_then(|i| options.get(i).cloned()).unwrap_or_default())
155                }
156                WidgetKind::Slider | WidgetKind::NumberInput => crate::find_prop!(props, Number).map(|n| n.to_string()),
157                // As screen readers read progress bars.
158                WidgetKind::Progress => {
159                    crate::find_prop!(props, Progress).flatten().map(|f| format!("{}%", (f * 100.0).round()))
160                }
161                _ => a11y.value,
162            },
163            checked: match node.kind {
164                WidgetKind::Checkbox | WidgetKind::Switch | WidgetKind::ToggleButton => {
165                    Some(crate::find_prop!(props, Checked).unwrap_or(false))
166                }
167                _ => None,
168            },
169            mixed: node.kind == WidgetKind::Checkbox && crate::find_prop!(props, Mixed) == Some(true),
170            read_only: crate::find_prop!(props, ReadOnly) == Some(true),
171            password: node.kind == WidgetKind::PasswordInput,
172            selected,
173            enabled: crate::find_prop!(props, Enabled).unwrap_or(true),
174            test_id: node.test_id.clone(),
175            frame,
176            children,
177        }]
178    }
179
180    /// A tab view's tabs, which are its data, not nodes: named by their
181    /// titles, the shown page's selected. They stand for the tab view,
182    /// where assistive technology acts on them.
183    fn tabs(&self, id: NodeId, frame: Rect) -> Vec<A11yNode> {
184        let props = &self.nodes[&id].props;
185        let shown = crate::find_prop!(props, SelectedIndex).flatten();
186        let titles = crate::find_prop!(props, TabTitles).unwrap_or_default();
187        titles
188            .into_iter()
189            .enumerate()
190            .map(|(index, title)| A11yNode {
191                id,
192                role: Role::Tab,
193                name: Some(title),
194                description: None,
195                value: None,
196                checked: None,
197                mixed: false,
198                read_only: false,
199                password: false,
200                selected: Some(shown == Some(index)),
201                enabled: true,
202                test_id: None,
203                frame,
204                children: Vec::new(),
205            })
206            .collect()
207    }
208
209    /// A radio group's buttons, which are its data, not nodes: named by
210    /// their options, the chosen one's checked. They stand for the group,
211    /// where assistive technology acts on them.
212    fn radio_buttons(&self, id: NodeId, frame: Rect) -> Vec<A11yNode> {
213        let props = &self.nodes[&id].props;
214        let chosen = crate::find_prop!(props, SelectedIndex).flatten();
215        let enabled = crate::find_prop!(props, Enabled).unwrap_or(true);
216        let options = crate::find_prop!(props, Options).unwrap_or_default();
217        options
218            .into_iter()
219            .enumerate()
220            .map(|(index, option)| A11yNode {
221                id,
222                role: Role::RadioButton,
223                name: Some(option),
224                description: None,
225                value: None,
226                checked: Some(chosen == Some(index)),
227                mixed: false,
228                read_only: false,
229                password: false,
230                selected: None,
231                enabled,
232                test_id: None,
233                frame,
234                children: Vec::new(),
235            })
236            .collect()
237    }
238
239    /// A table's column headers, which are its data, not nodes (named by
240    /// their titles, the sorted one's value its order), then its rows:
241    /// its cells, grouped by row. A row stands for its first cell, which
242    /// assistive technology selects the row through.
243    fn table_children(&self, id: NodeId, frame: Rect, cells: Vec<A11yNode>) -> Vec<A11yNode> {
244        let props = &self.nodes[&id].props;
245        let sort = crate::find_prop!(props, Sort).flatten();
246        let selected = crate::find_prop!(props, Selected).unwrap_or_default();
247        let node = |id, role, name: Option<String>, value, selected, frame, children| A11yNode {
248            id,
249            role,
250            name,
251            description: None,
252            value,
253            checked: None,
254            mixed: false,
255            read_only: false,
256            password: false,
257            selected,
258            enabled: true,
259            test_id: None,
260            frame,
261            children,
262        };
263        let columns = crate::find_prop!(props, Columns).unwrap_or_default();
264        let mut out: Vec<A11yNode> = columns
265            .into_iter()
266            .enumerate()
267            .map(|(index, column)| {
268                let order = sort.filter(|s| s.column == index).map(|s| format!("{:?}", s.order));
269                node(id, Role::ColumnHeader, Some(column.title), order, None, frame, Vec::new())
270            })
271            .collect();
272        let mut rows: Vec<(RowKey, Vec<A11yNode>)> = Vec::new();
273        for cell in cells {
274            let Some(key) = crate::find_prop!(self.nodes[&cell.id].props, Cell).map(|c| c.row) else { continue };
275            match rows.last_mut() {
276                Some((last, cells)) if *last == key => cells.push(cell),
277                _ => rows.push((key, vec![cell])),
278            }
279        }
280        out.extend(rows.into_iter().map(|(key, cells)| {
281            let frame = cells.iter().map(|c| c.frame).reduce(|a, b| a.union(&b)).unwrap_or_default();
282            let name = cells.iter().filter_map(|c| c.name.as_deref()).collect::<Vec<_>>().join(" ");
283            let name = (!name.is_empty()).then_some(name);
284            node(cells[0].id, Role::Row, name, None, Some(selected.contains(&key)), frame, cells)
285        }));
286        out
287    }
288
289    /// A sidebar's items, which are its data, not nodes: list items named
290    /// by their titles, under a heading for each titled section. They
291    /// stand for the sidebar, where assistive technology acts on them.
292    fn sidebar_items(&self, id: NodeId, frame: Rect) -> Vec<A11yNode> {
293        let props = &self.nodes[&id].props;
294        let selected = crate::find_prop!(props, SelectedIndex).flatten();
295        let node = |role, name: &str, description: Option<&str>, selected| A11yNode {
296            id,
297            role,
298            name: Some(name.to_owned()),
299            description: description.map(str::to_owned),
300            value: None,
301            checked: None,
302            mixed: false,
303            read_only: false,
304            password: false,
305            selected,
306            enabled: true,
307            test_id: None,
308            frame,
309            children: Vec::new(),
310        };
311        let mut out = Vec::new();
312        let mut index = 0;
313        for section in crate::find_prop!(props, Sections).unwrap_or_default() {
314            out.extend(section.title.as_deref().map(|title| node(Role::Heading, title, None, None)));
315            for item in &section.items {
316                out.push(node(Role::ListItem, &item.title, item.subtitle.as_deref(), Some(selected == Some(index))));
317                index += 1;
318            }
319        }
320        out
321    }
322}
323
324/// The text in these nodes, joined, as screen readers read a row or cell.
325fn text_in(children: &[A11yNode]) -> Option<String> {
326    let texts: Vec<&str> = children
327        .iter()
328        .flat_map(|c| c.walk())
329        .filter(|n| n.role == Role::StaticText)
330        .filter_map(|n| n.name.as_deref())
331        .collect();
332    (!texts.is_empty()).then(|| texts.join(" "))
333}