moirai-pal 0.7.0

Platform Abstraction Layer for Moirai async I/O operations
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
//! Validated, host-neutral accessibility semantics for native windows.

use accesskit::{Action, Node, NodeId, Role, TreeId, TreeInfo, TreeUpdate};
use std::collections::{HashMap, HashSet};
use std::io;

/// Maximum number of nodes retained by one native accessibility tree.
pub const MAX_ACCESSIBILITY_NODES: usize = 4_096;
/// Maximum UTF-8 bytes retained by one accessibility string.
pub const MAX_ACCESSIBILITY_TEXT_BYTES: usize = 4_096;
/// Maximum queued accessibility actions awaiting the window thread.
pub const MAX_ACCESSIBILITY_ACTIONS: usize = 256;

/// Role exposed by the format-neutral native accessibility contract.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AccessibilityRole {
    /// The application root.
    Application,
    /// A primary document region.
    Main,
    /// A navigation landmark containing links or commands.
    Navigation,
    /// A complementary region such as a sidebar.
    Complementary,
    /// A generic grouping container.
    Group,
    /// A command toolbar or title bar.
    Toolbar,
    /// A popup command menu.
    Menu,
    /// An actionable command inside a menu.
    MenuItem,
    /// An actionable button.
    Button,
    /// Static text.
    Text,
    /// An editable text control.
    TextInput,
    /// A binary choice control.
    CheckBox,
    /// A mutually exclusive choice control.
    Radio,
    /// A bounded numeric value control.
    Slider,
    /// A list or combobox selection control.
    ComboBox,
    /// A dialog surface.
    Dialog,
    /// A status or live-region message.
    Status,
    /// A table or grid surface.
    Table,
}

/// Action admitted by one native accessibility node.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AccessibilityAction {
    /// Activate the node's primary command.
    Activate,
    /// Move keyboard focus to the node.
    Focus,
    /// Replace the node's current value.
    SetValue,
    /// Toggle a binary choice.
    Toggle,
    /// Adjust a bounded numeric value.
    AdjustValue,
    /// Open a selection control.
    Open,
}

/// One validated node in a native accessibility tree.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccessibilityNode {
    id: u64,
    role: AccessibilityRole,
    name: String,
    description: Option<String>,
    value: Option<String>,
    keyboard_shortcut: Option<String>,
    children: Vec<u64>,
    hidden: bool,
    disabled: bool,
    focusable: bool,
    expanded: Option<bool>,
    selected: Option<bool>,
    checked: Option<bool>,
    actions: Vec<AccessibilityAction>,
}

impl AccessibilityNode {
    /// Creates a node with a nonzero stable identity and bounded name.
    pub fn new(id: u64, role: AccessibilityRole, name: impl Into<String>) -> io::Result<Self> {
        let name = name.into();
        validate_id(id)?;
        validate_text(&name)?;
        Ok(Self {
            id,
            role,
            name,
            description: None,
            value: None,
            keyboard_shortcut: None,
            children: Vec::new(),
            hidden: false,
            disabled: false,
            focusable: false,
            expanded: None,
            selected: None,
            checked: None,
            actions: Vec::new(),
        })
    }

    /// Replaces the optional accessible description.
    pub fn set_description(&mut self, description: Option<String>) -> io::Result<()> {
        if let Some(value) = &description {
            validate_text(value)?;
        }
        self.description = description;
        Ok(())
    }

    /// Replaces the optional value exposed to assistive technology.
    pub fn set_value(&mut self, value: Option<String>) -> io::Result<()> {
        if let Some(value) = &value {
            validate_text(value)?;
        }
        self.value = value;
        Ok(())
    }

    /// Replaces the keyboard shortcuts that activate this node, in the
    /// WAI-ARIA `aria-keyshortcuts` spelling (`Control+Shift+S`), separated
    /// by spaces when there are several.
    pub fn set_keyboard_shortcut(&mut self, shortcut: Option<String>) -> io::Result<()> {
        if let Some(value) = &shortcut {
            validate_text(value)?;
        }
        self.keyboard_shortcut = shortcut;
        Ok(())
    }

    /// Replaces the ordered child identities.
    pub fn set_children(&mut self, children: Vec<u64>) -> io::Result<()> {
        if children.len() > MAX_ACCESSIBILITY_NODES {
            return Err(limit_error("accessibility child count exceeds its bound"));
        }
        for child in &children {
            validate_id(*child)?;
        }
        self.children = children;
        Ok(())
    }

    /// Sets whether the node is hidden from assistive technology.
    pub const fn set_hidden(&mut self, hidden: bool) {
        self.hidden = hidden;
    }

    /// Sets whether the node rejects host actions.
    pub const fn set_disabled(&mut self, disabled: bool) {
        self.disabled = disabled;
    }

    /// Sets whether keyboard focus may land on the node.
    pub const fn set_focusable(&mut self, focusable: bool) {
        self.focusable = focusable;
    }

    /// Sets the optional expanded state.
    pub const fn set_expanded(&mut self, expanded: Option<bool>) {
        self.expanded = expanded;
    }

    /// Sets the optional selected state.
    pub const fn set_selected(&mut self, selected: Option<bool>) {
        self.selected = selected;
    }

    /// Sets the optional checked state.
    pub const fn set_checked(&mut self, checked: Option<bool>) {
        self.checked = checked;
    }

    /// Adds one action if it is not already present.
    pub fn add_action(&mut self, action: AccessibilityAction) {
        if !self.actions.contains(&action) {
            self.actions.push(action);
        }
    }
}

/// A validated, connected accessibility tree.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccessibilityTree {
    root: u64,
    focus: u64,
    nodes: Vec<AccessibilityNode>,
}

impl AccessibilityTree {
    /// Validates a tree assembled from its complete node set.
    pub fn from_nodes(root: u64, focus: u64, nodes: Vec<AccessibilityNode>) -> io::Result<Self> {
        let tree = Self { root, focus, nodes };
        tree.validate()?;
        Ok(tree)
    }

    pub(super) fn validate(&self) -> io::Result<()> {
        if self.nodes.is_empty() || self.nodes.len() > MAX_ACCESSIBILITY_NODES {
            return Err(limit_error("accessibility node count is outside its bound"));
        }
        validate_id(self.root)?;
        validate_id(self.focus)?;
        let mut by_id = HashMap::with_capacity(self.nodes.len());
        for node in &self.nodes {
            validate_id(node.id)?;
            validate_text(&node.name)?;
            if let Some(description) = &node.description {
                validate_text(description)?;
            }
            if let Some(value) = &node.value {
                validate_text(value)?;
            }
            if (node.hidden || node.disabled) && (!node.actions.is_empty() || node.focusable) {
                return Err(invalid_error(
                    "hidden or disabled accessibility nodes cannot expose focus or actions",
                ));
            }
            if by_id.insert(node.id, node).is_some() {
                return Err(invalid_error(
                    "accessibility node identities must be unique",
                ));
            }
        }
        let root_node = by_id
            .get(&self.root)
            .ok_or_else(|| invalid_error("accessibility root is missing"))?;
        if self.focus != self.root {
            let focus_node = by_id
                .get(&self.focus)
                .ok_or_else(|| invalid_error("accessibility focus node is missing"))?;
            if focus_node.hidden || focus_node.disabled || !focus_node.focusable {
                return Err(invalid_error(
                    "accessibility focus must identify an enabled focusable node",
                ));
            }
        }

        let mut parents = HashSet::with_capacity(self.nodes.len());
        let mut visited = HashSet::with_capacity(self.nodes.len());
        let mut pending = vec![self.root];
        while let Some(id) = pending.pop() {
            if !visited.insert(id) {
                return Err(invalid_error("accessibility tree contains a cycle"));
            }
            let node = by_id
                .get(&id)
                .ok_or_else(|| invalid_error("accessibility child identity is missing"))?;
            for child in &node.children {
                if !parents.insert(*child) {
                    return Err(invalid_error(
                        "accessibility nodes must have one parent in the tree",
                    ));
                }
                pending.push(*child);
            }
        }
        if !parents.contains(&self.focus) && self.focus != self.root {
            return Err(invalid_error(
                "accessibility focus is outside the root tree",
            ));
        }
        if visited.len() != self.nodes.len() {
            return Err(invalid_error(
                "accessibility tree contains an unreachable node",
            ));
        }
        if parents.contains(&self.root) || root_node.hidden {
            return Err(invalid_error(
                "accessibility root cannot be hidden or parented",
            ));
        }
        Ok(())
    }

    pub(super) fn to_accesskit(&self) -> TreeUpdate {
        let nodes = self
            .nodes
            .iter()
            .map(|source| {
                let mut node = Node::new(accesskit_role(source.role));
                if !source.name.is_empty() {
                    node.set_label(source.name.clone());
                }
                if let Some(description) = &source.description {
                    node.set_description(description.clone());
                }
                if let Some(value) = &source.value {
                    node.set_value(value.clone());
                }
                if let Some(shortcut) = &source.keyboard_shortcut {
                    node.set_keyboard_shortcut(shortcut.clone());
                }
                if !source.children.is_empty() {
                    node.set_children(
                        source
                            .children
                            .iter()
                            .copied()
                            .map(NodeId::from)
                            .collect::<Vec<_>>(),
                    );
                }
                if source.hidden {
                    node.set_hidden();
                }
                if source.disabled {
                    node.set_disabled();
                }
                if source.focusable {
                    node.add_action(Action::Focus);
                }
                if let Some(expanded) = source.expanded {
                    node.set_expanded(expanded);
                }
                if let Some(selected) = source.selected {
                    node.set_selected(selected);
                }
                if let Some(checked) = source.checked {
                    node.set_toggled(checked.into());
                }
                for action in &source.actions {
                    node.add_action(accesskit_action(*action));
                }
                (NodeId::from(source.id), node)
            })
            .collect();
        TreeUpdate {
            nodes,
            tree: Some(TreeInfo::new(NodeId::from(self.root))),
            tree_id: TreeId::ROOT,
            focus: NodeId::from(self.focus),
        }
    }
}

fn accesskit_role(role: AccessibilityRole) -> Role {
    match role {
        AccessibilityRole::Application => Role::Application,
        AccessibilityRole::Main => Role::Main,
        AccessibilityRole::Navigation => Role::Navigation,
        AccessibilityRole::Complementary => Role::Complementary,
        AccessibilityRole::Group => Role::Group,
        AccessibilityRole::Toolbar => Role::Toolbar,
        AccessibilityRole::Menu => Role::Menu,
        AccessibilityRole::MenuItem => Role::MenuItem,
        AccessibilityRole::Button => Role::Button,
        AccessibilityRole::Text => Role::Label,
        AccessibilityRole::TextInput => Role::TextInput,
        AccessibilityRole::CheckBox => Role::CheckBox,
        AccessibilityRole::Radio => Role::RadioButton,
        AccessibilityRole::Slider => Role::Slider,
        AccessibilityRole::ComboBox => Role::ComboBox,
        AccessibilityRole::Dialog => Role::Dialog,
        AccessibilityRole::Status => Role::Status,
        AccessibilityRole::Table => Role::Table,
    }
}

pub(super) fn accesskit_action(action: AccessibilityAction) -> Action {
    match action {
        AccessibilityAction::Activate | AccessibilityAction::Toggle => Action::Click,
        AccessibilityAction::Focus => Action::Focus,
        AccessibilityAction::SetValue => Action::ReplaceSelectedText,
        AccessibilityAction::AdjustValue => Action::Increment,
        AccessibilityAction::Open => Action::Expand,
    }
}

fn validate_id(id: u64) -> io::Result<()> {
    if id == 0 {
        return Err(invalid_error(
            "accessibility node identities must be nonzero",
        ));
    }
    Ok(())
}

fn validate_text(value: &str) -> io::Result<()> {
    if value.len() > MAX_ACCESSIBILITY_TEXT_BYTES {
        return Err(limit_error("accessibility text exceeds its byte bound"));
    }
    Ok(())
}

fn invalid_error(message: &'static str) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidInput, message)
}

fn limit_error(message: &'static str) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidInput, message)
}