Skip to main content

rust_glass/
accessibility.rs

1//! Accessibility tree for screen readers and other assistive technology.
2//!
3//! Widgets describe themselves with [`Ui::access`](crate::Ui::access) while
4//! they are drawn. Nothing is collected until a screen reader asks for the
5//! tree, so an app without one pays nothing. The window host passes the tree
6//! to the platform through AccessKit and turns requests from the screen
7//! reader into [`Event::Access`](crate::input::Event::Access) input.
8
9use std::collections::HashSet;
10
11use crate::context::{Id, Order};
12use crate::geometry::Rect;
13
14/// What kind of element a node is. Screen readers announce it with the label.
15#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
16pub enum Role {
17    /// Something to press.
18    Button,
19    /// A link to another place.
20    Link,
21    /// A box that is checked or not.
22    CheckBox,
23    /// An on and off switch.
24    Switch,
25    /// One choice of a group.
26    RadioButton,
27    /// A value picked along a track.
28    Slider,
29    /// A number changed in steps.
30    SpinButton,
31    /// A one line text field.
32    TextInput,
33    /// A text field of several lines.
34    MultilineTextInput,
35    /// A text field whose content is hidden.
36    PasswordInput,
37    /// A search field.
38    SearchInput,
39    /// Text.
40    Label,
41    /// A title of a page or section.
42    Heading,
43    /// One tab, segment or navigation entry.
44    Tab,
45    /// A group of tabs.
46    TabList,
47    /// An entry of a menu.
48    MenuItem,
49    /// A button that opens a list of options.
50    ComboBox,
51    /// Progress of a task.
52    ProgressIndicator,
53    /// A value within a known range, such as a gauge.
54    Meter,
55    /// A picture.
56    Image,
57    /// A color swatch that opens a picker.
58    ColorWell,
59    /// An area that scrolls.
60    ScrollView,
61    /// A list of items.
62    List,
63    /// One item of a list.
64    ListItem,
65    /// Elements that belong together.
66    Group,
67}
68
69impl Role {
70    /// Returns `true` for roles that react to a click.
71    pub fn clickable(self) -> bool {
72        matches!(
73            self,
74            Role::Button
75                | Role::Link
76                | Role::CheckBox
77                | Role::Switch
78                | Role::RadioButton
79                | Role::Tab
80                | Role::MenuItem
81                | Role::ComboBox
82                | Role::ColorWell
83        )
84    }
85    fn text_input(self) -> bool {
86        matches!(self, Role::TextInput | Role::MultilineTextInput | Role::PasswordInput | Role::SearchInput)
87    }
88}
89
90/// The number of a slider, stepper or progress indicator.
91#[derive(Clone, Copy, Debug, PartialEq)]
92pub struct Numeric {
93    /// Current value.
94    pub value: f64,
95    /// Smallest value.
96    pub min: f64,
97    /// Largest value.
98    pub max: f64,
99    /// Step between values, if it moves in steps.
100    pub step: Option<f64>,
101}
102
103/// One element as assistive technology sees it.
104#[derive(Clone, Debug)]
105pub struct Node {
106    /// The id of the widget. Requests from the screen reader carry it.
107    pub id: Id,
108    /// What kind of element it is.
109    pub role: Role,
110    /// Bounds in points.
111    pub rect: Rect,
112    /// The name read out first.
113    pub label: String,
114    /// Text content or a value, read out after the label.
115    pub value: Option<String>,
116    /// The number of a slider or stepper.
117    pub numeric: Option<Numeric>,
118    /// Whether a checkbox or switch is on.
119    pub toggled: Option<bool>,
120    /// Whether a tab, segment or menu item is selected.
121    pub selected: Option<bool>,
122    /// Whether a menu or section is open.
123    pub expanded: Option<bool>,
124    /// The element cannot be used right now.
125    pub disabled: bool,
126    /// Set when the node was registered with [`Context::focusable`](crate::Context::focusable).
127    pub focusable: bool,
128    pub(crate) layer: usize,
129}
130
131impl Node {
132    /// Creates a node without a label.
133    pub fn new(id: Id, role: Role, rect: Rect) -> Self {
134        Self {
135            id,
136            role,
137            rect,
138            label: String::new(),
139            value: None,
140            numeric: None,
141            toggled: None,
142            selected: None,
143            expanded: None,
144            disabled: false,
145            focusable: false,
146            layer: 0,
147        }
148    }
149    /// Sets the label.
150    pub fn label(&mut self, label: impl Into<String>) -> &mut Self {
151        self.label = label.into();
152        self
153    }
154    /// Sets the value read after the label.
155    pub fn value(&mut self, value: impl Into<String>) -> &mut Self {
156        self.value = Some(value.into());
157        self
158    }
159    /// Sets the number of a slider, stepper or progress indicator.
160    pub fn numeric(&mut self, value: f64, min: f64, max: f64, step: Option<f64>) -> &mut Self {
161        self.numeric = Some(Numeric { value, min, max, step });
162        self
163    }
164    /// Sets whether a checkbox or switch is on.
165    pub fn toggled(&mut self, on: bool) -> &mut Self {
166        self.toggled = Some(on);
167        self
168    }
169    /// Sets whether the element is selected.
170    pub fn selected(&mut self, on: bool) -> &mut Self {
171        self.selected = Some(on);
172        self
173    }
174    /// Sets whether the element is open.
175    pub fn expanded(&mut self, on: bool) -> &mut Self {
176        self.expanded = Some(on);
177        self
178    }
179}
180
181/// A request from assistive technology. Arrives as
182/// [`Event::Access`](crate::input::Event::Access) and is applied by the widget
183/// it targets.
184#[derive(Clone, Debug, PartialEq)]
185pub enum Action {
186    /// Press the element.
187    Click,
188    /// Give the element keyboard focus.
189    Focus,
190    /// Take keyboard focus away from the element.
191    Blur,
192    /// One step up. Delivered to the focused widget as the right arrow key.
193    Increment,
194    /// One step down. Delivered as the left arrow key.
195    Decrement,
196    /// Replace the whole text of a field.
197    SetValue(String),
198    /// Set the value of a slider or stepper.
199    SetNumber(f64),
200    /// Insert text at the caret, replacing the selection.
201    ReplaceSelection(String),
202}
203
204/// Collected nodes and pending requests of one window.
205#[derive(Default)]
206pub(crate) struct Access {
207    pub on: bool,
208    pub nodes: Vec<Node>,
209    pub requests: Vec<(Id, Action)>,
210}
211
212/// Window title, kept as the label of the root node.
213pub(crate) const ROOT: Id = Id(0x9e37_79b9_7f4a_7c15);
214
215pub(crate) struct LayerInfo {
216    pub index: usize,
217    pub id: Id,
218    pub order: Order,
219}
220
221/// Turn the nodes of a frame into a full AccessKit tree.
222pub(crate) fn tree(
223    nodes: &[Node],
224    layers: &[LayerInfo],
225    focus: Option<Id>,
226    ppp: f32,
227    screen: Rect,
228    title: &str,
229) -> accesskit::TreeUpdate {
230    use accesskit::{
231        Action as A, Affine, Node as N, NodeId, Rect as R, Role as AR, Toggled, TreeInfo, TreeUpdate,
232    };
233    let rect = |r: Rect| R { x0: r.min.x as f64, y0: r.min.y as f64, x1: r.max.x as f64, y1: r.max.y as f64 };
234    let mut out: Vec<(NodeId, N)> = Vec::with_capacity(nodes.len() + layers.len() + 1);
235    let mut seen = HashSet::new();
236    seen.insert(ROOT);
237    let mut root_children = Vec::new();
238    let mut focus_found = None;
239    for l in layers {
240        let mut children = Vec::new();
241        let mut bounds = Rect::NOTHING;
242        for n in nodes.iter().filter(|n| n.layer == l.index) {
243            // A widget drawn twice in one frame keeps its first node.
244            if !seen.insert(n.id) {
245                continue;
246            }
247            children.push(NodeId(n.id.0));
248            bounds = bounds.union(n.rect);
249            if focus == Some(n.id) {
250                focus_found = Some(n.id);
251            }
252            let mut a = N::new(match n.role {
253                Role::Button => AR::Button,
254                Role::Link => AR::Link,
255                Role::CheckBox => AR::CheckBox,
256                Role::Switch => AR::Switch,
257                Role::RadioButton => AR::RadioButton,
258                Role::Slider => AR::Slider,
259                Role::SpinButton => AR::SpinButton,
260                Role::TextInput => AR::TextInput,
261                Role::MultilineTextInput => AR::MultilineTextInput,
262                Role::PasswordInput => AR::PasswordInput,
263                Role::SearchInput => AR::SearchInput,
264                Role::Label => AR::Label,
265                Role::Heading => AR::Heading,
266                Role::Tab => AR::Tab,
267                Role::TabList => AR::TabList,
268                Role::MenuItem => AR::MenuItem,
269                Role::ComboBox => AR::ComboBox,
270                Role::ProgressIndicator => AR::ProgressIndicator,
271                Role::Meter => AR::Meter,
272                Role::Image => AR::Image,
273                Role::ColorWell => AR::ColorWell,
274                Role::ScrollView => AR::ScrollView,
275                Role::List => AR::List,
276                Role::ListItem => AR::ListItem,
277                Role::Group => AR::Group,
278            });
279            a.set_bounds(rect(n.rect));
280            match (&n.value, n.role) {
281                // Static text is read from its value.
282                (None, Role::Label) => a.set_value(n.label.as_str()),
283                (v, _) => {
284                    if !n.label.is_empty() {
285                        a.set_label(n.label.as_str());
286                    }
287                    if let Some(v) = v {
288                        a.set_value(v.as_str());
289                    }
290                }
291            }
292            if let Some(v) = n.numeric {
293                a.set_numeric_value(v.value);
294                a.set_min_numeric_value(v.min);
295                a.set_max_numeric_value(v.max);
296                if let Some(s) = v.step {
297                    a.set_numeric_value_step(s);
298                }
299            }
300            if let Some(t) = n.toggled {
301                a.set_toggled(if t { Toggled::True } else { Toggled::False });
302            }
303            if let Some(s) = n.selected {
304                a.set_selected(s);
305            }
306            if let Some(e) = n.expanded {
307                a.set_expanded(e);
308            }
309            if n.disabled {
310                a.set_disabled();
311            } else {
312                if n.role.clickable() {
313                    a.add_action(A::Click);
314                }
315                if n.focusable {
316                    a.add_action(A::Focus);
317                }
318                if n.numeric.is_some() && matches!(n.role, Role::Slider | Role::SpinButton) {
319                    a.add_action(A::Increment);
320                    a.add_action(A::Decrement);
321                    a.add_action(A::SetValue);
322                }
323                if n.role.text_input() {
324                    a.add_action(A::SetValue);
325                    a.add_action(A::ReplaceSelectedText);
326                }
327            }
328            out.push((NodeId(n.id.0), a));
329        }
330        if children.is_empty() {
331            continue;
332        }
333        let group_id = l.id.with("access");
334        let mut g = N::new(match l.order {
335            Order::Window => AR::Window,
336            Order::Modal => AR::Dialog,
337            Order::Toast => AR::Alert,
338            Order::Tooltip => AR::Tooltip,
339            _ => AR::Group,
340        });
341        g.set_bounds(rect(bounds));
342        g.set_children(children);
343        root_children.push(NodeId(group_id.0));
344        out.push((NodeId(group_id.0), g));
345    }
346    let mut root = N::new(AR::Window);
347    root.set_label(title);
348    root.set_bounds(rect(screen));
349    root.set_transform(Affine::scale(ppp as f64));
350    root.set_children(root_children);
351    out.push((NodeId(ROOT.0), root));
352    let mut info = TreeInfo::new(NodeId(ROOT.0));
353    info.toolkit_name = Some("rust-glass".into());
354    info.toolkit_version = Some(env!("CARGO_PKG_VERSION").into());
355    TreeUpdate {
356        nodes: out,
357        tree: Some(info),
358        tree_id: accesskit::TreeId::ROOT,
359        focus: NodeId(focus_found.unwrap_or(ROOT).0),
360    }
361}
362
363/// Translate a request from AccessKit. Returns `None` for actions no widget
364/// handles.
365pub(crate) fn from_accesskit(req: &accesskit::ActionRequest) -> Option<(Id, Action)> {
366    use accesskit::{Action as A, ActionData as D};
367    let id = Id(req.target_node.0);
368    let action = match (req.action, &req.data) {
369        (A::Click | A::Expand | A::Collapse, _) => Action::Click,
370        (A::Focus, _) => Action::Focus,
371        (A::Blur, _) => Action::Blur,
372        (A::Increment, _) => Action::Increment,
373        (A::Decrement, _) => Action::Decrement,
374        (A::SetValue, Some(D::Value(v))) => Action::SetValue(v.to_string()),
375        (A::SetValue, Some(D::NumericValue(v))) => Action::SetNumber(*v),
376        (A::ReplaceSelectedText, Some(D::Value(v))) => Action::ReplaceSelection(v.to_string()),
377        _ => return None,
378    };
379    Some((id, action))
380}