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