waft_embedder/semantics.rs
1//! Flutter counterpart: `dart:ui`'s `semantics.dart`: the value types the semantics widgets
2//! name (`SemanticsAction`, `SemanticsRole`, `SemanticsInputType`, `SemanticsHitTestBehavior`,
3//! `SemanticsValidationResult`, and the `StringAttribute`s).
4//!
5//! `SemanticsFlag`, `SemanticsFlags`, `CheckedState`, `Tristate`, `SemanticsUpdateBuilder` and
6//! `SemanticsUpdate` wait with the semantics tree, which is what reads them.
7
8use std::any::Any;
9use std::fmt::{self, Debug};
10use std::rc::Rc;
11
12use crate::{Locale, TextRange};
13
14/// The possible actions that can be conveyed from the operating system
15/// accessibility APIs to a semantics node.
16///
17/// Dart's class with one constant per action: `index` is the action's bit.
18#[derive(Clone, Copy, PartialEq, Eq, Hash)]
19pub struct SemanticsAction {
20 /// The numerical value for this action.
21 ///
22 /// Each action has one bit set in this bit field.
23 pub index: i32,
24
25 /// A human-readable name for this action, used for debugging purposes.
26 pub name: &'static str,
27}
28
29impl SemanticsAction {
30 const fn new(index: i32, name: &'static str) -> SemanticsAction {
31 SemanticsAction { index, name }
32 }
33
34 const K_TAP_INDEX: i32 = 1 << 0;
35 const K_LONG_PRESS_INDEX: i32 = 1 << 1;
36 const K_SCROLL_LEFT_INDEX: i32 = 1 << 2;
37 const K_SCROLL_RIGHT_INDEX: i32 = 1 << 3;
38 const K_SCROLL_UP_INDEX: i32 = 1 << 4;
39 const K_SCROLL_DOWN_INDEX: i32 = 1 << 5;
40 const K_INCREASE_INDEX: i32 = 1 << 6;
41 const K_DECREASE_INDEX: i32 = 1 << 7;
42 const K_SHOW_ON_SCREEN_INDEX: i32 = 1 << 8;
43 const K_MOVE_CURSOR_FORWARD_BY_CHARACTER_INDEX: i32 = 1 << 9;
44 const K_MOVE_CURSOR_BACKWARD_BY_CHARACTER_INDEX: i32 = 1 << 10;
45 const K_SET_SELECTION_INDEX: i32 = 1 << 11;
46 const K_COPY_INDEX: i32 = 1 << 12;
47 const K_CUT_INDEX: i32 = 1 << 13;
48 const K_PASTE_INDEX: i32 = 1 << 14;
49 const K_DID_GAIN_ACCESSIBILITY_FOCUS_INDEX: i32 = 1 << 15;
50 const K_DID_LOSE_ACCESSIBILITY_FOCUS_INDEX: i32 = 1 << 16;
51 const K_CUSTOM_ACTION_INDEX: i32 = 1 << 17;
52 const K_DISMISS_INDEX: i32 = 1 << 18;
53 const K_MOVE_CURSOR_FORWARD_BY_WORD_INDEX: i32 = 1 << 19;
54 const K_MOVE_CURSOR_BACKWARD_BY_WORD_INDEX: i32 = 1 << 20;
55 const K_SET_TEXT_INDEX: i32 = 1 << 21;
56 const K_FOCUS_INDEX: i32 = 1 << 22;
57 const K_SCROLL_TO_OFFSET_INDEX: i32 = 1 << 23;
58 const K_EXPAND_INDEX: i32 = 1 << 24;
59 const K_COLLAPSE_INDEX: i32 = 1 << 25;
60
61 /// The equivalent of a user briefly tapping the screen with the finger
62 /// without moving it.
63 pub const TAP: SemanticsAction = SemanticsAction::new(Self::K_TAP_INDEX, "tap");
64
65 /// The equivalent of a user pressing and holding the screen with the finger
66 /// for a few seconds without moving it.
67 pub const LONG_PRESS: SemanticsAction =
68 SemanticsAction::new(Self::K_LONG_PRESS_INDEX, "longPress");
69
70 /// The equivalent of a user moving their finger across the screen from right
71 /// to left.
72 pub const SCROLL_LEFT: SemanticsAction =
73 SemanticsAction::new(Self::K_SCROLL_LEFT_INDEX, "scrollLeft");
74
75 /// The equivalent of a user moving their finger across the screen from left
76 /// to right.
77 pub const SCROLL_RIGHT: SemanticsAction =
78 SemanticsAction::new(Self::K_SCROLL_RIGHT_INDEX, "scrollRight");
79
80 /// The equivalent of a user moving their finger across the screen from
81 /// bottom to top.
82 pub const SCROLL_UP: SemanticsAction =
83 SemanticsAction::new(Self::K_SCROLL_UP_INDEX, "scrollUp");
84
85 /// The equivalent of a user moving their finger across the screen from top
86 /// to bottom.
87 pub const SCROLL_DOWN: SemanticsAction =
88 SemanticsAction::new(Self::K_SCROLL_DOWN_INDEX, "scrollDown");
89
90 /// A request to scroll the scrollable container to a given scroll offset.
91 pub const SCROLL_TO_OFFSET: SemanticsAction =
92 SemanticsAction::new(Self::K_SCROLL_TO_OFFSET_INDEX, "scrollToOffset");
93
94 /// A request to increase the value represented by the semantics node.
95 pub const INCREASE: SemanticsAction = SemanticsAction::new(Self::K_INCREASE_INDEX, "increase");
96
97 /// A request to decrease the value represented by the semantics node.
98 pub const DECREASE: SemanticsAction = SemanticsAction::new(Self::K_DECREASE_INDEX, "decrease");
99
100 /// A request to fully show the semantics node on screen.
101 pub const SHOW_ON_SCREEN: SemanticsAction =
102 SemanticsAction::new(Self::K_SHOW_ON_SCREEN_INDEX, "showOnScreen");
103
104 /// Move the cursor forward by one character.
105 pub const MOVE_CURSOR_FORWARD_BY_CHARACTER: SemanticsAction = SemanticsAction::new(
106 Self::K_MOVE_CURSOR_FORWARD_BY_CHARACTER_INDEX,
107 "moveCursorForwardByCharacter",
108 );
109
110 /// Move the cursor backward by one character.
111 pub const MOVE_CURSOR_BACKWARD_BY_CHARACTER: SemanticsAction = SemanticsAction::new(
112 Self::K_MOVE_CURSOR_BACKWARD_BY_CHARACTER_INDEX,
113 "moveCursorBackwardByCharacter",
114 );
115
116 /// Replaces the current text in the text field.
117 pub const SET_TEXT: SemanticsAction = SemanticsAction::new(Self::K_SET_TEXT_INDEX, "setText");
118
119 /// Set the text selection to the given range.
120 pub const SET_SELECTION: SemanticsAction =
121 SemanticsAction::new(Self::K_SET_SELECTION_INDEX, "setSelection");
122
123 /// Copy the current selection to the clipboard.
124 pub const COPY: SemanticsAction = SemanticsAction::new(Self::K_COPY_INDEX, "copy");
125
126 /// Cut the current selection and place it in the clipboard.
127 pub const CUT: SemanticsAction = SemanticsAction::new(Self::K_CUT_INDEX, "cut");
128
129 /// Paste the current content of the clipboard.
130 pub const PASTE: SemanticsAction = SemanticsAction::new(Self::K_PASTE_INDEX, "paste");
131
132 /// Indicates that the node has gained accessibility focus.
133 pub const DID_GAIN_ACCESSIBILITY_FOCUS: SemanticsAction = SemanticsAction::new(
134 Self::K_DID_GAIN_ACCESSIBILITY_FOCUS_INDEX,
135 "didGainAccessibilityFocus",
136 );
137
138 /// Indicates that the node has lost accessibility focus.
139 pub const DID_LOSE_ACCESSIBILITY_FOCUS: SemanticsAction = SemanticsAction::new(
140 Self::K_DID_LOSE_ACCESSIBILITY_FOCUS_INDEX,
141 "didLoseAccessibilityFocus",
142 );
143
144 /// Indicates that the user has invoked a custom accessibility action.
145 pub const CUSTOM_ACTION: SemanticsAction =
146 SemanticsAction::new(Self::K_CUSTOM_ACTION_INDEX, "customAction");
147
148 /// A request that the node should be dismissed.
149 pub const DISMISS: SemanticsAction = SemanticsAction::new(Self::K_DISMISS_INDEX, "dismiss");
150
151 /// Move the cursor forward by one word.
152 pub const MOVE_CURSOR_FORWARD_BY_WORD: SemanticsAction = SemanticsAction::new(
153 Self::K_MOVE_CURSOR_FORWARD_BY_WORD_INDEX,
154 "moveCursorForwardByWord",
155 );
156
157 /// Move the cursor backward by one word.
158 pub const MOVE_CURSOR_BACKWARD_BY_WORD: SemanticsAction = SemanticsAction::new(
159 Self::K_MOVE_CURSOR_BACKWARD_BY_WORD_INDEX,
160 "moveCursorBackwardByWord",
161 );
162
163 /// Move the input focus to the respective widget.
164 pub const FOCUS: SemanticsAction = SemanticsAction::new(Self::K_FOCUS_INDEX, "focus");
165
166 /// A request that the node should be expanded.
167 pub const EXPAND: SemanticsAction = SemanticsAction::new(Self::K_EXPAND_INDEX, "expand");
168
169 /// A request that the node should be collapsed.
170 pub const COLLAPSE: SemanticsAction = SemanticsAction::new(Self::K_COLLAPSE_INDEX, "collapse");
171
172 /// Dart's `_kActionById`, in its order.
173 const K_ACTION_BY_ID: [SemanticsAction; 26] = [
174 Self::TAP,
175 Self::LONG_PRESS,
176 Self::SCROLL_LEFT,
177 Self::SCROLL_RIGHT,
178 Self::SCROLL_UP,
179 Self::SCROLL_DOWN,
180 Self::SCROLL_TO_OFFSET,
181 Self::INCREASE,
182 Self::DECREASE,
183 Self::SHOW_ON_SCREEN,
184 Self::MOVE_CURSOR_FORWARD_BY_CHARACTER,
185 Self::MOVE_CURSOR_BACKWARD_BY_CHARACTER,
186 Self::SET_SELECTION,
187 Self::COPY,
188 Self::CUT,
189 Self::PASTE,
190 Self::DID_GAIN_ACCESSIBILITY_FOCUS,
191 Self::DID_LOSE_ACCESSIBILITY_FOCUS,
192 Self::CUSTOM_ACTION,
193 Self::DISMISS,
194 Self::MOVE_CURSOR_FORWARD_BY_WORD,
195 Self::MOVE_CURSOR_BACKWARD_BY_WORD,
196 Self::SET_TEXT,
197 Self::FOCUS,
198 Self::EXPAND,
199 Self::COLLAPSE,
200 ];
201
202 /// Every action, in Dart's `_kActionById` order.
203 pub fn values() -> Vec<SemanticsAction> {
204 Self::K_ACTION_BY_ID.to_vec()
205 }
206
207 /// The action whose bit is `index`, if there is one.
208 pub fn from_index(index: i32) -> Option<SemanticsAction> {
209 Self::K_ACTION_BY_ID
210 .into_iter()
211 .find(|action| action.index == index)
212 }
213}
214
215impl Debug for SemanticsAction {
216 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217 write!(f, "SemanticsAction.{}", self.name)
218 }
219}
220
221/// An enum to describe the role for a semantics node.
222///
223/// The roles are translated into native accessibility roles in each platform.
224#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
225pub enum SemanticsRole {
226 /// Does not represent any role.
227 None,
228 /// A tab button.
229 Tab,
230 /// Contains tab buttons.
231 TabBar,
232 /// The main display for a tab.
233 TabPanel,
234 /// A pop up dialog.
235 Dialog,
236 /// An alert dialog.
237 AlertDialog,
238 /// A table structure containing data arranged in rows and columns.
239 Table,
240 /// A cell in a [`Table`](Self::Table) that does not contain column or row header
241 /// information.
242 Cell,
243 /// A row of [`Cell`](Self::Cell)s or [`ColumnHeader`](Self::ColumnHeader)s in a
244 /// [`Table`](Self::Table).
245 Row,
246 /// A cell in a [`Table`](Self::Table) contains header information for a column.
247 ColumnHeader,
248 /// A control used for dragging across content.
249 DragHandle,
250 /// A control to cycle through content on tap.
251 SpinButton,
252 /// A input field with a dropdown list box attached.
253 ComboBox,
254 /// A presentation of [`Menu`](Self::Menu) that usually remains visible and is usually
255 /// presented horizontally.
256 MenuBar,
257 /// A permanently visible list of controls or a widget that can be made to open and close.
258 Menu,
259 /// An item in a dropdown created by [`Menu`](Self::Menu) or [`MenuBar`](Self::MenuBar).
260 MenuItem,
261 /// An item with a checkbox in a dropdown created by [`Menu`](Self::Menu) or
262 /// [`MenuBar`](Self::MenuBar).
263 MenuItemCheckbox,
264 /// An item with a radio button in a dropdown created by [`Menu`](Self::Menu) or
265 /// [`MenuBar`](Self::MenuBar).
266 MenuItemRadio,
267 /// A container to display multiple [`ListItem`](Self::ListItem)s in vertical or horizontal
268 /// layout.
269 List,
270 /// An item in a [`List`](Self::List).
271 ListItem,
272 /// An area that represents a form.
273 Form,
274 /// A pop up displayed when hovering over a component to provide contextual explanation.
275 Tooltip,
276 /// A graphic object that spins to indicate the application is busy.
277 LoadingSpinner,
278 /// A graphic object that shows progress with a numeric number.
279 ProgressBar,
280 /// A keyboard shortcut field that allows the user to enter a combination or sequence of
281 /// keystrokes.
282 HotKey,
283 /// A group of radio buttons.
284 RadioGroup,
285 /// A component to provide advisory information that is not important to justify an
286 /// [`Alert`](Self::Alert).
287 Status,
288 /// A component to provide important and usually time-sensitive information.
289 Alert,
290 /// A supporting section that relates to the main content.
291 Complementary,
292 /// A section for a footer, containing identifying information such as copyright
293 /// information, navigation links and privacy statements.
294 ContentInfo,
295 /// The primary content of a document.
296 Main,
297 /// A region of a web page that contains navigation links.
298 Navigation,
299 /// A section of content sufficiently important but cannot be described by one of the other
300 /// landmark roles, such as main, contentinfo, complementary, or navigation.
301 Region,
302}
303
304/// Describe the type of data for an input field.
305///
306/// This is typically used to complement text fields.
307#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
308pub enum SemanticsInputType {
309 /// The default for non text field.
310 None,
311 /// Describes a generic text field.
312 Text,
313 /// Describes a url text field.
314 Url,
315 /// Describes a text field for phone input.
316 Phone,
317 /// Describes a text field that act as a search box.
318 Search,
319 /// Describes a text field for email input.
320 Email,
321}
322
323/// How a semantics node handles pointer events for the platform's accessibility layer.
324#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
325pub enum SemanticsHitTestBehavior {
326 /// Defer to the platform's default hit test behavior inference.
327 ///
328 /// When set to defer, the platform will infer the appropriate behavior
329 /// based on the semantic node's properties such as interactive behaviors,
330 /// route scoping, etc.
331 ///
332 /// This is the default value and provides backward compatibility.
333 Defer,
334
335 /// The semantic element is opaque to hit testing, consuming any pointer
336 /// events within its bounds and preventing them from reaching elements
337 /// behind it in Z-order (siblings and ancestors).
338 ///
339 /// Children of this node can still receive pointer events normally.
340 Opaque,
341
342 /// The semantic element is transparent to hit testing.
343 ///
344 /// Transparent nodes do not receive hit test events and allow events to pass
345 /// through to elements behind them.
346 Transparent,
347}
348
349/// The validation result of a form field.
350///
351/// The type, shape, and correctness of the value is specific to the kind of
352/// form field used.
353#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
354pub enum SemanticsValidationResult {
355 /// The node has no validation information attached to it.
356 ///
357 /// This is the default value.
358 #[default]
359 None,
360
361 /// The entered value is valid, and no error should be displayed to the user.
362 Valid,
363
364 /// The entered value is invalid, and an error message should be communicated
365 /// to the user.
366 Invalid,
367}
368
369/// An abstract interface for string attributes that affects how assistive
370/// technologies, e.g. VoiceOver or TalkBack, treat the text.
371///
372/// Dart's `abstract base class StringAttribute`, held as a [`StringAttributeRef`]. It does
373/// not override `==`: two attributes are equal only when they are the same object.
374pub trait StringAttribute: Debug + Any {
375 /// The range of the text to which this attribute applies.
376 fn range(&self) -> TextRange;
377
378 /// Creates a new attribute with all properties copied except for range, which
379 /// is updated to the specified value.
380 ///
381 /// For example, the [`LocaleStringAttribute`] specifies a [`Locale`] for its
382 /// range of characters. Copying it will result in a new
383 /// [`LocaleStringAttribute`] that has the same locale but an updated
384 /// [`TextRange`].
385 fn copy(&self, range: TextRange) -> StringAttributeRef;
386}
387
388/// A shared [`StringAttribute`]; Dart's identity is the `Rc`'s.
389pub type StringAttributeRef = Rc<dyn StringAttribute>;
390
391/// A string attribute that causes the assistive technologies, e.g. VoiceOver,
392/// to spell out the string character by character.
393pub struct SpellOutStringAttribute {
394 range: TextRange,
395}
396
397impl SpellOutStringAttribute {
398 /// Creates a string attribute that denotes the text in `range` must be
399 /// spell out when the assistive technologies announce the string.
400 pub fn new(range: TextRange) -> Rc<SpellOutStringAttribute> {
401 Rc::new(SpellOutStringAttribute { range })
402 }
403}
404
405impl StringAttribute for SpellOutStringAttribute {
406 fn range(&self) -> TextRange {
407 self.range
408 }
409
410 fn copy(&self, range: TextRange) -> StringAttributeRef {
411 SpellOutStringAttribute::new(range)
412 }
413}
414
415impl Debug for SpellOutStringAttribute {
416 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
417 write!(f, "SpellOutStringAttribute({:?})", self.range)
418 }
419}
420
421/// A string attribute that causes the assistive technologies, e.g. VoiceOver,
422/// to treat string as a certain language.
423pub struct LocaleStringAttribute {
424 range: TextRange,
425
426 /// The language of this attribute.
427 pub locale: Locale,
428}
429
430impl LocaleStringAttribute {
431 /// Creates a string attribute that denotes the text in `range` must be
432 /// treated as the language specified by the `locale` when the assistive
433 /// technologies announce the string.
434 pub fn new(range: TextRange, locale: Locale) -> Rc<LocaleStringAttribute> {
435 Rc::new(LocaleStringAttribute { range, locale })
436 }
437}
438
439impl StringAttribute for LocaleStringAttribute {
440 fn range(&self) -> TextRange {
441 self.range
442 }
443
444 fn copy(&self, range: TextRange) -> StringAttributeRef {
445 LocaleStringAttribute::new(range, self.locale.clone())
446 }
447}
448
449impl Debug for LocaleStringAttribute {
450 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
451 write!(
452 f,
453 "LocaleStringAttribute({:?}, {})",
454 self.range,
455 self.locale.to_language_tag()
456 )
457 }
458}
459
460#[cfg(test)]
461mod tests {
462 use super::*;
463
464 #[test]
465 fn an_action_is_found_by_its_bit() {
466 assert_eq!(
467 SemanticsAction::from_index(1 << 17),
468 Some(SemanticsAction::CUSTOM_ACTION)
469 );
470 assert_eq!(SemanticsAction::from_index(1 << 26), None);
471 assert_eq!(SemanticsAction::values().len(), 26);
472 }
473
474 #[test]
475 fn copying_a_locale_attribute_keeps_its_locale_and_takes_the_new_range() {
476 let attribute = LocaleStringAttribute::new(TextRange::new(0, 2), Locale::new("es"));
477 let copy = attribute.copy(TextRange::new(3, 5));
478 assert_eq!(copy.range(), TextRange::new(3, 5));
479 let copy = (copy.as_ref() as &dyn Any)
480 .downcast_ref::<LocaleStringAttribute>()
481 .unwrap();
482 assert_eq!(copy.locale, Locale::new("es"));
483 }
484}