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