1use core::fmt;
12use core::str::FromStr;
13
14use crate::suggest;
15
16mod sealed {
17 pub trait Sealed {}
18}
19
20pub trait RoleKind: sealed::Sealed + Copy + Default + fmt::Debug + Send + Sync + 'static {
22 const ROLE: ::core::option::Option<Role>;
24}
25
26#[diagnostic::on_unimplemented(
28 message = "`{Self}` is not a concrete role",
29 note = "use a role type such as `role::Button`"
30)]
31pub trait RoleType: RoleKind {
32 const ROLE_VALUE: Role;
34}
35
36#[diagnostic::on_unimplemented(
38 message = "this already has role `{Self}`",
39 note = "call `.any_role()` first if you really mean to change it"
40)]
41pub trait Untyped: RoleKind {}
42
43#[diagnostic::on_unimplemented(
45 message = "`{Self}` cannot be checked",
46 label = "this role has no checked state",
47 note = "narrow an untyped handle with `.into_role::<role::CheckBox>()`, or use a role that implements `Checkable`"
48)]
49pub trait Checkable: RoleType {}
50
51#[diagnostic::on_unimplemented(
53 message = "`{Self}` cannot be edited",
54 label = "this role takes no typed text",
55 note = "narrow an untyped handle with `.into_role::<role::TextBox>()`, or use a role that implements `Editable`"
56)]
57pub trait Editable: HasValue {}
58
59#[diagnostic::on_unimplemented(
61 message = "`{Self}` has no options to select",
62 label = "this role owns no options",
63 note = "narrow an untyped handle with `.into_role::<role::ComboBox>()`, or use a role that implements `Selectable`"
64)]
65pub trait Selectable: RoleType {}
66
67#[diagnostic::on_unimplemented(
69 message = "`{Self}` cannot be expanded",
70 label = "this role has no expanded state",
71 note = "narrow an untyped handle with `.into_role::<role::TreeItem>()`, or use a role that implements `Expandable`"
72)]
73pub trait Expandable: RoleType {}
74
75#[diagnostic::on_unimplemented(
77 message = "`{Self}` has no value range to set",
78 label = "this role has no numeric range",
79 note = "narrow an untyped handle with `.into_role::<role::Slider>()`, or use a role that implements `RangeValue`"
80)]
81pub trait RangeValue: HasValue {}
82
83#[diagnostic::on_unimplemented(
85 message = "`{Self}` has no pressed state",
86 label = "only toggle buttons are pressed or not",
87 note = "narrow an untyped handle with `.into_role::<role::ToggleButton>()`, or use a role that implements `Pressable`"
88)]
89pub trait Pressable: RoleType {}
90
91#[diagnostic::on_unimplemented(
93 message = "`{Self}` has no value",
94 label = "this role reports no value",
95 note = "narrow an untyped handle with `.into_role::<role::TextBox>()`, or use a role that implements `HasValue`"
96)]
97pub trait HasValue: RoleType {}
98
99#[diagnostic::on_unimplemented(
101 message = "`{Self}` cannot be selected",
102 label = "this role is not a selectable item",
103 note = "narrow an untyped handle with `.into_role::<role::ListOption>()`, or use a role that implements `SelectableItem`"
104)]
105pub trait SelectableItem: RoleType {}
106
107#[diagnostic::on_unimplemented(
109 message = "`{Self}` has no level",
110 label = "this role has no nesting level",
111 note = "narrow an untyped handle with `.into_role::<role::Heading>()`, or use a role that implements `Leveled`"
112)]
113pub trait Leveled: RoleType {}
114
115#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
117#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
118pub struct AnyRole;
119
120impl sealed::Sealed for AnyRole {}
121
122impl RoleKind for AnyRole {
123 const ROLE: ::core::option::Option<Role> = ::core::option::Option::None;
124}
125
126impl Untyped for AnyRole {}
127
128#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
130pub struct Capabilities(u16);
131
132impl Capabilities {
133 pub const NONE: Self = Self(0);
135 pub const CHECKABLE: Self = Self(1);
137 pub const EDITABLE: Self = Self(1 << 1);
139 pub const SELECTABLE: Self = Self(1 << 2);
141 pub const EXPANDABLE: Self = Self(1 << 3);
143 pub const RANGE_VALUE: Self = Self(1 << 4);
145 pub const PRESSABLE: Self = Self(1 << 5);
147 pub const HAS_VALUE: Self = Self(1 << 6);
149 pub const SELECTABLE_ITEM: Self = Self(1 << 7);
151 pub const LEVELED: Self = Self(1 << 8);
153
154 pub const NAMED: &'static [(Self, &'static str)] = &[
156 (Self::CHECKABLE, "Checkable"),
157 (Self::EDITABLE, "Editable"),
158 (Self::SELECTABLE, "Selectable"),
159 (Self::EXPANDABLE, "Expandable"),
160 (Self::RANGE_VALUE, "RangeValue"),
161 (Self::PRESSABLE, "Pressable"),
162 (Self::HAS_VALUE, "HasValue"),
163 (Self::SELECTABLE_ITEM, "SelectableItem"),
164 (Self::LEVELED, "Leveled"),
165 ];
166
167 #[must_use]
169 pub const fn contains(self, other: Self) -> bool {
170 self.0 & other.0 == other.0
171 }
172
173 #[must_use]
175 pub const fn is_empty(self) -> bool {
176 self.0 == 0
177 }
178
179 #[must_use]
181 pub const fn union(self, other: Self) -> Self {
182 Self(self.0 | other.0)
183 }
184
185 pub fn names(self) -> impl Iterator<Item = &'static str> {
187 Self::NAMED
188 .iter()
189 .filter(move |(capability, _)| self.contains(*capability))
190 .map(|(_, name)| *name)
191 }
192}
193
194impl core::ops::BitOr for Capabilities {
195 type Output = Self;
196
197 fn bitor(self, other: Self) -> Self {
198 self.union(other)
199 }
200}
201
202impl core::ops::BitOrAssign for Capabilities {
203 fn bitor_assign(&mut self, other: Self) {
204 *self = self.union(other);
205 }
206}
207
208impl fmt::Debug for Capabilities {
209 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210 f.debug_set().entries(self.names()).finish()
211 }
212}
213
214#[derive(Debug, Clone, Copy, PartialEq, Eq)]
216pub struct RoleMismatch {
217 pub expected: Role,
219 pub found: Role,
221}
222
223impl fmt::Display for RoleMismatch {
224 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225 write!(
226 f,
227 "expected role `{}`, found `{}`",
228 self.expected, self.found
229 )
230 }
231}
232
233impl std::error::Error for RoleMismatch {}
234
235#[derive(Debug, Clone, PartialEq, Eq)]
237pub struct ParseRoleError {
238 name: String,
239 suggestions: Vec<&'static str>,
240}
241
242impl ParseRoleError {
243 #[must_use]
245 pub fn name(&self) -> &str {
246 &self.name
247 }
248
249 #[must_use]
251 pub fn suggestions(&self) -> &[&'static str] {
252 &self.suggestions
253 }
254}
255
256impl fmt::Display for ParseRoleError {
257 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258 write!(
259 f,
260 "unknown role `{}`{}",
261 self.name,
262 suggest::did_you_mean(&self.suggestions)
263 )
264 }
265}
266
267impl std::error::Error for ParseRoleError {}
268
269impl<R: RoleType> From<R> for Role {
270 fn from(_: R) -> Role {
271 R::ROLE_VALUE
272 }
273}
274
275macro_rules! capability {
276 (Checkable) => {
277 Capabilities::CHECKABLE
278 };
279 (Editable) => {
280 Capabilities::EDITABLE
281 };
282 (Selectable) => {
283 Capabilities::SELECTABLE
284 };
285 (Expandable) => {
286 Capabilities::EXPANDABLE
287 };
288 (RangeValue) => {
289 Capabilities::RANGE_VALUE
290 };
291 (Pressable) => {
292 Capabilities::PRESSABLE
293 };
294 (HasValue) => {
295 Capabilities::HAS_VALUE
296 };
297 (SelectableItem) => {
298 Capabilities::SELECTABLE_ITEM
299 };
300 (Leveled) => {
301 Capabilities::LEVELED
302 };
303}
304
305macro_rules! roles {
306 ($(
307 $(#[doc = $doc:literal])+
308 $variant:ident {
309 selector: $selector:literal,
310 aria: $aria:expr,
311 accesskit: $accesskit:literal,
312 click_target: $click:literal,
313 capabilities: [$($capability:ident),*] $(,)?
314 }
315 )+) => {
316 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
321 #[non_exhaustive]
322 pub enum Role {
323 $(
324 $(#[doc = $doc])+
325 $variant,
326 )+
327 }
328
329 impl Role {
330 pub const ALL: &'static [Role] = &[$(Role::$variant),+];
332
333 #[must_use]
335 pub const fn selector_name(self) -> &'static str {
336 match self {
337 $(Role::$variant => $selector,)+
338 }
339 }
340
341 #[must_use]
343 pub const fn aria_name(self) -> ::core::option::Option<&'static str> {
344 match self {
345 $(Role::$variant => $aria,)+
346 }
347 }
348
349 #[must_use]
352 pub const fn accesskit_name(self) -> &'static str {
353 match self {
354 $(Role::$variant => $accesskit,)+
355 }
356 }
357
358 #[must_use]
360 pub const fn type_name(self) -> &'static str {
361 match self {
362 $(Role::$variant => stringify!($variant),)+
363 }
364 }
365
366 #[must_use]
368 pub const fn capabilities(self) -> Capabilities {
369 match self {
370 $(Role::$variant => Capabilities::NONE $(.union(capability!($capability)))*,)+
371 }
372 }
373
374 #[must_use]
376 pub const fn is_click_target(self) -> bool {
377 match self {
378 $(Role::$variant => $click,)+
379 }
380 }
381 }
382
383 $(
384 #[doc = concat!(
385 "The role type for [`Role::", stringify!($variant),
386 "`], selector name `", $selector, "`."
387 )]
388 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
389 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
390 pub struct $variant;
391
392 impl sealed::Sealed for $variant {}
393
394 impl RoleKind for $variant {
395 const ROLE: ::core::option::Option<Role> =
396 ::core::option::Option::Some(Role::$variant);
397 }
398
399 impl RoleType for $variant {
400 const ROLE_VALUE: Role = Role::$variant;
401 }
402
403 $(impl $capability for $variant {})*
404
405 impl ::core::convert::TryFrom<Role> for $variant {
406 type Error = RoleMismatch;
407
408 fn try_from(role: Role) -> ::core::result::Result<Self, RoleMismatch> {
409 if role == Role::$variant {
410 return ::core::result::Result::Ok($variant);
411 }
412 ::core::result::Result::Err(RoleMismatch {
413 expected: Role::$variant,
414 found: role,
415 })
416 }
417 }
418 )+
419 };
420}
421
422roles! {
423 Window { selector: "window", aria: None, accesskit: "Window", click_target: false, capabilities: [] }
425 Generic { selector: "generic", aria: Some("generic"), accesskit: "GenericContainer", click_target: false, capabilities: [] }
427 Group { selector: "group", aria: Some("group"), accesskit: "Group", click_target: false, capabilities: [] }
429 Region { selector: "region", aria: Some("region"), accesskit: "Region", click_target: false, capabilities: [] }
431 Navigation { selector: "navigation", aria: Some("navigation"), accesskit: "Navigation", click_target: false, capabilities: [] }
433 Toolbar { selector: "toolbar", aria: Some("toolbar"), accesskit: "Toolbar", click_target: false, capabilities: [] }
435 Text { selector: "text", aria: None, accesskit: "Label", click_target: false, capabilities: [] }
437 Paragraph { selector: "paragraph", aria: Some("paragraph"), accesskit: "Paragraph", click_target: false, capabilities: [] }
439 Heading { selector: "heading", aria: Some("heading"), accesskit: "Heading", click_target: false, capabilities: [Leveled] }
441 Image { selector: "img", aria: Some("img"), accesskit: "Image", click_target: false, capabilities: [] }
443 Link { selector: "link", aria: Some("link"), accesskit: "Link", click_target: true, capabilities: [] }
445 Button { selector: "button", aria: Some("button"), accesskit: "Button", click_target: true, capabilities: [Expandable] }
447 ToggleButton { selector: "togglebutton", aria: Some("button"), accesskit: "ToggleButton", click_target: true, capabilities: [Pressable] }
449 CheckBox { selector: "checkbox", aria: Some("checkbox"), accesskit: "CheckBox", click_target: false, capabilities: [Checkable] }
451 RadioButton { selector: "radio", aria: Some("radio"), accesskit: "RadioButton", click_target: false, capabilities: [Checkable] }
453 RadioGroup { selector: "radiogroup", aria: Some("radiogroup"), accesskit: "RadioGroup", click_target: false, capabilities: [Selectable] }
455 Switch { selector: "switch", aria: Some("switch"), accesskit: "Switch", click_target: false, capabilities: [Checkable] }
457 TextBox { selector: "textbox", aria: Some("textbox"), accesskit: "TextInput", click_target: false, capabilities: [Editable, HasValue] }
459 SearchBox { selector: "searchbox", aria: Some("searchbox"), accesskit: "SearchInput", click_target: false, capabilities: [Editable, HasValue] }
461 PasswordInput { selector: "password", aria: None, accesskit: "PasswordInput", click_target: false, capabilities: [Editable, HasValue] }
463 ComboBox { selector: "combobox", aria: Some("combobox"), accesskit: "ComboBox", click_target: false, capabilities: [Editable, Selectable, Expandable, HasValue] }
465 ListBox { selector: "listbox", aria: Some("listbox"), accesskit: "ListBox", click_target: false, capabilities: [Selectable] }
467 ListOption { selector: "option", aria: Some("option"), accesskit: "ListBoxOption", click_target: true, capabilities: [SelectableItem] }
469 Slider { selector: "slider", aria: Some("slider"), accesskit: "Slider", click_target: false, capabilities: [RangeValue, HasValue] }
471 SpinButton { selector: "spinbutton", aria: Some("spinbutton"), accesskit: "SpinButton", click_target: false, capabilities: [Editable, RangeValue, HasValue] }
473 ProgressIndicator { selector: "progressbar", aria: Some("progressbar"), accesskit: "ProgressIndicator", click_target: false, capabilities: [HasValue] }
475 ScrollView { selector: "scrollview", aria: None, accesskit: "ScrollView", click_target: false, capabilities: [] }
477 Splitter { selector: "separator", aria: Some("separator"), accesskit: "Splitter", click_target: false, capabilities: [RangeValue, HasValue] }
479 Separator { selector: "separator-static", aria: Some("separator"), accesskit: "GenericContainer", click_target: false, capabilities: [] }
481 Scrim { selector: "scrim", aria: None, accesskit: "GenericContainer", click_target: false, capabilities: [] }
483 List { selector: "list", aria: Some("list"), accesskit: "List", click_target: false, capabilities: [] }
485 ListItem { selector: "listitem", aria: Some("listitem"), accesskit: "ListItem", click_target: true, capabilities: [SelectableItem, Leveled] }
487 Tree { selector: "tree", aria: Some("tree"), accesskit: "Tree", click_target: false, capabilities: [] }
489 TreeItem { selector: "treeitem", aria: Some("treeitem"), accesskit: "TreeItem", click_target: true, capabilities: [Checkable, Expandable, SelectableItem, Leveled] }
491 Table { selector: "table", aria: Some("table"), accesskit: "Table", click_target: false, capabilities: [] }
493 Grid { selector: "grid", aria: Some("grid"), accesskit: "Grid", click_target: false, capabilities: [] }
495 Row { selector: "row", aria: Some("row"), accesskit: "Row", click_target: true, capabilities: [Expandable, SelectableItem, Leveled] }
497 Cell { selector: "cell", aria: Some("cell"), accesskit: "Cell", click_target: true, capabilities: [SelectableItem] }
499 ColumnHeader { selector: "columnheader", aria: Some("columnheader"), accesskit: "ColumnHeader", click_target: true, capabilities: [] }
501 RowHeader { selector: "rowheader", aria: Some("rowheader"), accesskit: "RowHeader", click_target: false, capabilities: [] }
503 TabList { selector: "tablist", aria: Some("tablist"), accesskit: "TabList", click_target: false, capabilities: [Selectable] }
505 Tab { selector: "tab", aria: Some("tab"), accesskit: "Tab", click_target: true, capabilities: [SelectableItem] }
507 TabPanel { selector: "tabpanel", aria: Some("tabpanel"), accesskit: "TabPanel", click_target: false, capabilities: [] }
509 Menu { selector: "menu", aria: Some("menu"), accesskit: "Menu", click_target: false, capabilities: [] }
511 MenuBar { selector: "menubar", aria: Some("menubar"), accesskit: "MenuBar", click_target: false, capabilities: [] }
513 MenuItem { selector: "menuitem", aria: Some("menuitem"), accesskit: "MenuItem", click_target: true, capabilities: [Expandable] }
515 MenuItemCheckBox { selector: "menuitemcheckbox", aria: Some("menuitemcheckbox"), accesskit: "MenuItemCheckBox", click_target: false, capabilities: [Checkable] }
517 MenuItemRadio { selector: "menuitemradio", aria: Some("menuitemradio"), accesskit: "MenuItemRadio", click_target: false, capabilities: [Checkable] }
519 Dialog { selector: "dialog", aria: Some("dialog"), accesskit: "Dialog", click_target: false, capabilities: [] }
521 AlertDialog { selector: "alertdialog", aria: Some("alertdialog"), accesskit: "AlertDialog", click_target: false, capabilities: [] }
523 Tooltip { selector: "tooltip", aria: Some("tooltip"), accesskit: "Tooltip", click_target: false, capabilities: [] }
525 Status { selector: "status", aria: Some("status"), accesskit: "Status", click_target: false, capabilities: [] }
527 Alert { selector: "alert", aria: Some("alert"), accesskit: "Alert", click_target: false, capabilities: [] }
529 Document { selector: "document", aria: Some("document"), accesskit: "Document", click_target: false, capabilities: [] }
531 Canvas { selector: "canvas", aria: None, accesskit: "Canvas", click_target: false, capabilities: [] }
533 Unknown { selector: "unknown", aria: None, accesskit: "Unknown", click_target: false, capabilities: [] }
535}
536
537const EXTRA_ALIASES: &[(&str, Role)] = &[("MultilineTextInput", Role::TextBox)];
539
540const INTERACTIVE: Capabilities = Capabilities::CHECKABLE
543 .union(Capabilities::PRESSABLE)
544 .union(Capabilities::EXPANDABLE)
545 .union(Capabilities::EDITABLE)
546 .union(Capabilities::SELECTABLE)
547 .union(Capabilities::SELECTABLE_ITEM)
548 .union(Capabilities::RANGE_VALUE);
549
550impl Role {
551 #[must_use]
554 pub const fn is_interactive(self) -> bool {
555 self.capabilities().0 & INTERACTIVE.0 != 0 || self.is_click_target()
556 }
557
558 #[must_use]
560 pub fn from_selector_name(name: &str) -> ::core::option::Option<Role> {
561 Role::ALL
562 .iter()
563 .copied()
564 .find(|role| role.selector_name() == name)
565 }
566
567 #[must_use]
570 pub fn from_accesskit_name(name: &str) -> ::core::option::Option<Role> {
571 Role::ALL
572 .iter()
573 .copied()
574 .find(|role| role.accesskit_name() == name)
575 .or_else(|| {
576 EXTRA_ALIASES
577 .iter()
578 .find(|(alias, _)| *alias == name)
579 .map(|(_, role)| *role)
580 })
581 }
582}
583
584impl fmt::Display for Role {
585 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
586 f.write_str(self.selector_name())
587 }
588}
589
590impl FromStr for Role {
591 type Err = ParseRoleError;
592
593 fn from_str(name: &str) -> Result<Self, ParseRoleError> {
594 if let Some(role) =
595 Role::from_selector_name(name).or_else(|| Role::from_accesskit_name(name))
596 {
597 return Ok(role);
598 }
599 Err(ParseRoleError {
600 name: name.to_owned(),
601 suggestions: suggest::nearest(name, Role::ALL.iter().map(|role| role.selector_name())),
602 })
603 }
604}
605
606#[cfg(feature = "serde")]
607impl serde::Serialize for Role {
608 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
609 serializer.serialize_str(self.selector_name())
610 }
611}
612
613#[cfg(feature = "serde")]
616impl<'de> serde::Deserialize<'de> for Role {
617 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
618 let name = String::deserialize(deserializer)?;
619 Ok(name.parse().unwrap_or(Role::Unknown))
620 }
621}
622
623#[cfg(test)]
624mod tests {
625 use super::*;
626 use core::marker::PhantomData;
627
628 #[test]
629 fn display_and_from_str_round_trip_for_every_role() {
630 for role in Role::ALL {
631 assert_eq!(role.to_string().parse::<Role>(), Ok(*role));
632 }
633 }
634
635 #[test]
636 fn selector_names_are_unique() {
637 for (i, a) in Role::ALL.iter().enumerate() {
638 for b in &Role::ALL[i + 1..] {
639 assert_ne!(a.selector_name(), b.selector_name());
640 }
641 }
642 }
643
644 #[test]
645 fn accesskit_names_parse_as_aliases() {
646 assert_eq!("Label".parse(), Ok(Role::Text));
647 assert_eq!("ListBoxOption".parse(), Ok(Role::ListOption));
648 assert_eq!("TextInput".parse(), Ok(Role::TextBox));
649 assert_eq!("MultilineTextInput".parse(), Ok(Role::TextBox));
650 assert_eq!("GenericContainer".parse(), Ok(Role::Generic));
651 assert_eq!("Splitter".parse(), Ok(Role::Splitter));
652 assert_eq!("ProgressIndicator".parse(), Ok(Role::ProgressIndicator));
653 }
654
655 #[test]
656 fn every_accesskit_name_parses_to_a_role_with_that_name() {
657 for role in Role::ALL {
658 let parsed: Role = role.accesskit_name().parse().unwrap_or(Role::Unknown);
659 assert_eq!(parsed.accesskit_name(), role.accesskit_name());
660 }
661 }
662
663 #[test]
664 fn unknown_names_suggest_the_nearest_roles() -> Result<(), &'static str> {
665 let error = "buton".parse::<Role>().err().ok_or("parsed")?;
666 assert_eq!(error.name(), "buton");
667 assert_eq!(error.suggestions(), &["button"]);
668 assert_eq!(
669 error.to_string(),
670 "unknown role `buton`; did you mean `button`?"
671 );
672 let error = "zzzzzzzz".parse::<Role>().err().ok_or("parsed")?;
673 assert!(error.suggestions().is_empty());
674 assert_eq!(error.to_string(), "unknown role `zzzzzzzz`");
675 Ok(())
676 }
677
678 #[test]
679 fn selector_names_are_case_sensitive() {
680 assert!("BUTTON".parse::<Role>().is_err());
681 }
682
683 #[test]
684 fn aria_names_follow_the_table() {
685 assert_eq!(Role::Window.aria_name(), None);
686 assert_eq!(Role::Text.aria_name(), None);
687 assert_eq!(Role::ToggleButton.aria_name(), Some("button"));
688 assert_eq!(Role::Splitter.aria_name(), Some("separator"));
689 assert_eq!(Role::Separator.aria_name(), Some("separator"));
690 assert_eq!(Role::Image.aria_name(), Some("img"));
691 assert_eq!(Role::PasswordInput.aria_name(), None);
692 }
693
694 #[test]
695 fn role_mismatch_reads_well() {
696 let error = RoleMismatch {
697 expected: Role::CheckBox,
698 found: Role::Button,
699 };
700 assert_eq!(CheckBox::try_from(Role::Button), Err(error));
701 assert_eq!(
702 error.to_string(),
703 "expected role `checkbox`, found `button`"
704 );
705 }
706
707 #[test]
708 fn any_role_has_no_runtime_role() {
709 assert_eq!(<AnyRole as RoleKind>::ROLE, None);
710 }
711
712 #[test]
713 fn capabilities_set_operations() {
714 let both = Capabilities::CHECKABLE | Capabilities::LEVELED;
715 assert!(both.contains(Capabilities::CHECKABLE));
716 assert!(both.contains(Capabilities::NONE));
717 assert!(!both.contains(Capabilities::EDITABLE));
718 assert!(Capabilities::default().is_empty());
719 assert!(!both.is_empty());
720 assert_eq!(both.names().collect::<Vec<_>>(), ["Checkable", "Leveled"]);
721 assert_eq!(format!("{both:?}"), r#"{"Checkable", "Leveled"}"#);
722 let mut grown = Capabilities::NONE;
723 grown |= Capabilities::PRESSABLE;
724 assert_eq!(grown, Capabilities::PRESSABLE);
725 }
726
727 #[test]
728 fn capability_bits_are_distinct() {
729 let mut seen = Capabilities::NONE;
730 for (capability, _) in Capabilities::NAMED {
731 assert!(!seen.contains(*capability));
732 seen |= *capability;
733 }
734 }
735
736 #[test]
737 fn interactive_roles_have_a_capability_or_are_click_targets() {
738 assert!(Role::Link.is_interactive());
739 assert!(Role::ColumnHeader.is_interactive());
740 assert!(Role::CheckBox.is_interactive());
741 assert!(!Role::Generic.is_interactive());
742 assert!(!Role::Scrim.is_interactive());
743 }
744
745 #[test]
746 fn a_level_or_a_read_only_value_alone_is_not_interactive() {
747 assert!(!Role::Heading.is_interactive());
748 assert!(!Role::ProgressIndicator.is_interactive());
749 assert!(Role::Slider.is_interactive());
750 assert!(Role::TextBox.is_interactive());
751 assert!(Role::Button.is_interactive());
752 for role in Role::ALL {
753 let acts = [
754 Capabilities::CHECKABLE,
755 Capabilities::PRESSABLE,
756 Capabilities::EXPANDABLE,
757 Capabilities::EDITABLE,
758 Capabilities::SELECTABLE,
759 Capabilities::SELECTABLE_ITEM,
760 Capabilities::RANGE_VALUE,
761 ]
762 .iter()
763 .any(|c| role.capabilities().contains(*c));
764 assert_eq!(
765 role.is_interactive(),
766 acts || role.is_click_target(),
767 "{role}"
768 );
769 }
770 }
771
772 struct Probe<T>(PhantomData<T>);
775
776 macro_rules! detector {
777 ($trait_name:ident, $fallback:ident, $method:ident) => {
778 trait $fallback {
779 fn $method(&self) -> bool {
780 false
781 }
782 }
783 impl<T> $fallback for Probe<T> {}
784 impl<T: $trait_name> Probe<T> {
785 fn $method(&self) -> bool {
786 true
787 }
788 }
789 };
790 }
791
792 detector!(Checkable, NotCheckable, checkable);
793 detector!(Editable, NotEditable, editable);
794 detector!(Selectable, NotSelectable, selectable);
795 detector!(Expandable, NotExpandable, expandable);
796 detector!(RangeValue, NotRangeValue, range_value);
797 detector!(Pressable, NotPressable, pressable);
798 detector!(HasValue, NotHasValue, has_value);
799 detector!(SelectableItem, NotSelectableItem, selectable_item);
800 detector!(Leveled, NotLeveled, leveled);
801
802 macro_rules! implemented {
803 ($ty:ty) => {{
804 let probe = Probe::<$ty>(PhantomData);
805 let mut set = Capabilities::NONE;
806 for (on, capability) in [
807 (probe.checkable(), Capabilities::CHECKABLE),
808 (probe.editable(), Capabilities::EDITABLE),
809 (probe.selectable(), Capabilities::SELECTABLE),
810 (probe.expandable(), Capabilities::EXPANDABLE),
811 (probe.range_value(), Capabilities::RANGE_VALUE),
812 (probe.pressable(), Capabilities::PRESSABLE),
813 (probe.has_value(), Capabilities::HAS_VALUE),
814 (probe.selectable_item(), Capabilities::SELECTABLE_ITEM),
815 (probe.leveled(), Capabilities::LEVELED),
816 ] {
817 if on {
818 set |= capability;
819 }
820 }
821 set
822 }};
823 }
824
825 macro_rules! semantics_table {
828 ($($ty:ident, $selector:literal, $aria:expr, $accesskit:literal, [$($cap:ident),*], $click:literal;)+) => {
829 vec![$((
830 Role::$ty,
831 <$ty as RoleType>::ROLE_VALUE,
832 Role::from($ty),
833 $ty::try_from(Role::$ty).is_ok(),
834 implemented!($ty),
835 $selector,
836 $aria,
837 $accesskit,
838 Capabilities::NONE $(| Capabilities::$cap)*,
839 $click,
840 )),+]
841 };
842 }
843
844 #[test]
845 fn the_table_matches_semantics_md() {
846 let rows = semantics_table! {
847 Window, "window", None, "Window", [], false;
848 Generic, "generic", Some("generic"), "GenericContainer", [], false;
849 Group, "group", Some("group"), "Group", [], false;
850 Region, "region", Some("region"), "Region", [], false;
851 Navigation, "navigation", Some("navigation"), "Navigation", [], false;
852 Toolbar, "toolbar", Some("toolbar"), "Toolbar", [], false;
853 Text, "text", None, "Label", [], false;
854 Paragraph, "paragraph", Some("paragraph"), "Paragraph", [], false;
855 Heading, "heading", Some("heading"), "Heading", [LEVELED], false;
856 Image, "img", Some("img"), "Image", [], false;
857 Link, "link", Some("link"), "Link", [], true;
858 Button, "button", Some("button"), "Button", [EXPANDABLE], true;
859 ToggleButton, "togglebutton", Some("button"), "ToggleButton", [PRESSABLE], true;
860 CheckBox, "checkbox", Some("checkbox"), "CheckBox", [CHECKABLE], false;
861 RadioButton, "radio", Some("radio"), "RadioButton", [CHECKABLE], false;
862 RadioGroup, "radiogroup", Some("radiogroup"), "RadioGroup", [SELECTABLE], false;
863 Switch, "switch", Some("switch"), "Switch", [CHECKABLE], false;
864 TextBox, "textbox", Some("textbox"), "TextInput", [EDITABLE, HAS_VALUE], false;
865 SearchBox, "searchbox", Some("searchbox"), "SearchInput", [EDITABLE, HAS_VALUE], false;
866 PasswordInput, "password", None, "PasswordInput", [EDITABLE, HAS_VALUE], false;
867 ComboBox, "combobox", Some("combobox"), "ComboBox", [EDITABLE, SELECTABLE, EXPANDABLE, HAS_VALUE], false;
868 ListBox, "listbox", Some("listbox"), "ListBox", [SELECTABLE], false;
869 ListOption, "option", Some("option"), "ListBoxOption", [SELECTABLE_ITEM], true;
870 Slider, "slider", Some("slider"), "Slider", [RANGE_VALUE, HAS_VALUE], false;
871 SpinButton, "spinbutton", Some("spinbutton"), "SpinButton", [EDITABLE, RANGE_VALUE, HAS_VALUE], false;
872 ProgressIndicator, "progressbar", Some("progressbar"), "ProgressIndicator", [HAS_VALUE], false;
873 ScrollView, "scrollview", None, "ScrollView", [], false;
874 Splitter, "separator", Some("separator"), "Splitter", [RANGE_VALUE, HAS_VALUE], false;
875 Separator, "separator-static", Some("separator"), "GenericContainer", [], false;
876 Scrim, "scrim", None, "GenericContainer", [], false;
877 List, "list", Some("list"), "List", [], false;
878 ListItem, "listitem", Some("listitem"), "ListItem", [SELECTABLE_ITEM, LEVELED], true;
879 Tree, "tree", Some("tree"), "Tree", [], false;
880 TreeItem, "treeitem", Some("treeitem"), "TreeItem", [CHECKABLE, EXPANDABLE, SELECTABLE_ITEM, LEVELED], true;
881 Table, "table", Some("table"), "Table", [], false;
882 Grid, "grid", Some("grid"), "Grid", [], false;
883 Row, "row", Some("row"), "Row", [EXPANDABLE, SELECTABLE_ITEM, LEVELED], true;
884 Cell, "cell", Some("cell"), "Cell", [SELECTABLE_ITEM], true;
885 ColumnHeader, "columnheader", Some("columnheader"), "ColumnHeader", [], true;
886 RowHeader, "rowheader", Some("rowheader"), "RowHeader", [], false;
887 TabList, "tablist", Some("tablist"), "TabList", [SELECTABLE], false;
888 Tab, "tab", Some("tab"), "Tab", [SELECTABLE_ITEM], true;
889 TabPanel, "tabpanel", Some("tabpanel"), "TabPanel", [], false;
890 Menu, "menu", Some("menu"), "Menu", [], false;
891 MenuBar, "menubar", Some("menubar"), "MenuBar", [], false;
892 MenuItem, "menuitem", Some("menuitem"), "MenuItem", [EXPANDABLE], true;
893 MenuItemCheckBox, "menuitemcheckbox", Some("menuitemcheckbox"), "MenuItemCheckBox", [CHECKABLE], false;
894 MenuItemRadio, "menuitemradio", Some("menuitemradio"), "MenuItemRadio", [CHECKABLE], false;
895 Dialog, "dialog", Some("dialog"), "Dialog", [], false;
896 AlertDialog, "alertdialog", Some("alertdialog"), "AlertDialog", [], false;
897 Tooltip, "tooltip", Some("tooltip"), "Tooltip", [], false;
898 Status, "status", Some("status"), "Status", [], false;
899 Alert, "alert", Some("alert"), "Alert", [], false;
900 Document, "document", Some("document"), "Document", [], false;
901 Canvas, "canvas", None, "Canvas", [], false;
902 Unknown, "unknown", None, "Unknown", [], false;
903 };
904
905 assert_eq!(rows.len(), Role::ALL.len());
906 for (
907 index,
908 (role, value, from, tried, traits, selector, aria, accesskit, capabilities, click),
909 ) in rows.into_iter().enumerate()
910 {
911 assert_eq!(Role::ALL[index], role, "table order");
912 assert_eq!(value, role);
913 assert_eq!(from, role);
914 assert!(tried);
915 assert_eq!(role.selector_name(), selector, "{role:?}");
916 assert_eq!(role.aria_name(), aria, "{role:?}");
917 assert_eq!(role.accesskit_name(), accesskit, "{role:?}");
918 assert_eq!(role.capabilities(), capabilities, "{role:?} bits");
919 assert_eq!(traits, capabilities, "{role:?} traits");
920 assert_eq!(role.is_click_target(), click, "{role:?}");
921 assert_eq!(role.type_name(), format!("{role:?}"));
922 }
923 }
924
925 macro_rules! maps_to_one_variant {
926 ($($ty:ident),+ $(,)?) => {{
927 let markers: Vec<Role> = vec![$(<$ty as RoleType>::ROLE_VALUE),+];
928 for role in Role::ALL {
929 let tried = [$($ty::try_from(*role).is_ok()),+];
930 assert_eq!(tried.iter().filter(|ok| **ok).count(), 1, "{role:?}");
931 }
932 markers
933 }};
934 }
935
936 #[test]
937 fn every_marker_maps_to_exactly_one_variant_and_back() {
938 let markers = maps_to_one_variant!(
939 Window,
940 Generic,
941 Group,
942 Region,
943 Navigation,
944 Toolbar,
945 Text,
946 Paragraph,
947 Heading,
948 Image,
949 Link,
950 Button,
951 ToggleButton,
952 CheckBox,
953 RadioButton,
954 RadioGroup,
955 Switch,
956 TextBox,
957 SearchBox,
958 PasswordInput,
959 ComboBox,
960 ListBox,
961 ListOption,
962 Slider,
963 SpinButton,
964 ProgressIndicator,
965 ScrollView,
966 Splitter,
967 Separator,
968 Scrim,
969 List,
970 ListItem,
971 Tree,
972 TreeItem,
973 Table,
974 Grid,
975 Row,
976 Cell,
977 ColumnHeader,
978 RowHeader,
979 TabList,
980 Tab,
981 TabPanel,
982 Menu,
983 MenuBar,
984 MenuItem,
985 MenuItemCheckBox,
986 MenuItemRadio,
987 Dialog,
988 AlertDialog,
989 Tooltip,
990 Status,
991 Alert,
992 Document,
993 Canvas,
994 Unknown,
995 );
996 assert_eq!(markers, Role::ALL);
997 }
998
999 #[cfg(feature = "serde")]
1000 #[test]
1001 fn roles_serialise_as_selector_names_and_unknown_names_become_unknown()
1002 -> Result<(), serde_json::Error> {
1003 for role in Role::ALL {
1004 let json = serde_json::to_string(role)?;
1005 assert_eq!(json, format!("\"{}\"", role.selector_name()));
1006 assert_eq!(serde_json::from_str::<Role>(&json)?, *role);
1007 }
1008 assert_eq!(serde_json::from_str::<Role>("\"hologram\"")?, Role::Unknown);
1009 assert_eq!(serde_json::from_str::<Role>("\"Label\"")?, Role::Text);
1010 assert_eq!(serde_json::to_string(&Button)?, "null");
1011 Ok(())
1012 }
1013}