crcbl-ui 0.20.0

Crucible immediate-mode GUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
//! The tree as a screen reader reads it: an AccessKit [`TreeUpdate`] built from
//! the frame as laid out, and the actions a reader asks for acted on. Behind
//! the `accesskit` feature; `crcbl-shell`'s feature of the same name carries
//! the update to the platform and brings the requests back.
//!
//! # The tree
//!
//! A node's [`NodeKey`] is stable across frames, so it is the node's
//! [`NodeId`]. Above the frame's roots — the tree's and every pop-up's and the
//! tooltip's, in build order — sits a synthetic [`Role::Window`] keyed by the
//! seed every root's key is derived from, which no node's key equals.
//!
//! **Every update carries the whole tree**, with [`TreeInfo`], rather than the
//! nodes that changed: simple, always valid however many frames the reader
//! missed, and what AccessKit asks for when a reader first connects. A frame
//! is rebuilt from nothing anyway, so a diff would cost a copy of last frame's
//! tree to compare against.
//!
//! A node's role comes from what its builder recorded it as
//! ([`WidgetKind`]), never from its selector, whose type a caller may have
//! replaced. A node no builder marked is a [`Role::Label`] holding its text
//! when it is a text span, a [`Role::Image`] when it is a picture, and a
//! [`Role::GenericContainer`] otherwise. A widget whose parts are all its
//! builder's own — a button, a checkbox, a tab, a select's option — is one
//! node: its spans' text becomes its label, or its value where the text is
//! what it holds (a drag-value's number, a select's choice), and its parts are
//! left out. Decorations — a checkbox's box, a toggle's glyph — are left out
//! with everything inside them.
//!
//! Text is as it was built, not as `text-overflow: ellipsis` cut it: a reader
//! should hear what a label says, not what fitted.
//!
//! # What it does not say
//!
//! Only what the tree holds. A slider's and a drag-value's numbers, their
//! range and step are the caller's and never stored, so a slider has no value
//! and a drag-value only the text it shows; a block a caller built to look
//! like a checkbox, without [`Ui::checkbox`], has no toggled state. A widget's
//! name drawn beside it rather than inside it (a text input's label, a select's
//! caption) is not tied to it.
//!
//! # Names a caller gives
//!
//! [`Ui::set_accessible_label`] names a node for this frame. Its own text spans
//! are then not read on their own — they are the pieces the name stands for, as
//! when a label is drawn as runs to accent part of it — and a block left with
//! nothing else to hold is read as one [`Role::Label`].
//!
//! [`Ui::set_accessible_text_input`] says a block a caller drew itself — its
//! own caret, its own pre-edit — is an editable text field: it reads as a
//! [`Role::TextInput`] holding the value given, not as its spans.
//!
//! # Text fields
//!
//! A text field, [`Ui::text_input`]'s or one a caller marked, holds one
//! [`Role::TextRun`] child with its value, a character per `char`, and carries
//! its caret and selection as a [`TextSelection`] on that run: what a reader
//! needs to say where the caret is and what is selected, and what a platform's
//! text interface (UI Automation's `TextPattern`, AT-SPI's `Text`) is built
//! from. The run's key is derived from the field's under a rule no built node
//! uses, so it never collides with one.
//!
//! # Actions
//!
//! A focusable node offers [`Action::Focus`], the focused node
//! [`Action::Blur`], and a node with a focus role that is not disabled
//! [`Action::Click`]; [`Ui::accessibility_action`] acts on those three.

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 {
    /// The whole tree as an AccessKit update, for `crcbl-shell`'s
    /// `Shell::update_accessibility`: valid once the frame is laid out, and
    /// sent whole every time — see the module docs for what it holds.
    ///
    /// Focus is the focused node when this frame built it, else the window.
    #[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,
        }
    }

    /// Acts on what a screen reader asked of a node in the tree
    /// [`Ui::accessibility_update`] built: [`Action::Focus`] focuses it as
    /// [`Ui::set_focus`] does, [`Action::Blur`] takes focus away from the
    /// focused node as [`Ui::clear_focus`] does, and [`Action::Click`] makes
    /// it report [`Response::clicked`](super::Response::clicked) on the next
    /// frame, as a pointer's click would — focusing it, and engaging a widget
    /// that engages.
    ///
    /// Returns whether it was acted on: false for another tree, a node the
    /// store does not hold (the window among them), an action the node does
    /// not offer, and any other action.
    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,
        }
    }

    /// Names the node `key` for screen readers this frame, as `label`: what a
    /// reader hears for it, in place of the text spans directly inside it. For
    /// a name drawn as pieces — a label split into runs so the characters a
    /// search matched can be accented reads as its runs, "ga" then "mma",
    /// unless the block holding them is named "gamma". Set it each frame the
    /// node is built; a key not built this frame is ignored.
    pub fn set_accessible_label(&mut self, key: NodeKey, label: &str) {
        self.accessible_labels.insert(key, label.to_owned());
    }

    /// Says the node `key` is an editable text field holding `value`, for
    /// screen readers this frame: for a field a caller draws itself, with its
    /// own caret and pre-edit, which would otherwise read as the spans it was
    /// drawn in. `selection` is the selected bytes of `value` with the caret at
    /// its end; an empty range is a caret alone. The field's spans are not read
    /// on their own, and [`Ui::set_accessible_label`] on the same key names it.
    /// Set it each frame the node is built; a key not built this frame is
    /// ignored.
    ///
    /// # Panics
    ///
    /// If either end of `selection` is past the end of `value` or inside a
    /// character, as slicing `value` with it would.
    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);
    }

    /// The node a screen reader clicked since the last frame, now reporting
    /// clicked — unless it has gone, or been disabled, since.
    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)
    }

    /// Adds the frame node `index` under `parent`, and pushes it and what it
    /// holds onto `out`, unless it is a decoration.
    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));
        }
        // A list row is selected or not only in a list that has a selection,
        // [`Ui::selectable_list`]; a plain list's rows say nothing either way.
        // UIA offers its SelectionItem pattern, and AT-SPI says a row is
        // selectable, only on a row that says one or the other.
        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());
        }
        // Where the name goes is the role's: AccessKit names a `Label` from
        // its value, as it does every text span, and everything else from its
        // label, so a `Label` carrying the name as a label reads as nothing.
        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));
    }

    /// What [`Ui::text_input`]'s field `key`, built as `kind`, holds, as its
    /// node's value shows it: masked for a password.
    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(),
        })
    }

    /// Names the widget at frame node `index`, one node with no children in
    /// the tree, from the text its parts hold: its label, or for a widget that
    /// holds a value, its value.
    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);
                }
                // An empty input draws its placeholder in its value's place.
                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),
            _ => {}
        }
    }

    /// Appends the text of every span inside frame node `index`, outside
    /// decorations, to `out`, a space between each.
    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;
        }
    }
}

/// A text field's value, and its selection in `char`s; see the module docs.
#[derive(Clone, Debug)]
pub(super) struct TextField {
    value: String,
    /// Where the selection began: the caret itself when nothing is selected.
    anchor: usize,
    /// The caret.
    focus: usize,
}

/// Gives the text field `node`, keyed `key`, its one text run holding
/// `field`'s value, pushed onto `out`, and its selection on that run.
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));
}

/// Whether a node that behaves as `behavior` takes a click a reader asks for:
/// one with a focus role, as a pointer's press goes to, and not disabled.
fn clickable(behavior: focus::Behavior) -> bool {
    behavior.role != focus::Role::None && !behavior.disabled
}

/// The role a node of `content`, which its builder recorded as `kind`, has.
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,
        // A list that takes a selection is a list box, which both platforms
        // give a container's selection; a plain list's rows are not options.
        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,
    }
}

/// Whether a widget recorded as `kind` is one node in the tree, named from
/// its parts' text: every part is its builder's, so none holds anything a
/// reader could reach on its own. A list's or an outliner's row holds what the
/// caller built in it, a button among them, so it keeps its children.
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
    )
}