Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Linux Accessibility (AT-SPI)

Screen readers such as Orca, magnifiers and switch-access tools on Linux learn what is on screen through AT-SPI, a D-Bus service that applications publish their user interface to. Every application is a tree of accessible objects, each with a Role (button, text field, menu item), a name a screen reader reads aloud, and a set of States (focused, checked, disabled). The atspi crate connects to that bus with AccessibilityConnection and talks to each object through an AccessibleProxy.

These recipes run on a Linux desktop with accessibility enabled (GNOME and KDE turn it on when an assistive technology runs; gsettings set org.gnome.desktop.interface toolkit-accessibility true turns it on for GTK applications).

This recipe requires the macros and rt-multi-thread feature flags of tokio to be enabled in Cargo.toml.

List the applications on the accessibility bus

atspi tokio Accessibility

The registry’s root object has one child per application that publishes its user interface. ObjectRefExt::as_accessible_proxy turns each child reference into a proxy, which reads the application’s name and how many windows it has.

use anyhow::Result;
use atspi::AccessibilityConnection;
use atspi::proxy::accessible::ObjectRefExt;

#[tokio::main]
async fn main() -> Result<()> {
    let a11y = AccessibilityConnection::new().await?;

    // Every application that supports accessibility is a child of the registry's root.
    let root = a11y.root_accessible_on_registry().await?;
    for app in root.get_children().await? {
        let app = app.as_accessible_proxy(a11y.connection()).await?;
        let name = app.name().await?;
        let windows = app.child_count().await?;
        if name.is_empty() {
            println!("(unnamed), {windows} window(s)");
        } else {
            println!("{name}, {windows} window(s)");
        }
    }
    Ok(())
}

atspi tokio Accessibility

This is what a screen reader knows about an application: each object’s role, name and the states a user cares about. The walk skips objects without the Showing state, such as closed menus, just as a screen reader does. Run it with the application’s name from the previous recipe, such as cargo run --bin dump_tree gedit.

use anyhow::{Context, Result, bail};
use atspi::proxy::accessible::ObjectRefExt;
use atspi::{AccessibilityConnection, ObjectRefOwned, State, StateSet};
use std::env;

/// Stop after this many objects, in case an application exposes a very large tree.
const MAX_OBJECTS: usize = 2000;

#[tokio::main]
async fn main() -> Result<()> {
    let wanted = env::args()
        .nth(1)
        .context("usage: dump_tree <application name>")?;
    let a11y = AccessibilityConnection::new().await?;
    let conn = a11y.connection();
    let app = find_application(&a11y, &wanted).await?;

    // Depth-first, so each object is printed under its parent.
    let mut stack = vec![(app, 0)];
    let mut visited = 0;
    while let Some((object, depth)) = stack.pop() {
        visited += 1;
        if visited > MAX_OBJECTS {
            println!("... stopped after {MAX_OBJECTS} objects");
            break;
        }
        let node = object.as_accessible_proxy(conn).await?;
        let states = node.get_state().await?;
        // Skip what is not on screen, such as closed menus: a screen reader skips it too.
        if depth > 0 && !states.contains(State::Showing) {
            continue;
        }
        let role = node.get_role().await?;
        let name = node.name().await?;
        // The application object itself has no meaningful states (it is never "sensitive").
        let states = if depth == 0 {
            String::new()
        } else {
            notable_states(states)
        };
        println!("{:indent$}{role} {name:?}{states}", "", indent = depth * 2);
        let children = node.get_children().await?;
        stack.extend(children.into_iter().rev().map(|child| (child, depth + 1)));
    }
    Ok(())
}

/// Finds a running application by its accessible name, ignoring case.
async fn find_application(a11y: &AccessibilityConnection, wanted: &str) -> Result<ObjectRefOwned> {
    let root = a11y.root_accessible_on_registry().await?;
    for app in root.get_children().await? {
        let name = app
            .as_accessible_proxy(a11y.connection())
            .await?
            .name()
            .await?;
        if name.eq_ignore_ascii_case(wanted) {
            return Ok(app);
        }
    }
    bail!("no application named {wanted:?} on the accessibility bus")
}

/// The states a user cares about, such as ` [focusable, checked]`, or nothing.
fn notable_states(states: StateSet) -> String {
    let mut shown: Vec<String> = [
        State::Focusable,
        State::Focused,
        State::Checked,
        State::Editable,
    ]
    .into_iter()
    .filter(|state| states.contains(*state))
    .map(|state| state.to_string())
    .collect();
    if !states.contains(State::Sensitive) {
        shown.push("disabled".into());
    }
    if shown.is_empty() {
        String::new()
    } else {
        format!(" [{}]", shown.join(", "))
    }
}

Find controls a screen reader cannot name

atspi tokio Accessibility

An icon button without an accessible name is announced as just “button”, so a screen reader user cannot tell what it does. This audit walks the controls on screen and reports every button, field, tab or link that has neither a name nor a label pointing at it through a RelationType::LabelledBy relation. It exits with an error when it finds any, so it can run as a check in CI, such as cargo run --bin audit_labels gedit.

use anyhow::{Context, Result, bail};
use atspi::proxy::accessible::{AccessibleProxy, ObjectRefExt};
use atspi::{AccessibilityConnection, ObjectRefOwned, RelationType, Role, State, StateSet};
use std::env;

/// Stop after this many objects, in case an application exposes a very large tree.
const MAX_OBJECTS: usize = 5000;

#[tokio::main]
async fn main() -> Result<()> {
    let wanted = env::args()
        .nth(1)
        .context("usage: audit_labels <application name>")?;
    let a11y = AccessibilityConnection::new().await?;
    let conn = a11y.connection();
    let app = find_application(&a11y, &wanted).await?;

    let mut problems = 0;
    let mut stack = vec![(app, String::new())];
    let mut visited = 0;
    while let Some((object, path)) = stack.pop() {
        visited += 1;
        if visited > MAX_OBJECTS {
            println!("... stopped after {MAX_OBJECTS} objects");
            break;
        }
        let node = object.as_accessible_proxy(conn).await?;
        let states = node.get_state().await?;
        if !path.is_empty() && !states.contains(State::Showing) {
            continue;
        }
        let role = node.get_role().await?;
        let name = node.name().await?;
        let path = if path.is_empty() {
            describe(role, &name)
        } else {
            format!("{path} > {}", describe(role, &name))
        };

        // A screen reader can only say "button" for a control with no name and no label.
        if is_interactive(role, states)
            && name.trim().is_empty()
            && !has_label(&a11y, &node).await?
        {
            problems += 1;
            println!("unlabeled {role}: {path}");
        }

        let children = node.get_children().await?;
        stack.extend(
            children
                .into_iter()
                .rev()
                .map(|child| (child, path.clone())),
        );
    }

    if problems > 0 {
        bail!("{problems} control(s) have no accessible name");
    }
    println!("Every control on screen has an accessible name.");
    Ok(())
}

/// Controls a user operates, which a screen reader has to announce by name.
fn is_interactive(role: Role, states: StateSet) -> bool {
    // GTK 4 reports text fields as editable `text` rather than `entry`.
    (role == Role::Text && states.contains(State::Editable))
        || matches!(
            role,
            Role::Button
                | Role::ToggleButton
                | Role::CheckBox
                | Role::RadioButton
                | Role::ComboBox
                | Role::Entry
                | Role::PasswordText
                | Role::SpinButton
                | Role::Slider
                | Role::Link
                | Role::MenuItem
                | Role::PageTab
        )
}

/// Whether another object with text, such as a label next to an entry, labels this one.
/// A label with no text does not count: the screen reader still has nothing to say.
async fn has_label(a11y: &AccessibilityConnection, node: &AccessibleProxy<'_>) -> Result<bool> {
    for (relation, targets) in node.get_relation_set().await? {
        if relation != RelationType::LabelledBy {
            continue;
        }
        for label in targets {
            let text = label
                .as_accessible_proxy(a11y.connection())
                .await?
                .name()
                .await?;
            if !text.trim().is_empty() {
                return Ok(true);
            }
        }
    }
    Ok(false)
}

fn describe(role: Role, name: &str) -> String {
    if name.is_empty() {
        role.to_string()
    } else {
        format!("{role} {name:?}")
    }
}

/// Finds a running application by its accessible name, ignoring case.
async fn find_application(a11y: &AccessibilityConnection, wanted: &str) -> Result<ObjectRefOwned> {
    let root = a11y.root_accessible_on_registry().await?;
    for app in root.get_children().await? {
        let name = app
            .as_accessible_proxy(a11y.connection())
            .await?
            .name()
            .await?;
        if name.eq_ignore_ascii_case(wanted) {
            return Ok(app);
        }
    }
    bail!("no application named {wanted:?} on the accessibility bus")
}

Announce the focused control like a screen reader

atspi tokio Accessibility

A screen reader speaks whatever receives keyboard focus. Registering for StateChangedEvent asks applications to report state changes, and the event stream from AccessibilityConnection::event_stream delivers them; read with StreamExt::next, each one that turns Focused on is announced with the object’s name and role. Press Tab in any application to hear it.

use anyhow::Result;
use atspi::events::object::StateChangedEvent;
use atspi::proxy::accessible::ObjectRefExt;
use atspi::{AccessibilityConnection, Event, ObjectEvents, Role, State};
use futures_util::StreamExt;
use std::pin::pin;

#[tokio::main]
async fn main() -> Result<()> {
    let a11y = AccessibilityConnection::new().await?;
    // Ask applications to send state changes; focus is one of them.
    a11y.register_event::<StateChangedEvent>().await?;
    let mut events = pin!(a11y.event_stream());

    println!("Move the keyboard focus in any application. Press Ctrl+C to stop.");
    while let Some(event) = events.next().await {
        let Ok(Event::Object(ObjectEvents::StateChanged(change))) = event else {
            continue;
        };
        if change.state != State::Focused || !change.enabled {
            continue;
        }
        // The object can be gone by the time we ask about it, such as a closed menu.
        let Ok(object) = change.item.as_accessible_proxy(a11y.connection()).await else {
            continue;
        };
        if let (Ok(role), Ok(name)) = (object.get_role().await, object.name().await) {
            println!("{}", announcement(role, &name));
        }
    }
    Ok(())
}

/// What a screen reader says when focus lands on an object, such as `Save, button`.
fn announcement(role: Role, name: &str) -> String {
    if name.trim().is_empty() {
        format!("unlabeled {role}")
    } else {
        format!("{name}, {role}")
    }
}