icedwright-types 0.1.0

Shared types for icedwright: roles and capabilities, pixel units, virtual time, frames, key chords and the Messages trait
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
//! Roles: the runtime [`Role`] enum, one zero-sized marker type per role, and the sealed
//! capability traits that say what each role can do.
//!
//! Code written by people names a role through its marker type, such as [`Button`] or
//! [`CheckBox`], so a method gated on a capability only compiles for roles that have it.
//! Trees, YAML, selector strings and the wire carry the runtime [`Role`] instead.
//!
//! Everything here comes from one table, so the enum, the marker types, the capability
//! impls and the names cannot drift apart.

use core::fmt;
use core::str::FromStr;

use crate::suggest;

mod sealed {
    pub trait Sealed {}
}

/// The one marker trait every role type and [`AnyRole`] implement. Sealed.
pub trait RoleKind: sealed::Sealed + Copy + Default + fmt::Debug + Send + Sync + 'static {
    /// The runtime role, or `None` for [`AnyRole`].
    const ROLE: ::core::option::Option<Role>;
}

/// Implemented by concrete roles only, never by [`AnyRole`]. Sealed through [`RoleKind`].
#[diagnostic::on_unimplemented(
    message = "`{Self}` is not a concrete role",
    note = "use a role type such as `role::Button`"
)]
pub trait RoleType: RoleKind {
    /// The runtime role this type stands for.
    const ROLE_VALUE: Role;
}

/// Implemented by [`AnyRole`] only. Gates narrowing an untyped handle to a role.
#[diagnostic::on_unimplemented(
    message = "this already has role `{Self}`",
    note = "call `.any_role()` first if you really mean to change it"
)]
pub trait Untyped: RoleKind {}

/// Roles that have a checked state: `check`, `uncheck`, `set_checked`, `to_be_checked`.
#[diagnostic::on_unimplemented(
    message = "`{Self}` cannot be checked",
    label = "this role has no checked state",
    note = "narrow an untyped handle with `.into_role::<role::CheckBox>()`, or use a role that implements `Checkable`"
)]
pub trait Checkable: RoleType {}

/// Roles whose text can be typed into: `fill`, `clear`, `press_sequentially`, `to_be_editable`.
#[diagnostic::on_unimplemented(
    message = "`{Self}` cannot be edited",
    label = "this role takes no typed text",
    note = "narrow an untyped handle with `.into_role::<role::TextBox>()`, or use a role that implements `Editable`"
)]
pub trait Editable: HasValue {}

/// Roles that own a set of options to pick from: `select_option`.
#[diagnostic::on_unimplemented(
    message = "`{Self}` has no options to select",
    label = "this role owns no options",
    note = "narrow an untyped handle with `.into_role::<role::ComboBox>()`, or use a role that implements `Selectable`"
)]
pub trait Selectable: RoleType {}

/// Roles that open and close: `expand`, `collapse`, `to_be_expanded`.
#[diagnostic::on_unimplemented(
    message = "`{Self}` cannot be expanded",
    label = "this role has no expanded state",
    note = "narrow an untyped handle with `.into_role::<role::TreeItem>()`, or use a role that implements `Expandable`"
)]
pub trait Expandable: RoleType {}

/// Roles with a numeric value in a range: `set_value`.
#[diagnostic::on_unimplemented(
    message = "`{Self}` has no value range to set",
    label = "this role has no numeric range",
    note = "narrow an untyped handle with `.into_role::<role::Slider>()`, or use a role that implements `RangeValue`"
)]
pub trait RangeValue: HasValue {}

/// Toggle buttons, which report whether they are pressed: `to_be_pressed`.
#[diagnostic::on_unimplemented(
    message = "`{Self}` has no pressed state",
    label = "only toggle buttons are pressed or not",
    note = "narrow an untyped handle with `.into_role::<role::ToggleButton>()`, or use a role that implements `Pressable`"
)]
pub trait Pressable: RoleType {}

/// Roles that have a value to read: `to_have_value`.
#[diagnostic::on_unimplemented(
    message = "`{Self}` has no value",
    label = "this role reports no value",
    note = "narrow an untyped handle with `.into_role::<role::TextBox>()`, or use a role that implements `HasValue`"
)]
pub trait HasValue: RoleType {}

/// Items inside a list, tree, table or tab list that can be selected: `select`, `to_be_selected`.
#[diagnostic::on_unimplemented(
    message = "`{Self}` cannot be selected",
    label = "this role is not a selectable item",
    note = "narrow an untyped handle with `.into_role::<role::ListOption>()`, or use a role that implements `SelectableItem`"
)]
pub trait SelectableItem: RoleType {}

/// Roles with a nesting level: `to_have_level`.
#[diagnostic::on_unimplemented(
    message = "`{Self}` has no level",
    label = "this role has no nesting level",
    note = "narrow an untyped handle with `.into_role::<role::Heading>()`, or use a role that implements `Leveled`"
)]
pub trait Leveled: RoleType {}

/// The role of a node found by text, test id or a run-time selector.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct AnyRole;

impl sealed::Sealed for AnyRole {}

impl RoleKind for AnyRole {
    const ROLE: ::core::option::Option<Role> = ::core::option::Option::None;
}

impl Untyped for AnyRole {}

/// The run-time mirror of the capability traits, for the recorder, the remote client and audits.
#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct Capabilities(u16);

impl Capabilities {
    /// No capabilities.
    pub const NONE: Self = Self(0);
    /// [`Checkable`].
    pub const CHECKABLE: Self = Self(1);
    /// [`Editable`].
    pub const EDITABLE: Self = Self(1 << 1);
    /// [`Selectable`].
    pub const SELECTABLE: Self = Self(1 << 2);
    /// [`Expandable`].
    pub const EXPANDABLE: Self = Self(1 << 3);
    /// [`RangeValue`].
    pub const RANGE_VALUE: Self = Self(1 << 4);
    /// [`Pressable`].
    pub const PRESSABLE: Self = Self(1 << 5);
    /// [`HasValue`].
    pub const HAS_VALUE: Self = Self(1 << 6);
    /// [`SelectableItem`].
    pub const SELECTABLE_ITEM: Self = Self(1 << 7);
    /// [`Leveled`].
    pub const LEVELED: Self = Self(1 << 8);

    /// Every capability with the name of its trait, in declaration order.
    pub const NAMED: &'static [(Self, &'static str)] = &[
        (Self::CHECKABLE, "Checkable"),
        (Self::EDITABLE, "Editable"),
        (Self::SELECTABLE, "Selectable"),
        (Self::EXPANDABLE, "Expandable"),
        (Self::RANGE_VALUE, "RangeValue"),
        (Self::PRESSABLE, "Pressable"),
        (Self::HAS_VALUE, "HasValue"),
        (Self::SELECTABLE_ITEM, "SelectableItem"),
        (Self::LEVELED, "Leveled"),
    ];

    /// Whether every capability in `other` is also in `self`.
    #[must_use]
    pub const fn contains(self, other: Self) -> bool {
        self.0 & other.0 == other.0
    }

    /// Whether the set is empty.
    #[must_use]
    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }

    /// The capabilities in either set.
    #[must_use]
    pub const fn union(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }

    /// The trait names of the capabilities in this set, in declaration order.
    pub fn names(self) -> impl Iterator<Item = &'static str> {
        Self::NAMED
            .iter()
            .filter(move |(capability, _)| self.contains(*capability))
            .map(|(_, name)| *name)
    }
}

impl core::ops::BitOr for Capabilities {
    type Output = Self;

    fn bitor(self, other: Self) -> Self {
        self.union(other)
    }
}

impl core::ops::BitOrAssign for Capabilities {
    fn bitor_assign(&mut self, other: Self) {
        *self = self.union(other);
    }
}

impl fmt::Debug for Capabilities {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_set().entries(self.names()).finish()
    }
}

/// A role type was asked for a [`Role`] it does not stand for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RoleMismatch {
    /// The role the type stands for.
    pub expected: Role,
    /// The role that was found.
    pub found: Role,
}

impl fmt::Display for RoleMismatch {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "expected role `{}`, found `{}`",
            self.expected, self.found
        )
    }
}

impl std::error::Error for RoleMismatch {}

/// A string that names no role.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseRoleError {
    name: String,
    suggestions: Vec<&'static str>,
}

impl ParseRoleError {
    /// The name that was not recognised.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The nearest selector names, nearest first.
    #[must_use]
    pub fn suggestions(&self) -> &[&'static str] {
        &self.suggestions
    }
}

impl fmt::Display for ParseRoleError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "unknown role `{}`{}",
            self.name,
            suggest::did_you_mean(&self.suggestions)
        )
    }
}

impl std::error::Error for ParseRoleError {}

impl<R: RoleType> From<R> for Role {
    fn from(_: R) -> Role {
        R::ROLE_VALUE
    }
}

macro_rules! capability {
    (Checkable) => {
        Capabilities::CHECKABLE
    };
    (Editable) => {
        Capabilities::EDITABLE
    };
    (Selectable) => {
        Capabilities::SELECTABLE
    };
    (Expandable) => {
        Capabilities::EXPANDABLE
    };
    (RangeValue) => {
        Capabilities::RANGE_VALUE
    };
    (Pressable) => {
        Capabilities::PRESSABLE
    };
    (HasValue) => {
        Capabilities::HAS_VALUE
    };
    (SelectableItem) => {
        Capabilities::SELECTABLE_ITEM
    };
    (Leveled) => {
        Capabilities::LEVELED
    };
}

macro_rules! roles {
    ($(
        $(#[doc = $doc:literal])+
        $variant:ident {
            selector: $selector:literal,
            aria: $aria:expr,
            accesskit: $accesskit:literal,
            click_target: $click:literal,
            capabilities: [$($capability:ident),*] $(,)?
        }
    )+) => {
        /// The runtime role of a node, carried by trees, YAML, selector strings and the wire.
        ///
        /// `Display` prints the selector name and `FromStr` parses it back, also accepting
        /// AccessKit names as aliases.
        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
        #[non_exhaustive]
        pub enum Role {
            $(
                $(#[doc = $doc])+
                $variant,
            )+
        }

        impl Role {
            /// Every role, in table order.
            pub const ALL: &'static [Role] = &[$(Role::$variant),+];

            /// The name used in selector strings, YAML and on the wire, such as `button`.
            #[must_use]
            pub const fn selector_name(self) -> &'static str {
                match self {
                    $(Role::$variant => $selector,)+
                }
            }

            /// The ARIA role name, or `None` where ARIA has no matching role.
            #[must_use]
            pub const fn aria_name(self) -> ::core::option::Option<&'static str> {
                match self {
                    $(Role::$variant => $aria,)+
                }
            }

            /// The AccessKit role name. A multi-line text box is `MultilineTextInput` in
            /// AccessKit; this returns the single-line name for [`Role::TextBox`].
            #[must_use]
            pub const fn accesskit_name(self) -> &'static str {
                match self {
                    $(Role::$variant => $accesskit,)+
                }
            }

            /// The name of the variant and of its role type in [`crate::role`], such as `Button`.
            #[must_use]
            pub const fn type_name(self) -> &'static str {
                match self {
                    $(Role::$variant => stringify!($variant),)+
                }
            }

            /// The capability traits this role's type implements.
            #[must_use]
            pub const fn capabilities(self) -> Capabilities {
                match self {
                    $(Role::$variant => Capabilities::NONE $(.union(capability!($capability)))*,)+
                }
            }

            /// Whether a click on the node itself is what activates it.
            #[must_use]
            pub const fn is_click_target(self) -> bool {
                match self {
                    $(Role::$variant => $click,)+
                }
            }
        }

        $(
            #[doc = concat!(
                "The role type for [`Role::", stringify!($variant),
                "`], selector name `", $selector, "`."
            )]
            #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
            #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
            pub struct $variant;

            impl sealed::Sealed for $variant {}

            impl RoleKind for $variant {
                const ROLE: ::core::option::Option<Role> =
                    ::core::option::Option::Some(Role::$variant);
            }

            impl RoleType for $variant {
                const ROLE_VALUE: Role = Role::$variant;
            }

            $(impl $capability for $variant {})*

            impl ::core::convert::TryFrom<Role> for $variant {
                type Error = RoleMismatch;

                fn try_from(role: Role) -> ::core::result::Result<Self, RoleMismatch> {
                    if role == Role::$variant {
                        return ::core::result::Result::Ok($variant);
                    }
                    ::core::result::Result::Err(RoleMismatch {
                        expected: Role::$variant,
                        found: role,
                    })
                }
            }
        )+
    };
}

roles! {
    /// A top-level window. Every tree has one per window as its root.
    Window { selector: "window", aria: None, accesskit: "Window", click_target: false, capabilities: [] }
    /// A container with no meaning of its own.
    Generic { selector: "generic", aria: Some("generic"), accesskit: "GenericContainer", click_target: false, capabilities: [] }
    /// A set of related controls.
    Group { selector: "group", aria: Some("group"), accesskit: "Group", click_target: false, capabilities: [] }
    /// A named landmark section.
    Region { selector: "region", aria: Some("region"), accesskit: "Region", click_target: false, capabilities: [] }
    /// A landmark holding navigation links or controls.
    Navigation { selector: "navigation", aria: Some("navigation"), accesskit: "Navigation", click_target: false, capabilities: [] }
    /// A row of controls such as buttons.
    Toolbar { selector: "toolbar", aria: Some("toolbar"), accesskit: "Toolbar", click_target: false, capabilities: [] }
    /// A run of static text.
    Text { selector: "text", aria: None, accesskit: "Label", click_target: false, capabilities: [] }
    /// A paragraph of text.
    Paragraph { selector: "paragraph", aria: Some("paragraph"), accesskit: "Paragraph", click_target: false, capabilities: [] }
    /// A heading, with a level.
    Heading { selector: "heading", aria: Some("heading"), accesskit: "Heading", click_target: false, capabilities: [Leveled] }
    /// An image.
    Image { selector: "img", aria: Some("img"), accesskit: "Image", click_target: false, capabilities: [] }
    /// A link.
    Link { selector: "link", aria: Some("link"), accesskit: "Link", click_target: true, capabilities: [] }
    /// A button, which may open a popup and so be expandable.
    Button { selector: "button", aria: Some("button"), accesskit: "Button", click_target: true, capabilities: [Expandable] }
    /// A button that stays pressed or not.
    ToggleButton { selector: "togglebutton", aria: Some("button"), accesskit: "ToggleButton", click_target: true, capabilities: [Pressable] }
    /// A checkbox.
    CheckBox { selector: "checkbox", aria: Some("checkbox"), accesskit: "CheckBox", click_target: false, capabilities: [Checkable] }
    /// One radio button of a group.
    RadioButton { selector: "radio", aria: Some("radio"), accesskit: "RadioButton", click_target: false, capabilities: [Checkable] }
    /// A group of radio buttons.
    RadioGroup { selector: "radiogroup", aria: Some("radiogroup"), accesskit: "RadioGroup", click_target: false, capabilities: [Selectable] }
    /// An on and off switch, such as a toggler.
    Switch { selector: "switch", aria: Some("switch"), accesskit: "Switch", click_target: false, capabilities: [Checkable] }
    /// A text input or editor; multi-line editors have the `multiline` state.
    TextBox { selector: "textbox", aria: Some("textbox"), accesskit: "TextInput", click_target: false, capabilities: [Editable, HasValue] }
    /// A text input for search terms.
    SearchBox { selector: "searchbox", aria: Some("searchbox"), accesskit: "SearchInput", click_target: false, capabilities: [Editable, HasValue] }
    /// A text input whose value is hidden.
    PasswordInput { selector: "password", aria: None, accesskit: "PasswordInput", click_target: false, capabilities: [Editable, HasValue] }
    /// A text input with a list of options, such as a pick list or combo box.
    ComboBox { selector: "combobox", aria: Some("combobox"), accesskit: "ComboBox", click_target: false, capabilities: [Editable, Selectable, Expandable, HasValue] }
    /// A list of options to pick from.
    ListBox { selector: "listbox", aria: Some("listbox"), accesskit: "ListBox", click_target: false, capabilities: [Selectable] }
    /// One option of a list box. Named so that it does not shadow `Option`.
    ListOption { selector: "option", aria: Some("option"), accesskit: "ListBoxOption", click_target: true, capabilities: [SelectableItem] }
    /// A slider over a range of values.
    Slider { selector: "slider", aria: Some("slider"), accesskit: "Slider", click_target: false, capabilities: [RangeValue, HasValue] }
    /// A numeric input with step buttons.
    SpinButton { selector: "spinbutton", aria: Some("spinbutton"), accesskit: "SpinButton", click_target: false, capabilities: [Editable, RangeValue, HasValue] }
    /// A progress bar.
    ProgressIndicator { selector: "progressbar", aria: Some("progressbar"), accesskit: "ProgressIndicator", click_target: false, capabilities: [HasValue] }
    /// A scrollable area.
    ScrollView { selector: "scrollview", aria: None, accesskit: "ScrollView", click_target: false, capabilities: [] }
    /// A focusable separator that resizes the panes either side of it.
    Splitter { selector: "separator", aria: Some("separator"), accesskit: "Splitter", click_target: false, capabilities: [RangeValue, HasValue] }
    /// A separator that only divides content.
    Separator { selector: "separator-static", aria: Some("separator"), accesskit: "GenericContainer", click_target: false, capabilities: [] }
    /// The layer that blocks the pointer under a dialog or drawer.
    Scrim { selector: "scrim", aria: None, accesskit: "GenericContainer", click_target: false, capabilities: [] }
    /// A list.
    List { selector: "list", aria: Some("list"), accesskit: "List", click_target: false, capabilities: [] }
    /// One item of a list.
    ListItem { selector: "listitem", aria: Some("listitem"), accesskit: "ListItem", click_target: true, capabilities: [SelectableItem, Leveled] }
    /// A tree view.
    Tree { selector: "tree", aria: Some("tree"), accesskit: "Tree", click_target: false, capabilities: [] }
    /// One item of a tree view.
    TreeItem { selector: "treeitem", aria: Some("treeitem"), accesskit: "TreeItem", click_target: true, capabilities: [Checkable, Expandable, SelectableItem, Leveled] }
    /// A table.
    Table { selector: "table", aria: Some("table"), accesskit: "Table", click_target: false, capabilities: [] }
    /// An interactive grid.
    Grid { selector: "grid", aria: Some("grid"), accesskit: "Grid", click_target: false, capabilities: [] }
    /// A row of a table, grid or tree grid.
    Row { selector: "row", aria: Some("row"), accesskit: "Row", click_target: true, capabilities: [Expandable, SelectableItem, Leveled] }
    /// A cell of a table or grid.
    Cell { selector: "cell", aria: Some("cell"), accesskit: "Cell", click_target: true, capabilities: [SelectableItem] }
    /// A column header.
    ColumnHeader { selector: "columnheader", aria: Some("columnheader"), accesskit: "ColumnHeader", click_target: true, capabilities: [] }
    /// A row header.
    RowHeader { selector: "rowheader", aria: Some("rowheader"), accesskit: "RowHeader", click_target: false, capabilities: [] }
    /// A row of tabs.
    TabList { selector: "tablist", aria: Some("tablist"), accesskit: "TabList", click_target: false, capabilities: [Selectable] }
    /// One tab.
    Tab { selector: "tab", aria: Some("tab"), accesskit: "Tab", click_target: true, capabilities: [SelectableItem] }
    /// The content shown for a tab.
    TabPanel { selector: "tabpanel", aria: Some("tabpanel"), accesskit: "TabPanel", click_target: false, capabilities: [] }
    /// A menu.
    Menu { selector: "menu", aria: Some("menu"), accesskit: "Menu", click_target: false, capabilities: [] }
    /// A menu bar.
    MenuBar { selector: "menubar", aria: Some("menubar"), accesskit: "MenuBar", click_target: false, capabilities: [] }
    /// A menu item, which may open a submenu.
    MenuItem { selector: "menuitem", aria: Some("menuitem"), accesskit: "MenuItem", click_target: true, capabilities: [Expandable] }
    /// A menu item with a checked state.
    MenuItemCheckBox { selector: "menuitemcheckbox", aria: Some("menuitemcheckbox"), accesskit: "MenuItemCheckBox", click_target: false, capabilities: [Checkable] }
    /// A menu item that is one of a group.
    MenuItemRadio { selector: "menuitemradio", aria: Some("menuitemradio"), accesskit: "MenuItemRadio", click_target: false, capabilities: [Checkable] }
    /// A dialog.
    Dialog { selector: "dialog", aria: Some("dialog"), accesskit: "Dialog", click_target: false, capabilities: [] }
    /// A dialog that interrupts with an urgent message.
    AlertDialog { selector: "alertdialog", aria: Some("alertdialog"), accesskit: "AlertDialog", click_target: false, capabilities: [] }
    /// A tooltip.
    Tooltip { selector: "tooltip", aria: Some("tooltip"), accesskit: "Tooltip", click_target: false, capabilities: [] }
    /// A live region with advisory status.
    Status { selector: "status", aria: Some("status"), accesskit: "Status", click_target: false, capabilities: [] }
    /// A live region with an important message.
    Alert { selector: "alert", aria: Some("alert"), accesskit: "Alert", click_target: false, capabilities: [] }
    /// A document.
    Document { selector: "document", aria: Some("document"), accesskit: "Document", click_target: false, capabilities: [] }
    /// A canvas.
    Canvas { selector: "canvas", aria: None, accesskit: "Canvas", click_target: false, capabilities: [] }
    /// A role this version does not know, or none could be given.
    Unknown { selector: "unknown", aria: None, accesskit: "Unknown", click_target: false, capabilities: [] }
}

/// AccessKit names that map to a role without being its [`Role::accesskit_name`].
const EXTRA_ALIASES: &[(&str, Role)] = &[("MultilineTextInput", Role::TextBox)];

/// The capabilities that make a role interactive. A level or a read-only value alone, as on a
/// heading or a progress bar, does not.
const INTERACTIVE: Capabilities = Capabilities::CHECKABLE
    .union(Capabilities::PRESSABLE)
    .union(Capabilities::EXPANDABLE)
    .union(Capabilities::EDITABLE)
    .union(Capabilities::SELECTABLE)
    .union(Capabilities::SELECTABLE_ITEM)
    .union(Capabilities::RANGE_VALUE);

impl Role {
    /// Whether the role is interactive, for audits: a click target, or any capability a person
    /// acts through (checking, pressing, expanding, editing, selecting or setting a value).
    #[must_use]
    pub const fn is_interactive(self) -> bool {
        self.capabilities().0 & INTERACTIVE.0 != 0 || self.is_click_target()
    }

    /// The role with this selector name, without AccessKit aliases.
    #[must_use]
    pub fn from_selector_name(name: &str) -> ::core::option::Option<Role> {
        Role::ALL
            .iter()
            .copied()
            .find(|role| role.selector_name() == name)
    }

    /// The role with this AccessKit name. Where several roles share one, the first in
    /// [`Role::ALL`] wins, so `GenericContainer` is [`Role::Generic`].
    #[must_use]
    pub fn from_accesskit_name(name: &str) -> ::core::option::Option<Role> {
        Role::ALL
            .iter()
            .copied()
            .find(|role| role.accesskit_name() == name)
            .or_else(|| {
                EXTRA_ALIASES
                    .iter()
                    .find(|(alias, _)| *alias == name)
                    .map(|(_, role)| *role)
            })
    }
}

impl fmt::Display for Role {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.selector_name())
    }
}

impl FromStr for Role {
    type Err = ParseRoleError;

    fn from_str(name: &str) -> Result<Self, ParseRoleError> {
        if let Some(role) =
            Role::from_selector_name(name).or_else(|| Role::from_accesskit_name(name))
        {
            return Ok(role);
        }
        Err(ParseRoleError {
            name: name.to_owned(),
            suggestions: suggest::nearest(name, Role::ALL.iter().map(|role| role.selector_name())),
        })
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Role {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.selector_name())
    }
}

/// A name this version does not know, which only a newer probe can send, becomes
/// [`Role::Unknown`].
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Role {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let name = String::deserialize(deserializer)?;
        Ok(name.parse().unwrap_or(Role::Unknown))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use core::marker::PhantomData;

    #[test]
    fn display_and_from_str_round_trip_for_every_role() {
        for role in Role::ALL {
            assert_eq!(role.to_string().parse::<Role>(), Ok(*role));
        }
    }

    #[test]
    fn selector_names_are_unique() {
        for (i, a) in Role::ALL.iter().enumerate() {
            for b in &Role::ALL[i + 1..] {
                assert_ne!(a.selector_name(), b.selector_name());
            }
        }
    }

    #[test]
    fn accesskit_names_parse_as_aliases() {
        assert_eq!("Label".parse(), Ok(Role::Text));
        assert_eq!("ListBoxOption".parse(), Ok(Role::ListOption));
        assert_eq!("TextInput".parse(), Ok(Role::TextBox));
        assert_eq!("MultilineTextInput".parse(), Ok(Role::TextBox));
        assert_eq!("GenericContainer".parse(), Ok(Role::Generic));
        assert_eq!("Splitter".parse(), Ok(Role::Splitter));
        assert_eq!("ProgressIndicator".parse(), Ok(Role::ProgressIndicator));
    }

    #[test]
    fn every_accesskit_name_parses_to_a_role_with_that_name() {
        for role in Role::ALL {
            let parsed: Role = role.accesskit_name().parse().unwrap_or(Role::Unknown);
            assert_eq!(parsed.accesskit_name(), role.accesskit_name());
        }
    }

    #[test]
    fn unknown_names_suggest_the_nearest_roles() -> Result<(), &'static str> {
        let error = "buton".parse::<Role>().err().ok_or("parsed")?;
        assert_eq!(error.name(), "buton");
        assert_eq!(error.suggestions(), &["button"]);
        assert_eq!(
            error.to_string(),
            "unknown role `buton`; did you mean `button`?"
        );
        let error = "zzzzzzzz".parse::<Role>().err().ok_or("parsed")?;
        assert!(error.suggestions().is_empty());
        assert_eq!(error.to_string(), "unknown role `zzzzzzzz`");
        Ok(())
    }

    #[test]
    fn selector_names_are_case_sensitive() {
        assert!("BUTTON".parse::<Role>().is_err());
    }

    #[test]
    fn aria_names_follow_the_table() {
        assert_eq!(Role::Window.aria_name(), None);
        assert_eq!(Role::Text.aria_name(), None);
        assert_eq!(Role::ToggleButton.aria_name(), Some("button"));
        assert_eq!(Role::Splitter.aria_name(), Some("separator"));
        assert_eq!(Role::Separator.aria_name(), Some("separator"));
        assert_eq!(Role::Image.aria_name(), Some("img"));
        assert_eq!(Role::PasswordInput.aria_name(), None);
    }

    #[test]
    fn role_mismatch_reads_well() {
        let error = RoleMismatch {
            expected: Role::CheckBox,
            found: Role::Button,
        };
        assert_eq!(CheckBox::try_from(Role::Button), Err(error));
        assert_eq!(
            error.to_string(),
            "expected role `checkbox`, found `button`"
        );
    }

    #[test]
    fn any_role_has_no_runtime_role() {
        assert_eq!(<AnyRole as RoleKind>::ROLE, None);
    }

    #[test]
    fn capabilities_set_operations() {
        let both = Capabilities::CHECKABLE | Capabilities::LEVELED;
        assert!(both.contains(Capabilities::CHECKABLE));
        assert!(both.contains(Capabilities::NONE));
        assert!(!both.contains(Capabilities::EDITABLE));
        assert!(Capabilities::default().is_empty());
        assert!(!both.is_empty());
        assert_eq!(both.names().collect::<Vec<_>>(), ["Checkable", "Leveled"]);
        assert_eq!(format!("{both:?}"), r#"{"Checkable", "Leveled"}"#);
        let mut grown = Capabilities::NONE;
        grown |= Capabilities::PRESSABLE;
        assert_eq!(grown, Capabilities::PRESSABLE);
    }

    #[test]
    fn capability_bits_are_distinct() {
        let mut seen = Capabilities::NONE;
        for (capability, _) in Capabilities::NAMED {
            assert!(!seen.contains(*capability));
            seen |= *capability;
        }
    }

    #[test]
    fn interactive_roles_have_a_capability_or_are_click_targets() {
        assert!(Role::Link.is_interactive());
        assert!(Role::ColumnHeader.is_interactive());
        assert!(Role::CheckBox.is_interactive());
        assert!(!Role::Generic.is_interactive());
        assert!(!Role::Scrim.is_interactive());
    }

    #[test]
    fn a_level_or_a_read_only_value_alone_is_not_interactive() {
        assert!(!Role::Heading.is_interactive());
        assert!(!Role::ProgressIndicator.is_interactive());
        assert!(Role::Slider.is_interactive());
        assert!(Role::TextBox.is_interactive());
        assert!(Role::Button.is_interactive());
        for role in Role::ALL {
            let acts = [
                Capabilities::CHECKABLE,
                Capabilities::PRESSABLE,
                Capabilities::EXPANDABLE,
                Capabilities::EDITABLE,
                Capabilities::SELECTABLE,
                Capabilities::SELECTABLE_ITEM,
                Capabilities::RANGE_VALUE,
            ]
            .iter()
            .any(|c| role.capabilities().contains(*c));
            assert_eq!(
                role.is_interactive(),
                acts || role.is_click_target(),
                "{role}"
            );
        }
    }

    // `impls`-style detection: the inherent method wins when the bound holds, otherwise
    // the trait method's `false` is used. Only works on concrete types.
    struct Probe<T>(PhantomData<T>);

    macro_rules! detector {
        ($trait_name:ident, $fallback:ident, $method:ident) => {
            trait $fallback {
                fn $method(&self) -> bool {
                    false
                }
            }
            impl<T> $fallback for Probe<T> {}
            impl<T: $trait_name> Probe<T> {
                fn $method(&self) -> bool {
                    true
                }
            }
        };
    }

    detector!(Checkable, NotCheckable, checkable);
    detector!(Editable, NotEditable, editable);
    detector!(Selectable, NotSelectable, selectable);
    detector!(Expandable, NotExpandable, expandable);
    detector!(RangeValue, NotRangeValue, range_value);
    detector!(Pressable, NotPressable, pressable);
    detector!(HasValue, NotHasValue, has_value);
    detector!(SelectableItem, NotSelectableItem, selectable_item);
    detector!(Leveled, NotLeveled, leveled);

    macro_rules! implemented {
        ($ty:ty) => {{
            let probe = Probe::<$ty>(PhantomData);
            let mut set = Capabilities::NONE;
            for (on, capability) in [
                (probe.checkable(), Capabilities::CHECKABLE),
                (probe.editable(), Capabilities::EDITABLE),
                (probe.selectable(), Capabilities::SELECTABLE),
                (probe.expandable(), Capabilities::EXPANDABLE),
                (probe.range_value(), Capabilities::RANGE_VALUE),
                (probe.pressable(), Capabilities::PRESSABLE),
                (probe.has_value(), Capabilities::HAS_VALUE),
                (probe.selectable_item(), Capabilities::SELECTABLE_ITEM),
                (probe.leveled(), Capabilities::LEVELED),
            ] {
                if on {
                    set |= capability;
                }
            }
            set
        }};
    }

    /// Copied by hand from semantics.md's role table: role type, selector name, ARIA,
    /// AccessKit, capabilities, click target.
    macro_rules! semantics_table {
        ($($ty:ident, $selector:literal, $aria:expr, $accesskit:literal, [$($cap:ident),*], $click:literal;)+) => {
            vec![$((
                Role::$ty,
                <$ty as RoleType>::ROLE_VALUE,
                Role::from($ty),
                $ty::try_from(Role::$ty).is_ok(),
                implemented!($ty),
                $selector,
                $aria,
                $accesskit,
                Capabilities::NONE $(| Capabilities::$cap)*,
                $click,
            )),+]
        };
    }

    #[test]
    fn the_table_matches_semantics_md() {
        let rows = semantics_table! {
            Window, "window", None, "Window", [], false;
            Generic, "generic", Some("generic"), "GenericContainer", [], false;
            Group, "group", Some("group"), "Group", [], false;
            Region, "region", Some("region"), "Region", [], false;
            Navigation, "navigation", Some("navigation"), "Navigation", [], false;
            Toolbar, "toolbar", Some("toolbar"), "Toolbar", [], false;
            Text, "text", None, "Label", [], false;
            Paragraph, "paragraph", Some("paragraph"), "Paragraph", [], false;
            Heading, "heading", Some("heading"), "Heading", [LEVELED], false;
            Image, "img", Some("img"), "Image", [], false;
            Link, "link", Some("link"), "Link", [], true;
            Button, "button", Some("button"), "Button", [EXPANDABLE], true;
            ToggleButton, "togglebutton", Some("button"), "ToggleButton", [PRESSABLE], true;
            CheckBox, "checkbox", Some("checkbox"), "CheckBox", [CHECKABLE], false;
            RadioButton, "radio", Some("radio"), "RadioButton", [CHECKABLE], false;
            RadioGroup, "radiogroup", Some("radiogroup"), "RadioGroup", [SELECTABLE], false;
            Switch, "switch", Some("switch"), "Switch", [CHECKABLE], false;
            TextBox, "textbox", Some("textbox"), "TextInput", [EDITABLE, HAS_VALUE], false;
            SearchBox, "searchbox", Some("searchbox"), "SearchInput", [EDITABLE, HAS_VALUE], false;
            PasswordInput, "password", None, "PasswordInput", [EDITABLE, HAS_VALUE], false;
            ComboBox, "combobox", Some("combobox"), "ComboBox", [EDITABLE, SELECTABLE, EXPANDABLE, HAS_VALUE], false;
            ListBox, "listbox", Some("listbox"), "ListBox", [SELECTABLE], false;
            ListOption, "option", Some("option"), "ListBoxOption", [SELECTABLE_ITEM], true;
            Slider, "slider", Some("slider"), "Slider", [RANGE_VALUE, HAS_VALUE], false;
            SpinButton, "spinbutton", Some("spinbutton"), "SpinButton", [EDITABLE, RANGE_VALUE, HAS_VALUE], false;
            ProgressIndicator, "progressbar", Some("progressbar"), "ProgressIndicator", [HAS_VALUE], false;
            ScrollView, "scrollview", None, "ScrollView", [], false;
            Splitter, "separator", Some("separator"), "Splitter", [RANGE_VALUE, HAS_VALUE], false;
            Separator, "separator-static", Some("separator"), "GenericContainer", [], false;
            Scrim, "scrim", None, "GenericContainer", [], false;
            List, "list", Some("list"), "List", [], false;
            ListItem, "listitem", Some("listitem"), "ListItem", [SELECTABLE_ITEM, LEVELED], true;
            Tree, "tree", Some("tree"), "Tree", [], false;
            TreeItem, "treeitem", Some("treeitem"), "TreeItem", [CHECKABLE, EXPANDABLE, SELECTABLE_ITEM, LEVELED], true;
            Table, "table", Some("table"), "Table", [], false;
            Grid, "grid", Some("grid"), "Grid", [], false;
            Row, "row", Some("row"), "Row", [EXPANDABLE, SELECTABLE_ITEM, LEVELED], true;
            Cell, "cell", Some("cell"), "Cell", [SELECTABLE_ITEM], true;
            ColumnHeader, "columnheader", Some("columnheader"), "ColumnHeader", [], true;
            RowHeader, "rowheader", Some("rowheader"), "RowHeader", [], false;
            TabList, "tablist", Some("tablist"), "TabList", [SELECTABLE], false;
            Tab, "tab", Some("tab"), "Tab", [SELECTABLE_ITEM], true;
            TabPanel, "tabpanel", Some("tabpanel"), "TabPanel", [], false;
            Menu, "menu", Some("menu"), "Menu", [], false;
            MenuBar, "menubar", Some("menubar"), "MenuBar", [], false;
            MenuItem, "menuitem", Some("menuitem"), "MenuItem", [EXPANDABLE], true;
            MenuItemCheckBox, "menuitemcheckbox", Some("menuitemcheckbox"), "MenuItemCheckBox", [CHECKABLE], false;
            MenuItemRadio, "menuitemradio", Some("menuitemradio"), "MenuItemRadio", [CHECKABLE], false;
            Dialog, "dialog", Some("dialog"), "Dialog", [], false;
            AlertDialog, "alertdialog", Some("alertdialog"), "AlertDialog", [], false;
            Tooltip, "tooltip", Some("tooltip"), "Tooltip", [], false;
            Status, "status", Some("status"), "Status", [], false;
            Alert, "alert", Some("alert"), "Alert", [], false;
            Document, "document", Some("document"), "Document", [], false;
            Canvas, "canvas", None, "Canvas", [], false;
            Unknown, "unknown", None, "Unknown", [], false;
        };

        assert_eq!(rows.len(), Role::ALL.len());
        for (
            index,
            (role, value, from, tried, traits, selector, aria, accesskit, capabilities, click),
        ) in rows.into_iter().enumerate()
        {
            assert_eq!(Role::ALL[index], role, "table order");
            assert_eq!(value, role);
            assert_eq!(from, role);
            assert!(tried);
            assert_eq!(role.selector_name(), selector, "{role:?}");
            assert_eq!(role.aria_name(), aria, "{role:?}");
            assert_eq!(role.accesskit_name(), accesskit, "{role:?}");
            assert_eq!(role.capabilities(), capabilities, "{role:?} bits");
            assert_eq!(traits, capabilities, "{role:?} traits");
            assert_eq!(role.is_click_target(), click, "{role:?}");
            assert_eq!(role.type_name(), format!("{role:?}"));
        }
    }

    macro_rules! maps_to_one_variant {
        ($($ty:ident),+ $(,)?) => {{
            let markers: Vec<Role> = vec![$(<$ty as RoleType>::ROLE_VALUE),+];
            for role in Role::ALL {
                let tried = [$($ty::try_from(*role).is_ok()),+];
                assert_eq!(tried.iter().filter(|ok| **ok).count(), 1, "{role:?}");
            }
            markers
        }};
    }

    #[test]
    fn every_marker_maps_to_exactly_one_variant_and_back() {
        let markers = maps_to_one_variant!(
            Window,
            Generic,
            Group,
            Region,
            Navigation,
            Toolbar,
            Text,
            Paragraph,
            Heading,
            Image,
            Link,
            Button,
            ToggleButton,
            CheckBox,
            RadioButton,
            RadioGroup,
            Switch,
            TextBox,
            SearchBox,
            PasswordInput,
            ComboBox,
            ListBox,
            ListOption,
            Slider,
            SpinButton,
            ProgressIndicator,
            ScrollView,
            Splitter,
            Separator,
            Scrim,
            List,
            ListItem,
            Tree,
            TreeItem,
            Table,
            Grid,
            Row,
            Cell,
            ColumnHeader,
            RowHeader,
            TabList,
            Tab,
            TabPanel,
            Menu,
            MenuBar,
            MenuItem,
            MenuItemCheckBox,
            MenuItemRadio,
            Dialog,
            AlertDialog,
            Tooltip,
            Status,
            Alert,
            Document,
            Canvas,
            Unknown,
        );
        assert_eq!(markers, Role::ALL);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn roles_serialise_as_selector_names_and_unknown_names_become_unknown()
    -> Result<(), serde_json::Error> {
        for role in Role::ALL {
            let json = serde_json::to_string(role)?;
            assert_eq!(json, format!("\"{}\"", role.selector_name()));
            assert_eq!(serde_json::from_str::<Role>(&json)?, *role);
        }
        assert_eq!(serde_json::from_str::<Role>("\"hologram\"")?, Role::Unknown);
        assert_eq!(serde_json::from_str::<Role>("\"Label\"")?, Role::Text);
        assert_eq!(serde_json::to_string(&Button)?, "null");
        Ok(())
    }
}