JFLib

19. Accessibility (screen readers)#

Every semantic record of a frame (sem(), section 12's dump) becomes a node of the accessibility tree that screen readers read: AT-SPI2 on Linux (Orca), UI Automation on Windows (Narrator, NVDA), NSAccessibility on macOS and UIAccessibility on iOS (VoiceOver), an ARIA shadow tree in the DOM in the browser (NVDA / JAWS / VoiceOver with the browser), an AccessibilityNodeProvider on Android (TalkBack). Nothing has to be switched on: the first window frame starts the bridge. Linux connects to the accessibility bus only when assistive technology is enabled (org.a11y.Status; jfgui_A11Y=1 forces it), Windows answers WM_GETOBJECT, macOS the first question an assistive technology asks a window, iOS follows VoiceOver's and Switch Control's switches (and a question to its view), Android follows the system's accessibility switch, the browser cannot tell and always keeps the shadow tree (?a11y=0 in the page address leaves it out); everywhere the UI builds the tree only while a client listens. jfgui_A11Y=0 (or NO_AT_BRIDGE=1) turns it off. Headless runs have no bridge.

What the built-in widgets report (role on AT-SPI / UI Automation, the name, state and value, the actions a screen reader can take):

WidgetRoleNameState, valueActions
textlabel / Textthe text
heading, the headings of markdown_view / html_view (K_HEADING)heading / Text with HeadingLevelthe textthe level
button, icon_button, tool_button, toggle_button, cmd_buttonpush button / Buttonthe label (icon buttons: their tooltip label)pressed when checkedclick / Invoke
checkboxcheck box / CheckBoxthe labelchecked, mixed (value 2)toggle
radioradio button / RadioButtonthe labelchecked (selected)select
switchtoggle button / Button + Togglethe labelcheckedtoggle
slider, track_slider, slider_f, prop_sliderslider / Sliderthe property label, else the text before itvalue, min, maxset the value
progressprogress bar / ProgressBarthe text before itvalue of max
textbox, number_boxentry / Editthe text before itthe text, the caret and its rectangle, the selectionset the text, the caret / selection
comboboxcombo box / ComboBoxthe text before itthe choice, openopen / close
tabs, segmented stripspage tab list + page tabs / Tab + TabItemthe tab labelsselectedselect
list_begin .. list_itemlist box + list items / List + ListItemthe row labelsselectedselect
menubar, menus, popupsmenu bar, menu, menu itemthe labelsopen, checkedclick / expand
dialog_begindialog / Panethe title
linklink / Hyperlinkthe labelclick
colour swatchespush button / Button#RRGGBBclick
titled boxes (notifications, info bars)panel / Groupthe title

Headings (heading(level, ..), the headings of the document view; records K_HEADING with the level as value, Role::Heading with Node::level()) are headings on every platform, so heading navigation finds them (H / 1 .. 6 in the browse modes of NVDA, JAWS and Orca, Narrator's headings, TalkBack's heading navigation): UI Automation a Text element with HeadingLevel1 .. 9 (plus AriaRole heading and AriaProperties level=N; a new level raises the property change), AT-SPI2 the role heading with the object attribute level:N (GetAttributes; a new level: object:attributes-changed), the browser role="heading" with aria-level, Android setHeading(true) (API 28 and later; API 26 / 27 the heading flag of a CollectionItemInfo, which isHeading() and TalkBack read there) -- Android has no heading level. A text box, drop-down, slider, progress bar or list without a label right after a heading takes its name from it, as from a text.

Every node has its rectangle; disabled widgets (ST_DISABLED, disabled_push) report it and take no actions, and nothing behind a modal dialog can be acted on. The focus is the focused widget's (a focused list or tab strip passes it on to its selected row / tab). Changes go out as events: focus, checked / selected / open / enabled, names (a label whose text changes), values, texts, added and removed nodes. A screen reader's click, toggle, select or open acts like Space on the focused widget (EV_ACT from behave); a new slider value or text goes through the widget like typed input (EV_ACT, plus EV_COMMIT for texts and the value sliders).

Widgets of your own need one thing: after behave (or hit_rect), a sem() record with the same id, the kind that says what it is, and a label that names it:

let r = ui.place(ui.dp(120), ui.dp(28));
let ev = ui.hit_rect(ID_GRID, r[0], r[1], r[2], r[3], HB_FOCUS);
if ev & EV_ACT != 0 {
    self.grid = !self.grid; // a click, Space, or a screen reader's "toggle"
}
// ... draw it ...
let rec = ui.sem(K_CHECKBOX, ID_GRID, Some("Raster"), self.grid as i32);
if self.grid {
    rec.state |= SS_CHECKED;
}
  • Use the id you gave behave: then a screen reader's click arrives as EV_ACT. A record with another id gets a pointer click in its middle instead, after a scroll view brought it into view, and none when something else lies there.

  • Name every control: icon-only buttons through their label, drawings through the label of their K_CANVAS record. Text boxes, sliders, drop-downs, progress bars and lists without a label take the text (or heading) record directly before them -- put text(TS_BODY, "Name") to the left in the same row, or directly above with the same left edge.

  • Section titles: heading(2, TS_SUBTITLE, "Konto") instead of text -- or a K_HEADING record with the level as value for a title a widget of your own draws.

  • States the kind does not imply go into the returned record (state |= SS_CHECKED, SS_SELECTED, SS_OPEN); a slider-like widget sets rec.min / rec.max and applies ui.a11y_value(id) (a text widget ui.a11y_text(id)) when a screen reader sets a value.

  • Records without area (hidden probe records) are left out.

  • Content drawn inside a canvas (the links, headings and images of a web page an engine draws, the shapes of a diagram): ui.sem_rect(kind, id, rect, label, value) after the canvas adds a record at rect (px of the window, as last_rect) without a hit box of its own and without touching last_rect. Screen readers read it with the role of its kind (K_LINK, K_HEADING with the level as value, K_IMAGE, K_TEXT, K_BUTTON, K_LIST / K_LISTITEM ...), a script finds it by its label, and a click on it -- the script's click "Label", a screen reader's -- is a press in its middle, so it reaches the canvas as any click does. Publish what is visible, every frame:

    let inp = ui.canvas(ID_PAGE, Some(d), 0, self.ver).clone();
    for l in self.page.visible_links() {                     // rectangles relative to the page
        let r = [inp.rect[0] + l.x, inp.rect[1] + l.y, l.w, l.h];
        ui.sem_rect(K_LINK, 0, r, Some(&l.text), 0);
    }

    Tables, landmarks, trees and the rest of a web page's tree have kinds of their own, and a record can say much more than kind, label and value: "A web page's tree" below. The canvas's own record (K_CANVAS) has no name unless ui.canvas_label("Webseite") comes right before ui.canvas: then a screen reader says it and a script finds it as canvas:"Webseite".

Screen magnifiers follow the focus and the text caret. Text boxes report their caret (ime_pos, which a text widget of your own calls with its caret's rectangle, like the IME): the node of a focused text box carries the caret offset, the selection and the caret's rectangle (Node::caret_rect, char_rect(k): exact at the caret, estimated elsewhere). Windows: a hidden system caret sits in the window with the keyboard (Magnifier, ZoomText: GetGUIThreadInfo, the caret's location events), and the Text / Text2 patterns serve the text, its ranges, GetCaretRange and the selection (NVDA, Narrator, Magnifier); a moved caret raises TextSelectionChanged. Linux: CaretOffset, GetCharacterExtents (screen coordinates), object:text-caret-moved -- also when a text box gets the focus -- for Orca and GNOME's zoom; SetCaretOffset / SetSelection move the caret.

VoiceOver on the Mac and the iPhone reads the tree in the app's own process (lib/plat/apple_mac_a11y.rs, apple_ios_a11y.rs): every node is an accessibility element of its own that stays the same while its widget does. On macOS the window's view is no element itself, so the nodes hang directly on the window: roles and subroles (a switch is a check box with the subrole AXSwitch, a tab a radio button with AXTabButton, a heading AXHeading with its level as value, a password box AXSecureTextField), names as title, description or value as AppKit's own controls have them, values, the focus, frames, press, increment / decrement (5 % of a slider's range, as on Android), setting values, the focus and a selection; text boxes answer the text attributes (characters, lines, the insertion point, the selection, the rectangle of a range: VoiceOver reads by character and word and follows the caret). Notifications: focus, values, titles, a list's selection, layout, popup menus opening and closing; dialog windows are AXDialog. On iOS the nodes are the elements of the host's view: lists, tab strips (a tab bar), dialogs, menus and titled boxes are containers, everything else an element with its traits (header, button, selected, adjustable, not enabled, toggle button for a switch from iOS 17); a double tap clicks, swiping up or down on a slider sets it, VoiceOver's Escape gesture presses Escape, and each of them runs a frame at once so that VoiceOver reads the new state. Text boxes and the view are UITextInput: VoiceOver reads and moves in the text, the keyboard sees the text around the caret and composes into the preedit. The app menus in the macOS menu bar are real NSMenus, which VoiceOver reads without the tree.

The browser and Android keep a mirror of the tree: after every frame the library sends the differences to the tree the host has (plat::a11y::wire: new and changed nodes, the order when nodes came or went, the events) -- in the browser from the WASM worker to the page, on Android to the Java host after the frame. The page (web/a11y.js) lays one transparent element per node over the canvas at the node's rectangle (no pointer events, opacity: 0, still in the browser's accessibility tree); Android (android/GalleryAccessibility.java) serves virtual views with their bounds on the screen:

NodeBrowser (ARIA / element)Android (class)
labeltextTextView
button (pressed: toggle)button (aria-pressed)Button / ToggleButton
check box, radio button, switchcheckbox, radio, switch (aria-checked, mixed)CheckBox, RadioButton, Switch
slider<input type=range>SeekBar (range info)
progress barprogressbar (aria-valuenow)ProgressBar (range info)
text box<input> / <textarea> (password: type=password) with the text and the selectionEditText (text, hint = name, selection, multi-line, password)
list, rowlistbox, option (aria-selected)ListView, TextView (selected)
menu bar, menu, entrymenubar, menu / menuitem (aria-haspopup, aria-expanded)Button / ListView, TextView
tab strip, tabtablist, tabTabWidget, TextView (selected)
drop-downcombobox (the choice, aria-expanded; its open list: aria-controls)Spinner
image, drawingimgImageView
dialog, windowdialog (aria-modal), the main window a regionViewGroup with its pane title

In the browser the DOM focus follows the app's focus as soon as the keyboard (Tab, arrows) or a screen reader drives it; a pointer on the canvas gives the keyboard back to the hidden text area that serves typing and the IME. Keys, typed text, the IME and paste reach the app the same way from either; a screen reader's click, a focus it moves, a range input it sets, a text it replaces and a selection it moves in a text field become the actions above. On Android TalkBack's accessibility focus, explore by touch (hover), click, focus, set progress / scroll a slider, set text and set selection work on the virtual views, and the app sends the events TalkBack speaks (focus, text changed, selection changed, state and value changes, a dialog appearing).

Testing: ui.a11y_tree() returns the tree as the bridges serve it (headless, e.g. through ui::Runtime); plattest --test a11y checks the mapping, the actions, the caret and the browser's / Android's update format, tools/platshared/atspi_bus.py the AT-SPI2 bridge in WSL (a fake bus, and with --real at-spi2-core through libatspi; both follow the caret), plattest --test uia the UI Automation providers through IUIAutomation and plattest --test caret the caret alone: system caret and TextPattern2 (Windows, a window for a few seconds), plattest --test a11y-mac the NSAccessibility elements as AppKit serves them to VoiceOver (a real window: python3 tools/apple.py gui build/mac/plattest --test a11y-mac), plattest --test a11y-ios the UIAccessibility elements and UITextInput under UIKit in the simulator (tools/apple.py simapp build/ios-sim/plattest --test a11y-ios), and plattest --test a11y-show shows the demo for a probe by hand with a screen reader. node apps/androidGallery/tests/a11y_web.mjs build checks the shadow tree of the androidGallery web build in Chromium (Chromium's own accessibility tree through the DevTools protocol, clicks, values, Tab, typing, selections; Playwright through tools/tests/playwright.mjs), and the debug APK's GalleryA11yInstrumentation the Android provider through UiAutomation, the client side TalkBack uses (adb shell am instrument -w -r org.jflib.gallery/.GalleryA11yInstrumentation). Each of them also checks a heading and its level (the demo's heading(2, ..), the gallery's section titles).

A web page's tree (rich records)#

A browser engine (or any content an app draws itself) has an accessibility tree of its own: tables, landmarks, trees, live regions, descriptions, form states, content out of view. The app publishes it with sem_rect as above and says the rest through setters on the returned record; each returns the record, so they chain:

let page = ID_PAGE as u64; // the canvas's widget id: the page's top nodes hang under it
for n in tree.nodes.iter().filter(|n| ui.a11y_active() || !n.offscreen) {
    let r = [view[0] + n.rect.x, view[1] + n.rect.y, n.rect.width, n.rect.height];
    let rec = ui.sem_rect(kind_of(n.role), 0, r, Some(n.label()), value_of(n));
    rec.id64(n.id.get()).parent(n.parent.map_or(page, |p| p.get()));
    if !n.description.is_empty() { rec.desc(&n.description); }
    if let Some(c) = n.cell { rec.cell(c.row, c.column).span(c.row_span, c.column_span); }
    if let Some((pos, size)) = n.set { rec.set_pos(pos, size); }
    if n.offscreen { rec.states(AS_OFFSCREEN); }
    if n.states.contains(AxStates::REQUIRED) { rec.states(AS_REQUIRED); }
    // ... name (a text box's), url, level, live, range, value_text, text_sel
}
while let Some(q) = ui.a11y_request_take() {     // a screen reader acts on a node
    engine.act(AxNodeId::from_raw(q.id), action_of(q.action));
}

Kinds. Beside the kinds of section 12 (K_LINK, K_HEADING, K_TEXTBOX, K_LIST ...):

Kind (value)UI AutomationAT-SPI2Browser (ARIA)Bridges without it (Apple until the VoiceOver bridge maps them; Android's class, with the extras below)
K_TABLE (grid: .grid(rows, cols))Table + Grid, Table, Selectiontable + Tabletable (aria-rowcount / colcount)group
K_ROWDataItemtable rowrowgroup
K_CELL (.cell(row, col), .span)DataItem + GridItem, TableItemtable cell + TableCellcell (aria-rowindex / colindex, spans)label
K_COLHEADER, K_ROWHEADERHeaderItem + GridItem, TableItemcolumn header, row header + TableCellcolumnheader, rowheaderlabel
K_LANDMARK (value LM_BANNER, LM_MAIN, LM_NAVIGATION, LM_COMPLEMENTARY, LM_CONTENTINFO, LM_SEARCH, LM_FORM, LM_REGION)Group with LandmarkType Main, Navigation, Search, Form, else Custom with LocalizedLandmarkTypelandmark (form: form), attribute xml-rolesbanner, main, navigation, complementary, contentinfo, search, form, regiongroup
K_TREE, K_TREEITEM (.level(n), AS_COLLAPSED / SS_OPEN)Tree, TreeItem + ExpandCollapse, SelectionItemtree, tree item (attribute level)tree, treeitem (aria-level, aria-expanded)list, list item
K_RADIOGROUPGroup ("radio group")panel, xml-roles radiogroupradiogroupgroup
K_TOOLBAR, K_TOOLTIP, K_SEPARATORToolBar, ToolTip, Separatortool bar, tool tip, separatortoolbar, tooltip, separatorgroup, label, group
K_ALERT, K_STATUS, K_LOG (live regions)Text or Group ("alert", "log"), StatusBar; LiveSetting; SystemAlert when an alert appearsnotification, status bar, log; attribute livealert, status, log (aria-live)label
K_METERProgressBar ("meter")level bar + Valuemeterprogress bar
K_SPIN, K_SCROLLBARSpinner, ScrollBar + RangeValuespin button, scroll bar + Value<input type=number>, scrollbarslider
K_ARTICLE, K_FIGUREGroup ("article", "figure")article, panel (xml-roles figure)article, figuregroup

Every one of them names itself in the UI language where the platform has no name of its own (plat::a11y::SUB_TEXTS, sub_name); scripts select them as table:"Preise", cell:"12,50 €" ... (kind_name). The platforms tell no more apart: a grid is a table with selectable rows or cells (AS_SELECTABLE, AS_MULTISELECT), a tree grid a table, a search box a text box, a timer or marquee a status, a group or row group a K_BOX with a label (without one it is left out and passes its children on to its parent).

Setters (Sem; the record's SemAx, only allocated for records that use them):

SetterWhat it saysUIA / AT-SPI2 / ARIA
id64(id)its own id (below 2^62): its node keeps it, parents name it, its requests come back to the appAutomationId / object path / data-key
parent(id)it hangs under the record of that id64 (else that widget id) in the same frame and window, whatever the rectangles saythe tree
name("Suche")the name beside the label (a text box's or drop-down's label is its text)Name
desc("..")a descriptionFullDescription, HelpText / Description / aria-description
url("https://..")a link's addressValue / Hyperlink / --
value_text("Montag"), range(v, min, max, step)a value's text, a value with fractions-- , RangeValue / Value / aria-valuetext, aria-valuenow
states(AS_*)required, invalid, busy, has a popup, visited, modal, multi-select, collapsed, off screen, focusable, clickable, selectable, read-only, multi-line, passwordIsRequiredForForm, IsDataValidForForm, AriaProperties ... / the states / aria-required ...
set_pos(pos, size), level(n)its place in a set, its levelPositionInSet, SizeOfSet, Level / posinset, setsize, level / aria-posinset ...
cell(row, col), span(rows, cols), grid(rows, cols)a cell's place, a table's sizeGrid, GridItem, Table, TableItem / Table, TableCell / aria-rowindex ...
live(LIVE_*), text_sel(anchor, caret)how a live region speaks (LIVE_OFF: not at all); a page field's selectionLiveSetting / live / aria-live; the text patterns

Parents. Without parent a record hangs by its rectangle (the smallest container around its centre), which nests positioned and overlapping web content wrongly. With it the tree follows the engine's: a parent that is not published passes its children on to its own parent (left-out records with an id64), an unknown id or a loop leaves the record to its rectangle.

Out of view. Records of content outside the view (AS_OFFSCREEN, their rectangle where the content lies, outside the canvas) are nodes like the others: browse modes (Narrator's scan mode, the virtual buffers of NVDA and JAWS, Orca) reach them, the pointer and GetAccessibleAtPoint do not, UIA reports IsOffscreen and AT-SPI2 no "showing". They cost what any record costs: a record of at most 4 KB text per field (SEMS_MAX 65 536 records a frame), the tree is built only while a client listens. Publish them only while ui.a11y_active() says one does (it turns true with a frame of its own; on Windows false again 10 s after the last question of a UI Automation client, unless a screen reader -- one that says it runs, SPI_GETSCREENREADER: Narrator, NVDA, JAWS -- or Magnifier listens for events: a client that only listens, as the touch keyboard's host TextInputHost always does on Windows 11, keeps nothing on). The app gets the command UIC_A11Y when it flips (arg 1: a client came, 0: it left), also while it is idle: the window loop looks by itself. A frame whose records, windows and carets equal those of the tree published last publishes nothing (the key of its inputs is compared, not the tree built): a page that does not move costs its records, not the tree.

Requests. A screen reader's actions on a record with an id64 come back to the app, not to a widget: ui.a11y_request_take() -> Option<A11yRequest { win, id, action }> in every frame (win: the window's id, 0 the main window; at most 64 wait). A11yAction is Focus, Click, ScrollIntoView, Expand, Collapse, Increment, Decrement, SetValue(f64), SetText(String), SelectText(anchor, caret), Select, AddToSelection, RemoveFromSelection; a disabled record or one behind a modal dialog gets only ScrollIntoView. Where they come from: UI Automation SetFocus, Invoke, Toggle, ScrollItem, ExpandCollapse, Value / RangeValue, the text patterns, SelectionItem (Select / AddToSelection / RemoveFromSelection); AT-SPI2 GrabFocus, the actions click / expand / collapse / increment / decrement, Component.ScrollTo, Value, EditableText, Text's caret and selection, Selection on the container; the browser the DOM's click, focus (a node out of view is scrolled in first), the input of a range or number field, text and selection edits. Records without an id64 keep the widget paths (EV_ACT, a11y_value, a11y_text). An app's own tests build requests with A11yRequest::new(win, id, action).

Announcements and live regions. ui.announce("Gespeichert", LIVE_POLITE) (or LIVE_ASSERTIVE) is said with this frame's tree: UI Automation's notification event (Windows 10 1709 and later), AT-SPI2's Announcement (Orca 45 and later), the shadow tree's live region in the browser. A record of K_ALERT (assertive), K_STATUS or K_LOG (polite), or one with .live(..), is a live region: a changed name, text or value inside it, or a node that comes or goes, raises LiveRegionChanged (UIA), an Announcement with its text (AT-SPI2) or is the browser's own aria-live; nothing while it is AS_BUSY, and a polite region says nothing of its first content. An app that gets the announcements from elsewhere (a web engine's) calls ui.announce with them and gives its region records .live(LIVE_OFF), so nothing is said twice.

Scripts act and look as a screen reader does: a11y click|focus|scroll|expand|collapse| increment|decrement|select|add|remove S, a11y value S N, a11y text S "s", a11y selecttext S A C; a11y expect S role cell (the Sub's ARIA name or the role's), name "s", desc "s", url "s", level N, set POS SIZE, cell ROW COL, grid ROWS COLS, live polite, is offscreen, not collapsed, can expand, parent S2, children N, missing; a11y expect announced "s" (headless runs keep what ui.announce said); a11y dump prints the tree (a node per line: role, name, text, description, address, a value with its range and text, states, set, cell, live). expect S unfocused | unselected | closed complete the states.

Testing: apps/a11ytest shows such a page (its src/page.rs: landmarks, a table with headers, a tree, a form, live regions, a meter, a spin button, a scroll bar, an article and a figure out of view); plattest --test a11y-rich reads it headless (kinds, fields, parents, out of view, requests, live changes, the rich update format), plattest --test uia-rich through IUIAutomation (Windows), python3 tools/platshared/atspi_bus.py --rich through AT-SPI2 (WSL), and node apps/a11ytest/tests/a11y_web.mjs build in Chromium after build_rs.py app a11ytest --target web. The browser's host and Android's read the rich update format (a11y_wire::VERSION2, jfgui_a11y(2)). Android shows tables as collections (their cells and headers with their place, TalkBack's table navigation), trees as hierarchical collections with expand / collapse, the place in a set, descriptions (hint text), a link's address, invalid fields, live regions (setLiveRegion; a change inside one is reported on the region) and announcements (announceForAccessibility), and takes the further actions (show on screen, expand / collapse, increment / decrement, select); landmarks, tool bars, articles and the other kinds without an Android class stay groups.

Source: docs/GUIDE.md in the JFLib repository.