Truly independent web browser
/*
* Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include "AccessibilityInterface.h"
#include "WebContentView.h"
#include <AK/Utf8View.h>
#include <AK/Vector.h>
#include <LibWebCommon/WebView/AccessibilityNodeData.h>
#include <LibWebView/AccessibilityTreeManager.h>
#include <QAccessible>
#include <QWidget>
namespace Ladybird {
// Factory function — Qt calls this to get the accessible interface for any QObject.
QAccessibleInterface* accessibility_factory(QString const& class_name, QObject* object)
{
if (class_name == QStringLiteral("Ladybird::WebContentView")) {
if (auto* view = qobject_cast<WebContentView*>(object))
return new WebContentViewAccessible(view);
}
return nullptr;
}
// WebContentViewAccessible bridges WebContentView into the Qt accessibility tree.
WebContentViewAccessible::WebContentViewAccessible(WebContentView* view)
: QAccessibleWidget(view, QAccessible::Grouping)
{
}
int WebContentViewAccessible::childCount() const
{
auto* view = static_cast<WebContentView*>(widget());
if (!view || !view->m_accessibility_manager || view->m_accessibility_manager->is_empty())
return 0;
return 1; // The document root.
}
QAccessibleInterface* WebContentViewAccessible::child(int index) const
{
if (index != 0)
return nullptr;
auto* view = static_cast<WebContentView*>(widget());
if (!view || !view->m_accessibility_manager)
return nullptr;
auto const* root = view->m_accessibility_manager->root();
if (!root)
return nullptr;
return view->accessibility_interface_for_node(root->id);
}
QAccessibleInterface* WebContentViewAccessible::focusChild() const
{
auto* root_child = child(0);
if (!root_child)
return nullptr;
return root_child->focusChild();
}
int WebContentViewAccessible::indexOfChild(QAccessibleInterface const* iface) const
{
auto* root_child = child(0);
if (root_child && root_child == iface)
return 0;
return -1;
}
QAccessible::Role WebContentViewAccessible::role() const
{
return QAccessible::Grouping;
}
static bool is_ignored_role(StringView role, String const& name)
{
// Generic containers without a name (div, span, etc.) add no meaning — and cluttering Orca's tree with them hurts
// navigation. Paragraphs must *not* be ignored: Orca relies on the PARAGRAPH role being present in the AT-SPI2 tree
// for is_text_block_element() and for sentence-extension logic during Say All. If we ignore paragraphs, their
// text-leaf children bubble up and Orca sees them as Role.LABEL — which isn't a text_block_element — and sentence
// extension then walks across paragraph boundaries undesirably pulling in everything up to the nearest heading.
return role == "generic"sv && name.is_empty();
}
// An ARIA grid or treegrid is a table to the AT, as a table element is: Blink's IsTableLike() and WebKit's
// isTableRole() take grid and treegrid along with table, and Gecko's role map types both eTable. Qt has no tree-table
// role (QAccessible::Role), so a treegrid is a Table here too, where WebKit and Gecko give AT-SPI a tree table.
static bool is_table_container_role(StringView role)
{
return role == "table"sv || role == "grid"sv || role == "treegrid"sv;
}
// A text control holds its own text (its value) rather than text-leaf children: an input or a textarea (role textbox
// or searchbox), a password field, or a combobox the user can type into.
static bool is_text_control(WebView::AccessibilityNodeData const& data)
{
auto role = data.role.bytes_as_string_view();
return role == "textbox"sv || role == "searchbox"sv || data.is_password
|| (role == "combobox"sv && data.is_editable);
}
// This gets roles that Orca (and other AT-SPI2 clients) read as whole units via Atspi.Text. When the container has
// embedded children (e.g. a link inside a list item), Atspi.Text by itself only carries U+FFFC object-replacement
// markers; expanding those requires the Atspi.Hypertext interface, which Qt's built-in AT-SPI2 bridge doesn't
// implement. So, to keep screen-reader speech complete for those container-as-unit reads, we flatten descendant text
// directly into the returned string. Finer-grained hypertext navigation (arrow-key caret movement across a paragraph
// with a link, etc.) still runs on the general code path that preserves the U+FFFCs.
static bool is_leaf_like_container_role(StringView role)
{
return role == "link"sv
|| role == "button"sv
|| role == "heading"sv
|| role == "img"sv
|| role == "image"sv
|| role == "menuitem"sv
|| role == "tab"sv
|| role == "checkbox"sv
|| role == "radio"sv
|| role == "listitem"sv;
}
AccessibilityInterface::AccessibilityInterface(i64 node_id, WebView::AccessibilityTreeManager const* manager, WebContentView* view)
: m_node_id(node_id)
, m_manager(manager)
, m_view(view)
{
// Qt's bridge requires a non-null QObject* from object(). This interface owns it outright (no parent), so
// ~AccessibilityInterface deletes it and it never leaks as a child of the view.
m_object = new QObject;
m_id = QAccessible::registerAccessibleInterface(this);
}
AccessibilityInterface::~AccessibilityInterface()
{
delete m_object;
}
WebView::AccessibilityNodeData const* AccessibilityInterface::node_data() const
{
return m_manager->node(m_node_id);
}
bool AccessibilityInterface::is_ignored(WebView::AccessibilityNodeData const* data) const
{
if (!data)
return true;
return is_ignored_role(data->role.bytes_as_string_view(), data->name);
}
// The ordered unignored children of node_id, with ignored generic containers flattened recursively so their unignored
// descendants are promoted to this level. This single traversal defines the hypertext offset space: build_hypertext(),
// characterRect(), and append_offset_ys() all walk it, so their offsets stay aligned.
static void gather_unignored_children(WebView::AccessibilityTreeManager const* manager, i64 node_id, QList<i64>& out)
{
auto const* data = manager->node(node_id);
if (!data)
return;
for (auto child_id : data->child_ids) {
auto const* child_data = manager->node(child_id);
if (!child_data)
continue;
if (is_ignored_role(child_data->role.bytes_as_string_view(), child_data->name))
gather_unignored_children(manager, child_id, out);
else
out.append(child_id);
}
}
void AccessibilityInterface::collect_unignored_children(i64 node_id, QList<i64>& out) const
{
gather_unignored_children(m_manager, node_id, out);
}
// Hide text-leaf children from AT-SPI2 — matching Firefox's EmbeddedObjCollector pattern.
//
// We expose two kinds of containers:
//
// - Leaf-like containers (listitem, link, heading, button, etc.) flatten descendant text into their own Atspi.Text
// via flatten_descendant_text() - so text-leaf children are already reachable through the parent's text content.
//
// - Hypertext-exposing containers (paragraph, section, etc.) expose the descendant text interleaved with U+FFFC
// markers for embedded objects via build_hypertext() — so text-leaf children are likewise reachable through the
// parent's own Atspi.Text.
//
// In both cases, re-exposing text-leaves as AT-SPI2 children makes AT clients (Orca's flat review in particular) walk
// in and produce duplicate zones covering text already covered by the parent's own zones. So we hide text-leaf children
// and keep embedded objects (links, images, etc.). Those remain reachable for structural navigation and DOM focus.
void AccessibilityInterface::collect_exposed_children(i64 node_id, QList<i64>& out) const
{
QList<i64> raw;
collect_unignored_children(node_id, raw);
for (auto child_id : raw) {
auto const* child_data = m_manager->node(child_id);
if (!child_data)
continue;
if (child_data->role.bytes_as_string_view() == "text leaf"sv)
continue;
out.append(child_id);
}
}
i64 AccessibilityInterface::find_unignored_parent(i64 node_id) const
{
auto const* data = m_manager->node(node_id);
if (!data)
return -1;
i64 parent_id = data->parent_id;
while (parent_id != -1) {
auto const* parent_data = m_manager->node(parent_id);
if (!parent_data)
return -1;
if (!is_ignored(parent_data))
return parent_id;
parent_id = parent_data->parent_id;
}
return -1;
}
// QAccessibleInterface
bool AccessibilityInterface::isValid() const
{
return m_manager && node_data() != nullptr;
}
QObject* AccessibilityInterface::object() const
{
return m_object;
}
QAccessibleInterface* AccessibilityInterface::childAt(int x, int y) const
{
for (int i = 0; i < childCount(); ++i) {
auto* iface = child(i);
if (iface && iface->rect().contains(x, y))
return iface;
}
return nullptr;
}
void* AccessibilityInterface::interface_cast(QAccessible::InterfaceType type)
{
switch (type) {
case QAccessible::ActionInterface: {
// Every node advertises setFocus (see actionNames), so every node must expose the Action interface — not just
// the press-able roles — or Qt can't reach the advertised action.
if (!node_data())
break;
return static_cast<QAccessibleActionInterface*>(this);
}
case QAccessible::TextInterface: {
auto const* data = node_data();
if (!data)
break;
auto role = data->role.bytes_as_string_view();
// Important: We deliberately exclude the list role (the container, not the list items) from any of the
// conditions we check below — because it actually must *not* have a Text interface. Otherwise, Orca will skip
// the list entirely during Say All iteration. That's because (1) the Text would be just U+FFFC per listitem,
// and (2) Orca can't expand that without a Hypertext interface — *which Qt's AT-SPI2 bridge doesn't give us*.
// And so when Orca sees that, it'll treat find_next_caret_in_order on the list as "text object with
// unexpandable markers" — and that's what leads to Orca skipping the list entirely during Say All iteration.
if (role == "text leaf"sv)
return static_cast<QAccessibleTextInterface*>(this); // Text leaves always have Text.
// A text control always has Text, whatever it holds. An unlabeled field that's still empty has no name and no
// hypertext, so the checks below would leave it without the interface until the user typed into it, and Orca
// would have no text object for caret tracking or typing echo on the first keystrokes — while Gecko (every
// HyperTextAccessible gets MAI_INTERFACE_TEXT, an entry included) and Blink (AXPlatformNodeAuraLinux::
// GetGTypeInterfaceMask() gives a text field AtkText from its role) expose it unconditionally.
if (is_text_control(*data))
return static_cast<QAccessibleTextInterface*>(this);
if (role == "link"sv || role == "button"sv || role == "heading"sv
|| role == "img"sv || role == "image"sv || role == "menuitem"sv
|| role == "tab"sv || role == "checkbox"sv || role == "radio"sv
|| role == "listitem"sv)
return static_cast<QAccessibleTextInterface*>(this);
// Text block containers need a Text interface so that Orca's is_text_block_element heuristic matches;
// otherwise, supports_text() returns False — and its sentence-contents extension walks across paragraph
// boundaries looking for a text-block-element to stop at. Unlike leaf-like containers, these are *not* in
// is_leaf_like_container_role — so build_hypertext uses the general code path (text-leaf children inline;
// embedded objects as U+FFFC).
if (role == "paragraph"sv)
return static_cast<QAccessibleTextInterface*>(this);
// Any other named elements with no children.
if (!data->name.is_empty() && childCount() == 0)
return static_cast<QAccessibleTextInterface*>(this);
// An unnamed container such as an article or blockquote with direct text matches none of the conditions above,
// yet collect_exposed_children strips its text-leaf children (they stay reachable through this node's own
// hypertext). Without a Text interface, that text would be exposed nowhere. Grant Text when build_hypertext()
// carries real textual content — but never when it holds only U+FFFC embedded-object markers (a list of
// listitems, a row of links). That's for the same reason the list role is excluded above: Orca skips a
// marker-only text object it can't expand.
if (hypertext_has_real_text())
return static_cast<QAccessibleTextInterface*>(this);
break;
}
case QAccessible::TableCellInterface: {
auto mapped_role = role();
if (mapped_role == QAccessible::Cell || mapped_role == QAccessible::ColumnHeader || mapped_role == QAccessible::RowHeader)
return static_cast<QAccessibleTableCellInterface*>(this);
break;
}
#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
case QAccessible::AttributesInterface:
return static_cast<QAccessibleAttributesInterface*>(this);
#endif
default:
break;
}
return nullptr;
}
QAccessibleInterface* AccessibilityInterface::parent() const
{
auto const* data = node_data();
if (!data || data->parent_id == -1)
return QAccessible::queryAccessibleInterface(m_view);
i64 parent_id = find_unignored_parent(m_node_id);
if (parent_id == -1)
return QAccessible::queryAccessibleInterface(m_view);
return m_view->accessibility_interface_for_node(parent_id);
}
QAccessibleInterface* AccessibilityInterface::child(int index) const
{
QList<i64> children;
collect_exposed_children(m_node_id, children);
if (index < 0 || index >= children.size())
return nullptr;
return m_view->accessibility_interface_for_node(children[index]);
}
// Qt's UIA and Cocoa bridges ask an interface for its focused descendant; the AT-SPI adaptor never does (it follows
// the Focus events WebContentView posts). The tree records which node has focus, so walk up from that node to this one
// rather than down thru every child — child() rebuilds the exposed-children list and registers an interface for each
// node it visits, which on a big page is thousands of interfaces for one question.
QAccessibleInterface* AccessibilityInterface::focusChild() const
{
auto const* data = node_data();
if (data && data->is_focused)
return const_cast<AccessibilityInterface*>(this);
auto focused_id = m_manager->focused_node_id();
if (!focused_id.has_value())
return nullptr;
for (auto const* node = m_manager->node(*focused_id); node && node->parent_id != -1; node = m_manager->node(node->parent_id)) {
if (node->parent_id == m_node_id)
return m_view->accessibility_interface_for_node(*focused_id);
}
return nullptr;
}
int AccessibilityInterface::childCount() const
{
QList<i64> children;
collect_exposed_children(m_node_id, children);
return children.size();
}
int AccessibilityInterface::indexOfChild(QAccessibleInterface const* iface) const
{
if (!iface)
return -1;
// Qt may pass any interface here and expects -1 for one that's not our child — so a downcast would be undefined for
// anything that isn't an AccessibilityInterface. Instead compare identity against what our own children resolve to;
// child() hands out these same pointers.
QList<i64> children;
collect_exposed_children(m_node_id, children);
for (int index = 0; index < children.size(); ++index) {
if (m_view->accessibility_interface_for_node(children[index]) == iface)
return index;
}
return -1;
}
QString AccessibilityInterface::text(QAccessible::Text t) const
{
auto const* data = node_data();
if (!data)
return {};
auto to_qstring = [](String const& s) -> QString {
if (s.is_empty())
return {};
return QString::fromUtf8(reinterpret_cast<char const*>(s.bytes().data()), s.bytes().size());
};
switch (t) {
case QAccessible::Name:
return to_qstring(data->name);
case QAccessible::Description:
return to_qstring(data->description);
case QAccessible::Value:
if (!data->value.is_empty())
return to_qstring(data->value);
if (data->heading_level > 0)
return QString::number(data->heading_level);
return {};
default:
return {};
}
}
void AccessibilityInterface::setText(QAccessible::Text, QString const&)
{
}
// The node data's geometry is in CSS pixels, and the view shows the page at its zoom level: WebContent folds zoom
// into its device scale, the way Gecko does (nsPresContext::SetFullZoom() refreshes the app-units-per-device-pixel
// ratio that LocalAccessible::Bounds() converts with), so a CSS-pixel rect is zoom_level() times as large on the
// widget. Blink and WebKit zoom in layout instead, so their AX bounds come out zoomed already.
static QRect css_rect_to_global(WebContentView const& view, QRect css_rect)
{
auto zoom = view.zoom_level();
QRect local(qRound(css_rect.x() * zoom), qRound(css_rect.y() * zoom),
qRound(css_rect.width() * zoom), qRound(css_rect.height() * zoom));
auto global_pos = view.mapToGlobal(QPoint(local.x(), local.y()));
return QRect(global_pos.x(), global_pos.y(), local.width(), local.height());
}
QRect AccessibilityInterface::rect() const
{
auto const* data = node_data();
if (!data)
return {};
return css_rect_to_global(*m_view, QRect(data->bounds.x(), data->bounds.y(), data->bounds.width(), data->bounds.height()));
}
QAccessible::Role AccessibilityInterface::map_role() const
{
auto const* data = node_data();
if (!data)
return QAccessible::NoRole;
auto role = data->role.bytes_as_string_view();
// A password field has no ARIA role (HTML-AAM gives it none), but it's a text field to the platform: EditableText
// with the passwordEdit state, which Qt's AT-SPI adaptor reports as ATSPI_ROLE_PASSWORD_TEXT (AtSpiAdaptor::
// getRole) — the role Gecko (HTMLTextFieldAccessible::NativeRole), WebKit (AccessibilityObjectAtspi::effectiveRole)
// and Blink (AXPlatformNodeAuraLinux, a protected kTextField) give it.
if (data->is_password)
return QAccessible::EditableText;
if (role == "document"sv)
return QAccessible::WebDocument;
if (role == "button"sv)
return QAccessible::Button;
if (role == "link"sv)
return QAccessible::Link;
if (role == "heading"sv)
return QAccessible::Heading;
if (role == "textbox"sv)
return QAccessible::EditableText;
if (role == "checkbox"sv)
return QAccessible::CheckBox;
if (role == "radio"sv)
return QAccessible::RadioButton;
if (role == "combobox"sv)
return QAccessible::ComboBox;
if (role == "list"sv)
return QAccessible::List;
if (role == "listitem"sv)
return QAccessible::ListItem;
if (is_table_container_role(role))
return QAccessible::Table;
if (role == "row"sv)
return QAccessible::Row;
if (role == "cell"sv || role == "gridcell"sv)
return QAccessible::Cell;
if (role == "columnheader"sv)
return QAccessible::ColumnHeader;
if (role == "rowheader"sv)
return QAccessible::RowHeader;
if (role == "img"sv || role == "image"sv)
return QAccessible::Graphic;
if (role == "navigation"sv)
return QAccessible::Section;
if (role == "main"sv)
return QAccessible::Section;
if (role == "banner"sv)
return QAccessible::Section;
if (role == "complementary"sv)
return QAccessible::Section;
if (role == "contentinfo"sv)
return QAccessible::Footer;
if (role == "search"sv)
return QAccessible::Section;
if (role == "form"sv)
return QAccessible::Form;
if (role == "region"sv)
return QAccessible::Section;
if (role == "dialog"sv || role == "alertdialog"sv)
return QAccessible::Dialog;
if (role == "progressbar"sv)
return QAccessible::ProgressBar;
if (role == "slider"sv)
return QAccessible::Slider;
if (role == "tab"sv)
return QAccessible::PageTab;
if (role == "tablist"sv)
return QAccessible::PageTabList;
if (role == "tabpanel"sv)
return QAccessible::Pane;
if (role == "menu"sv)
return QAccessible::PopupMenu;
if (role == "menuitem"sv)
return QAccessible::MenuItem;
if (role == "menubar"sv)
return QAccessible::MenuBar;
if (role == "separator"sv)
return QAccessible::Separator;
if (role == "alert"sv)
return QAccessible::AlertMessage;
if (role == "status"sv)
return QAccessible::StatusBar;
if (role == "log"sv)
return QAccessible::Section;
// Qt has no internal-frame role (the ATK_ROLE_INTERNAL_FRAME of Gecko's OuterDocAccessible and Blink's
// Role::kIframe), so a frame is a section: ATSPI_ROLE_SECTION, per QSpiAccessibleBridge::namesForRole().
if (role == "iframe"sv)
return QAccessible::Section;
if (role == "text leaf"sv)
return QAccessible::StaticText;
if (role == "generic"sv)
return QAccessible::Section;
if (role == "article"sv)
return QAccessible::Section;
if (role == "figure"sv)
return QAccessible::Section;
if (role == "group"sv)
return QAccessible::Grouping;
if (role == "searchbox"sv)
return QAccessible::EditableText;
if (role == "paragraph"sv)
return QAccessible::Paragraph;
if (role == "spinbutton"sv)
return QAccessible::SpinBox;
if (role == "switch"sv)
return QAccessible::CheckBox;
if (role == "treeitem"sv)
return QAccessible::TreeItem;
if (role == "option"sv)
return QAccessible::ListItem;
if (role == "menuitemcheckbox"sv)
return QAccessible::CheckBox;
if (role == "menuitemradio"sv)
return QAccessible::RadioButton;
return QAccessible::Section;
}
QAccessible::Role AccessibilityInterface::role() const
{
return map_role();
}
QAccessible::State AccessibilityInterface::state() const
{
QAccessible::State accessible_state;
auto const* data = node_data();
if (!data)
return accessible_state;
auto role = data->role.bytes_as_string_view();
// Only report focusable for roles that really are keyboard-focusable. Reporting it on non-interactive elements
// (headings, paragraphs, lists, list items, generic containers) breaks Orca heuristics; is_text_block_element
// returns False for any focusable object — which causes sentence-contents extension to run past paragraph
// boundaries and pull in the *entire* document.
bool role_is_focusable = role == "button"sv
|| role == "link"sv
|| role == "textbox"sv
|| role == "searchbox"sv
|| role == "checkbox"sv
|| role == "radio"sv
|| role == "combobox"sv
|| role == "slider"sv
|| role == "spinbutton"sv
|| role == "menuitem"sv
|| role == "menuitemcheckbox"sv
|| role == "menuitemradio"sv
|| role == "tab"sv
|| role == "treeitem"sv
|| role == "option"sv
|| role == "switch"sv;
if (role_is_focusable || data->is_editable || data->is_focused)
accessible_state.focusable = true;
if (data->is_focused)
accessible_state.focused = true;
if (data->is_disabled)
accessible_state.disabled = true;
if (data->is_password)
accessible_state.passwordEdit = true;
// The text-editing bits Qt's AT-SPI adaptor turns into EDITABLE, READ_ONLY, MULTI_LINE and MULTISELECTABLE
// (spiStatesFromQState()) — the states Gecko (nsStateMap.h) and Blink (AXPlatformNodeAuraLinux::GetAtkStateSet())
// put on their entries and listboxes, and the ones Orca reads to treat a text object as an editable field: focus
// mode, typing echo, and a read-only field announced as one. Gecko leaves read-only to the absence of EDITABLE,
// which holds here too, since is_read_only clears is_editable.
if (data->is_editable)
accessible_state.editable = true;
if (data->is_read_only)
accessible_state.readOnly = true;
if (data->is_multi_line)
accessible_state.multiLine = true;
if (data->is_multi_selectable)
accessible_state.multiSelectable = true;
// Only report visible/showing for the *active* tab's elements. Elements from *inactive* tabs *must* be hidden from
// AT-SPI2 — so that Orca doesn't try to navigate to them during Say All.
if (m_view && m_view->isVisible()) {
accessible_state.invisible = false;
} else {
accessible_state.invisible = true;
accessible_state.offscreen = true;
}
if (role == "link"sv)
accessible_state.linked = true;
if (role == "text leaf"sv)
accessible_state.readOnly = true;
// The node data carries these, and without them AT-SPI2 clients can't tell a ticked checkbox from an unticked one,
// or an open disclosure from a closed one. NotApplicable means the element has no such state — so leave the
// corresponding bits alone, rather than reporting a false negative.
if (data->is_selected) {
accessible_state.selected = true;
accessible_state.selectable = true;
}
switch (data->checked_state) {
case WebView::AccessibilityNodeData::CheckedState::Unchecked:
accessible_state.checkable = true;
break;
case WebView::AccessibilityNodeData::CheckedState::Checked:
accessible_state.checkable = true;
accessible_state.checked = true;
break;
case WebView::AccessibilityNodeData::CheckedState::Mixed:
accessible_state.checkable = true;
accessible_state.checkStateMixed = true;
break;
case WebView::AccessibilityNodeData::CheckedState::NotApplicable:
break;
}
switch (data->expanded_state) {
case WebView::AccessibilityNodeData::ExpandedState::Collapsed:
accessible_state.expandable = true;
accessible_state.collapsed = true;
break;
case WebView::AccessibilityNodeData::ExpandedState::Expanded:
accessible_state.expandable = true;
accessible_state.expanded = true;
break;
case WebView::AccessibilityNodeData::ExpandedState::NotApplicable:
break;
}
// Qt has no tri-state for pressed, so Mixed reports pressed as the closer of the two.
switch (data->pressed_state) {
case WebView::AccessibilityNodeData::PressedState::Pressed:
case WebView::AccessibilityNodeData::PressedState::Mixed:
accessible_state.pressed = true;
break;
case WebView::AccessibilityNodeData::PressedState::NotPressed:
case WebView::AccessibilityNodeData::PressedState::NotApplicable:
break;
}
return accessible_state;
}
// QAccessibleActionInterface
QStringList AccessibilityInterface::actionNames() const
{
auto const* data = node_data();
if (!data)
return {};
QStringList actions;
auto role = data->role.bytes_as_string_view();
if (role == "button"sv || role == "link"sv || role == "checkbox"sv
|| role == "radio"sv || role == "menuitem"sv || role == "tab"sv
|| role == "switch"sv || role == "menuitemcheckbox"sv || role == "menuitemradio"sv)
actions << QAccessibleActionInterface::pressAction();
// All elements support setFocus so that Orca's GrabFocus (AT-SPI2 Component interface) can move DOM focus there —
// which triggers the CSS :focus-visible focus ring during screen-reader navigation.
actions << QAccessibleActionInterface::setFocusAction();
return actions;
}
void AccessibilityInterface::doAction(QString const& actionName)
{
if (actionName == QAccessibleActionInterface::pressAction())
m_view->perform_accessibility_action(m_node_id, "press"_string);
else if (actionName == QAccessibleActionInterface::setFocusAction())
m_view->perform_accessibility_action(m_node_id, "focus"_string);
}
QStringList AccessibilityInterface::keyBindingsForAction(QString const&) const
{
return {};
}
// QAccessibleTextInterface
void AccessibilityInterface::addSelection(int, int) { }
QString AccessibilityInterface::attributes(int offset, int* startOffset, int* endOffset) const
{
*startOffset = 0;
*endOffset = characterCount();
if (*endOffset <= 0)
*endOffset = offset + 1;
// Return a minimal valid attribute string — so Qt's bridge produces a non-empty a{ss} dict. Orca otherwise crashes
// when the attributes dict is None (empty response from AT-SPI2).
return QStringLiteral("direction:ltr");
}
int AccessibilityInterface::cursorPosition() const { return 0; }
// Qt indexes text in UTF-16 code units, while character_offsets holds one entry per code point. The two agree across
// the whole BMP, and diverge at the first surrogate pair. So a caller's offset has to be translated before it indexes
// that array. Without this, every character after a non-BMP one reports its neighbor's rectangle, or none at all.
static int code_point_offset_for_utf16_offset(String const& text, int utf16_offset)
{
int code_points = 0;
int utf16_units = 0;
for (auto code_point : text.code_points()) {
if (utf16_units >= utf16_offset)
break;
utf16_units += code_point > 0xFFFF ? 2 : 1;
++code_points;
}
return code_points;
}
// For a text leaf, return the rect of the character at 'offset' using per-character layout offsets. Per-character data
// is populated by LibWeb from the text's rendered visual lines and correctly places each character on its own line —
// even when the text wraps. Coordinates are widget-local.
static QRect leaf_character_rect_local(WebView::AccessibilityNodeData const* leaf_data, int offset)
{
if (!leaf_data)
return {};
auto local_full = QRect(leaf_data->bounds.x(), leaf_data->bounds.y(),
leaf_data->bounds.width(), leaf_data->bounds.height());
if (leaf_data->character_offsets.is_empty() || offset < 0)
return local_full;
offset = code_point_offset_for_utf16_offset(leaf_data->name, offset);
// Return empty rect for out-of-range offsets. Qt's AT-SPI2 bridge implementation of GetRangeExtents iterates
// characterRect over [startOffset..endOffset] *inclusive* — while callers pass endOffset as *exclusive*; returning
// an empty rect for the extra past-end offset keeps the union confined to the requested range.
if (offset >= static_cast<int>(leaf_data->character_offsets.size()))
return {};
auto const& char_pt = leaf_data->character_offsets[offset];
int line_index = 0;
for (size_t i = 0; i < leaf_data->line_break_character_offsets.size(); ++i) {
if (leaf_data->line_break_character_offsets[i] <= offset)
line_index = static_cast<int>(i);
}
int line_height = (line_index < static_cast<int>(leaf_data->line_heights.size()))
? leaf_data->line_heights[line_index]
: leaf_data->bounds.height();
int char_width = line_height / 2;
int next_offset = offset + 1;
if (next_offset < static_cast<int>(leaf_data->character_offsets.size())) {
auto const& next_pt = leaf_data->character_offsets[next_offset];
if (next_pt.y() == char_pt.y())
char_width = next_pt.x() - char_pt.x();
}
return QRect(leaf_data->bounds.x() + char_pt.x(),
leaf_data->bounds.y() + char_pt.y(),
char_width,
line_height);
}
static void append_offset_ys(WebView::AccessibilityTreeManager const* manager, i64 node_id, Vector<i32>& out);
static int representative_line_height(WebView::AccessibilityTreeManager const* manager, i64 node_id);
// Return the rect of the character at offset in this interface's Atspi.Text. Text leaves: use per-character layout
// data. General containers exposing hypertext (paragraphs, sections, etc.): walk the unignored children concatenated
// by build_hypertext(). Text-leaf children contribute per-character rects from their own layout data; embedded-object
// children contribute their bounding rect at their U+FFFC position. That all makes per-character rects match the visual
// line each character is actually on — which is what Orca's flat review depends on to cluster zones by line.
QRect AccessibilityInterface::characterRect(int offset) const
{
auto const* data = node_data();
if (!data)
return {};
auto to_global = [this](QRect css_rect) {
return css_rect_to_global(*m_view, css_rect);
};
auto role = data->role.bytes_as_string_view();
if (role == "text leaf"sv)
return to_global(leaf_character_rect_local(data, offset));
if (is_leaf_like_container_role(role))
return rect();
// Qt's AT-SPI2 bridge GetRangeExtents iterates characterRect over [startOffset..endOffset] *inclusive* — while
// callers (including Orca) pass endOffset as exclusive. For a range that ends at the start of the next visual line,
// the inclusive iteration picks up a character from the next line, and the union rect spans two lines — which
// breaks Orca's flat-review line clustering (5px middle-y tolerance). Compensate by returning an empty rect when
// that offset begins a new visual line. Qt's operator| treats isNull() rects as no-ops — so the union stays
// confined to the intended line.
if (offset > 0) {
// Compare the y of offset-1 and offset; if y jumps, treat offset as a line start and return empty.
Vector<i32> ys;
append_offset_ys(m_manager, m_node_id, ys);
// Same tolerance compute_visual_line_starts() applies: only a jump of more than half a line means a new
// visual line. A bare inequality would report no extents for a character merely shifted off the baseline
// (a superscript, or text beside an inline image), dropping it from the union rect GetRangeExtents builds.
int const line_tolerance = representative_line_height(m_manager, m_node_id) / 2;
if (static_cast<size_t>(offset) < ys.size() && qAbs(ys[offset] - ys[offset - 1]) > line_tolerance)
return {};
}
QList<i64> children;
collect_unignored_children(m_node_id, children);
int cumulative = 0;
for (auto child_id : children) {
auto const* child_data = m_manager->node(child_id);
if (!child_data)
continue;
auto child_role = child_data->role.bytes_as_string_view();
if (child_role == "text leaf"sv) {
auto leaf_string = QString::fromUtf8(
reinterpret_cast<char const*>(child_data->name.bytes().data()),
child_data->name.bytes().size());
int leaf_len = leaf_string.size();
if (offset < cumulative + leaf_len)
return to_global(leaf_character_rect_local(child_data, offset - cumulative));
cumulative += leaf_len;
} else {
if (offset == cumulative) {
auto local = QRect(child_data->bounds.x(), child_data->bounds.y(),
child_data->bounds.width(), child_data->bounds.height());
return to_global(local);
}
cumulative += 1;
}
}
// Past-end offset: return empty rect (see comment in leaf_character_rect_local).
return {};
}
int AccessibilityInterface::selectionCount() const { return 0; }
int AccessibilityInterface::offsetAtPoint(QPoint const&) const { return 0; }
void AccessibilityInterface::selection(int, int* startOffset, int* endOffset) const
{
*startOffset = 0;
*endOffset = 0;
}
// This builds hypertext-aware text for this node. Text-leaf children contribute their text content; non-text children
// contribute U+FFFC (object replacement character) as embedded objects — except for leaf-like container roles
// (listitem, heading, link, button, etc.), where we flatten the full descendant text directly. That's because Qt's
// bridge doesn't expose AtkHypertext — and AT clients therefore can't expand the U+FFFC markers into child content.
QString AccessibilityInterface::build_hypertext() const
{
auto const* data = node_data();
if (!data)
return {};
auto role = data->role.bytes_as_string_view();
// Text leaves just return their own name.
if (role == "text leaf"sv)
return QString::fromUtf8(reinterpret_cast<char const*>(data->name.bytes().data()), data->name.bytes().size());
// A text control's text is what it holds (its value), not its name: an input or textarea has no text-leaf children
// in the tree, and its name is its label. Qt's own QAccessibleLineEdit hands out the field's display text the same
// way, and it's this text Orca reads back for typing echo and caret navigation — against the same offsets the
// caret, selection and editable-text plumbing use.
if (is_text_control(*data))
return QString::fromUtf8(reinterpret_cast<char const*>(data->value.bytes().data()), data->value.bytes().size());
// Leaf-like containers: flatten all descendant text so the whole unit speaks as one string.
if (is_leaf_like_container_role(role))
return flatten_descendant_text(m_node_id);
// General containers: text-leaf children inline, other children become U+FFFC.
QList<i64> children;
collect_unignored_children(m_node_id, children);
if (children.isEmpty()) {
// No children — return the node's own name (e.g. for img[alt]).
return QString::fromUtf8(reinterpret_cast<char const*>(data->name.bytes().data()), data->name.bytes().size());
}
QString result;
for (auto child_id : children) {
auto const* child_data = m_manager->node(child_id);
if (!child_data)
continue;
if (child_data->role.bytes_as_string_view() == "text leaf"sv) {
result += QString::fromUtf8(
reinterpret_cast<char const*>(child_data->name.bytes().data()),
child_data->name.bytes().size());
} else {
result += QChar(0xFFFC); // Embedded-object marker.
}
}
return result;
}
// Real text means at least one character that is neither an embedded-object marker (U+FFFC) nor whitespace. A container
// whose hypertext is only markers must not advertise Text: Orca treats it as an unexpandable text object and skips it
// during Say All, and the Qt bridge exposes no Hypertext interface to expand the markers. Incidental whitespace between
// markers doesn't make the content readable, so it doesn't count.
bool AccessibilityInterface::hypertext_has_real_text() const
{
auto const hypertext = build_hypertext();
for (QChar const ch : hypertext) {
if (ch != QChar(0xFFFC) && !ch.isSpace())
return true;
}
return false;
}
// This is used for leaf-like containers whose children's text must be inlined (see build_hypertext). Text leaves
// contribute their name; every other node recurses into its unignored children – and, if that yields nothing, falls
// back to the node's own name.
QString AccessibilityInterface::flatten_descendant_text(i64 node_id) const
{
auto const* data = m_manager->node(node_id);
if (!data)
return {};
auto role = data->role.bytes_as_string_view();
if (role == "text leaf"sv)
return QString::fromUtf8(reinterpret_cast<char const*>(data->name.bytes().data()), data->name.bytes().size());
QString result;
QList<i64> children;
collect_unignored_children(node_id, children);
for (auto child_id : children)
result += flatten_descendant_text(child_id);
if (result.isEmpty() && !data->name.is_empty())
result = QString::fromUtf8(reinterpret_cast<char const*>(data->name.bytes().data()), data->name.bytes().size());
return result;
}
QString AccessibilityInterface::text(int startOffset, int endOffset) const
{
auto full_text = build_hypertext();
return full_text.mid(startOffset, endOffset - startOffset);
}
void AccessibilityInterface::removeSelection(int) { }
void AccessibilityInterface::setCursorPosition(int) { }
void AccessibilityInterface::setSelection(int, int, int) { }
int AccessibilityInterface::characterCount() const
{
return build_hypertext().size();
}
void AccessibilityInterface::scrollToSubstring(int, int)
{
// Orca calls scrollToSubstring when its browse-mode cursor moves to an element. To get the accessibility focus ring
// painted, we use the "scroll_into_view" action to scroll the element into view and mark it as the document's
// accessibility focus target — all without moving DOM focus. But Orca may hold stale references to inactive tab
// objects and send scrollToSubstring to them — so, we only do this if this view is visible.
if (m_view && m_view->isVisible())
m_view->perform_accessibility_action(m_node_id, "scroll_into_view"_string);
}
// The vertical extent of one UTF-16 code unit of build_hypertext()'s text: the line it renders on, in the same space
// (CSS px) as every bounds here.
struct OffsetLineExtent {
i32 y { 0 };
i32 height { 0 };
// An embedded object with no text of its own (an <img>, e.g.): its y starts as its top edge and is settled onto a
// neighbor's line by settle_textless_objects() once every entry is known.
bool is_textless_object { false };
};
// The y of the first text character inside a node, and that character's line height.
static Optional<OffsetLineExtent> first_text_leaf_extent(WebView::AccessibilityTreeManager const* manager, i64 node_id)
{
auto const* data = manager->node(node_id);
if (!data)
return {};
if (data->role.bytes_as_string_view() == "text leaf"sv) {
if (data->name.is_empty())
return {};
i32 y = data->bounds.y();
if (!data->character_offsets.is_empty())
y += data->character_offsets.first().y();
i32 height = data->line_heights.is_empty() ? data->bounds.height() : data->line_heights.first();
return OffsetLineExtent { y, height, false };
}
for (auto child_id : data->child_ids) {
if (auto extent = first_text_leaf_extent(manager, child_id); extent.has_value())
return extent;
}
return {};
}
// Gathers the extent of every code unit of a node's hypertext, in one pass over the same flattened child sequence
// build_hypertext() walks: a text-leaf child contributes an entry per code unit (two for a surrogate pair, both at the
// code point's line — character_offsets has one entry per code point), every other child one entry for the U+FFFC it
// occupies. Resolving offsets one at a time would walk the children, decode every earlier leaf and rescan the leaf's
// code points for each offset — O(n²) in the container's text, enough to stall the UI thread on a long <pre> while Orca
// asks for line after line during Say All or flat review.
static void gather_offset_line_extents(WebView::AccessibilityTreeManager const* manager, i64 node_id, Vector<OffsetLineExtent>& out)
{
auto const* data = manager->node(node_id);
if (!data)
return;
if (data->role.bytes_as_string_view() == "text leaf"sv) {
size_t code_point_index = 0;
size_t line_index = 0;
for (auto code_point : data->name.code_points()) {
// line_break_character_offsets is ascending, so the line a code point is on only ever advances.
while (line_index + 1 < data->line_break_character_offsets.size()
&& static_cast<size_t>(data->line_break_character_offsets[line_index + 1]) <= code_point_index)
++line_index;
i32 y = data->bounds.y();
if (!data->character_offsets.is_empty())
y += data->character_offsets[min(code_point_index, data->character_offsets.size() - 1)].y();
i32 height = line_index < data->line_heights.size()
? data->line_heights[line_index]
: data->bounds.height();
out.append({ y, height, false });
if (code_point > 0xFFFF)
out.append({ y, height, false });
++code_point_index;
}
return;
}
QList<i64> children;
gather_unignored_children(manager, node_id, children);
for (auto child_id : children) {
auto const* child = manager->node(child_id);
if (!child)
continue;
if (child->role.bytes_as_string_view() == "text leaf"sv) {
gather_offset_line_extents(manager, child_id, out);
} else if (auto extent = first_text_leaf_extent(manager, child_id); extent.has_value()) {
// An object with text sits on the line its first character is on — so a link that wraps onto a second line
// stays anchored to the line it starts on.
out.append(*extent);
} else {
out.append({ child->bounds.y(), child->bounds.height(), true });
}
}
}
// Puts each textless embedded object on the line of the text beside it: the nearest text character before it whose
// line the object's box overlaps vertically, else the nearest one after it. A text character's y is the top of the
// text's box on that line, while an inline image's is its own top edge — for a tall image, well above the text's on
// the same line, and far enough for compute_visual_line_starts() to read a line break before the image and another
// after it. Overlap is what marks the shared line, whatever the image's vertical-align, since every inline box is
// inside its line box. An object with no text beside it on its line (one alone on a line, e.g.) keeps its top edge.
static void settle_textless_objects(Vector<OffsetLineExtent>& extents)
{
auto overlaps = [](OffsetLineExtent const& object, OffsetLineExtent const& text) {
return !text.is_textless_object && object.y < text.y + text.height && text.y < object.y + object.height;
};
for (size_t i = 0; i < extents.size(); ++i) {
if (!extents[i].is_textless_object)
continue;
Optional<i32> line_y;
for (size_t j = i; j-- > 0;) {
if (extents[j].is_textless_object)
continue;
if (overlaps(extents[i], extents[j]))
line_y = extents[j].y;
break;
}
for (size_t j = i + 1; !line_y.has_value() && j < extents.size(); ++j) {
if (extents[j].is_textless_object)
continue;
if (overlaps(extents[i], extents[j]))
line_y = extents[j].y;
break;
}
if (line_y.has_value())
extents[i].y = *line_y;
}
}
// The y (in the same space as every bounds here) of the line each UTF-16 code unit of build_hypertext()'s text sits on.
static void append_offset_ys(WebView::AccessibilityTreeManager const* manager, i64 node_id, Vector<i32>& out)
{
Vector<OffsetLineExtent> extents;
gather_offset_line_extents(manager, node_id, extents);
settle_textless_objects(extents);
out.ensure_capacity(out.size() + extents.size());
for (auto const& extent : extents)
out.unchecked_append(extent.y);
}
// A representative line height (CSS px) for the node's text, used as the same-line y tolerance below. line_heights is
// populated on text leaves — so descend to the first one.
static int representative_line_height(WebView::AccessibilityTreeManager const* manager, i64 node_id)
{
auto const* data = manager->node(node_id);
if (!data)
return 0;
if (data->role.bytes_as_string_view() == "text leaf"sv) {
if (!data->line_heights.is_empty())
return data->line_heights.first();
return data->bounds.height();
}
for (auto child_id : data->child_ids) {
if (int height = representative_line_height(manager, child_id); height > 0)
return height;
}
return 0;
}
// Compute the character offsets where each visual line starts — from the per-character y that append_offset_ys()
// gathers. The last entry is char_count as an end sentinel. Robust against small y-jitter by only treating a change in
// y as a new line when the jump is larger than half the current line height.
static QList<int> compute_visual_line_starts(AccessibilityInterface const& iface, int char_count)
{
QList<int> starts;
starts.append(0);
if (char_count <= 0) {
starts.append(0);
return starts;
}
auto* manager = iface.accessibility_manager();
auto node_id = iface.node_id();
// Only treat a y change as a new visual line when the jump exceeds half the line height, so intra-line
// baseline shifts (superscripts, inline images) don't split one visual line into several.
int const tolerance = representative_line_height(manager, node_id) / 2;
Vector<i32> ys;
append_offset_ys(manager, node_id, ys);
i32 prev_y = ys.is_empty() ? 0 : ys[0];
int const known = min(char_count, static_cast<int>(ys.size()));
for (int i = 1; i < known; ++i) {
if (qAbs(ys[i] - prev_y) > tolerance) {
starts.append(i);
prev_y = ys[i];
}
}
starts.append(char_count);
return starts;
}
static QString text_at_visual_line_containing(QList<int> const& line_starts, QString const& full_text, int offset,
int* start_offset, int* end_offset)
{
int count = full_text.size();
if (offset < 0 || offset > count) {
*start_offset = *end_offset = -1;
return {};
}
int clamped = qBound(0, offset, count);
int line_index = -1;
for (int i = 0; i + 1 < line_starts.size(); ++i) {
if (line_starts[i] <= clamped && clamped < line_starts[i + 1]) {
line_index = i;
break;
}
}
if (line_index < 0) {
line_index = line_starts.size() - 2;
if (line_index < 0) {
*start_offset = *end_offset = 0;
return {};
}
}
*start_offset = line_starts[line_index];
*end_offset = line_starts[line_index + 1];
return full_text.mid(*start_offset, *end_offset - *start_offset);
}
// We want visual-line boundary iteration for *text-block* containers (paragraphs, sections), whose inline content can
// wrap across multiple visual lines — so Orca's flat review clusters zones by line, and line-by-line navigation walks
// the wrapped lines. But we do *not* want it for *leaf-like* containers (listitem, link, heading, button, image,
// menuitem, tab, checkbox, radio) — because those are *atomic units* whose full flattened text is one presentation
// unit. Orca's _generate_text_line (reached via structural navigation's I key for list items, H for headings, etc.)
// calls get_string_at_offset(obj, 0, LINE). And for an atomic unit, that's supposed to be the *whole* text — not the
// first visual sub-line. Falling through to Qt's default textAtOffset here matches what the base does (split on \n) —
// which gives the full flattened text for leaf-like containers whose content has no embedded \n.
static bool should_use_visual_line_boundary(AccessibilityInterface const& iface)
{
auto const* data = iface.node_data();
if (!data)
return false;
return !is_leaf_like_container_role(data->role.bytes_as_string_view());
}
QString AccessibilityInterface::textAtOffset(int offset, QAccessible::TextBoundaryType boundaryType,
int* startOffset, int* endOffset) const
{
if (boundaryType != QAccessible::LineBoundary || !should_use_visual_line_boundary(*this))
return QAccessibleTextInterface::textAtOffset(offset, boundaryType, startOffset, endOffset);
auto full_text = build_hypertext();
auto line_starts = compute_visual_line_starts(*this, full_text.size());
return text_at_visual_line_containing(line_starts, full_text, offset, startOffset, endOffset);
}
QString AccessibilityInterface::textBeforeOffset(int offset, QAccessible::TextBoundaryType boundaryType,
int* startOffset, int* endOffset) const
{
if (boundaryType != QAccessible::LineBoundary || !should_use_visual_line_boundary(*this))
return QAccessibleTextInterface::textBeforeOffset(offset, boundaryType, startOffset, endOffset);
auto full_text = build_hypertext();
auto line_starts = compute_visual_line_starts(*this, full_text.size());
int this_start = -1, this_end = -1;
text_at_visual_line_containing(line_starts, full_text, offset, &this_start, &this_end);
if (this_start <= 0) {
*startOffset = *endOffset = -1;
return {};
}
return text_at_visual_line_containing(line_starts, full_text, this_start - 1, startOffset, endOffset);
}
QString AccessibilityInterface::textAfterOffset(int offset, QAccessible::TextBoundaryType boundaryType,
int* startOffset, int* endOffset) const
{
if (boundaryType != QAccessible::LineBoundary || !should_use_visual_line_boundary(*this))
return QAccessibleTextInterface::textAfterOffset(offset, boundaryType, startOffset, endOffset);
auto full_text = build_hypertext();
auto line_starts = compute_visual_line_starts(*this, full_text.size());
int this_start = -1, this_end = -1;
text_at_visual_line_containing(line_starts, full_text, offset, &this_start, &this_end);
if (this_end >= full_text.size()) {
*startOffset = *endOffset = -1;
return {};
}
return text_at_visual_line_containing(line_starts, full_text, this_end, startOffset, endOffset);
}
#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
// QAccessibleAttributesInterface
QList<QAccessible::Attribute> AccessibilityInterface::attributeKeys() const
{
return { QAccessible::Attribute::Custom };
}
QVariant AccessibilityInterface::attributeValue(QAccessible::Attribute key) const
{
if (key != QAccessible::Attribute::Custom)
return {};
auto const* data = node_data();
if (!data)
return {};
QHash<QString, QString> attrs;
auto role = data->role.bytes_as_string_view();
// "tag" attribute: Orca's web script uses this to identify web elements (is_web_element checks for it), so
// synthesize one from the role.
if (role == "document"sv)
attrs[QStringLiteral("tag")] = QStringLiteral("body");
else if (role == "heading"sv)
attrs[QStringLiteral("tag")] = QStringLiteral("h%1").arg(data->heading_level > 0 ? data->heading_level : 1);
else if (role == "link"sv)
attrs[QStringLiteral("tag")] = QStringLiteral("a");
else if (role == "img"sv || role == "image"sv)
attrs[QStringLiteral("tag")] = QStringLiteral("img");
else if (role == "list"sv)
attrs[QStringLiteral("tag")] = QStringLiteral("ul");
else if (role == "listitem"sv)
attrs[QStringLiteral("tag")] = QStringLiteral("li");
else if (role == "table"sv)
attrs[QStringLiteral("tag")] = QStringLiteral("table");
else if (role == "row"sv)
attrs[QStringLiteral("tag")] = QStringLiteral("tr");
else if (role == "cell"sv || role == "gridcell"sv)
attrs[QStringLiteral("tag")] = QStringLiteral("td");
else if (role == "columnheader"sv)
attrs[QStringLiteral("tag")] = QStringLiteral("th");
else if (role == "button"sv)
attrs[QStringLiteral("tag")] = QStringLiteral("button");
else if (role == "textbox"sv || role == "searchbox"sv)
attrs[QStringLiteral("tag")] = QStringLiteral("input");
else if (role == "form"sv)
attrs[QStringLiteral("tag")] = QStringLiteral("form");
else if (role == "navigation"sv)
attrs[QStringLiteral("tag")] = QStringLiteral("nav");
else if (role == "main"sv)
attrs[QStringLiteral("tag")] = QStringLiteral("main");
else if (role == "banner"sv)
attrs[QStringLiteral("tag")] = QStringLiteral("header");
else if (role == "contentinfo"sv)
attrs[QStringLiteral("tag")] = QStringLiteral("footer");
else if (role == "complementary"sv)
attrs[QStringLiteral("tag")] = QStringLiteral("aside");
else if (role == "search"sv)
attrs[QStringLiteral("tag")] = QStringLiteral("search");
else if (role == "region"sv)
attrs[QStringLiteral("tag")] = QStringLiteral("section");
else if (role == "paragraph"sv)
attrs[QStringLiteral("tag")] = QStringLiteral("p");
else if (role == "separator"sv)
attrs[QStringLiteral("tag")] = QStringLiteral("hr");
else if (role == "article"sv)
attrs[QStringLiteral("tag")] = QStringLiteral("article");
else if (role == "blockquote"sv)
attrs[QStringLiteral("tag")] = QStringLiteral("blockquote");
else if (role == "text leaf"sv)
attrs[QStringLiteral("tag")] = QStringLiteral("#text");
else if (role == "generic"sv)
attrs[QStringLiteral("tag")] = QStringLiteral("div");
else if (!role.is_empty())
attrs[QStringLiteral("tag")] = QStringLiteral("div");
// "xml-roles": Orca uses this to distinguish landmark types.
if (!role.is_empty() && role != "text leaf"sv) {
attrs[QStringLiteral("xml-roles")] = QString::fromUtf8(
reinterpret_cast<char const*>(data->role.bytes().data()),
data->role.bytes().size());
}
// "level": a heading's level, or a treeitem's, row's or listitem's depth — the object attribute that Gecko
// (GroupPosition) and Blink (AXPlatformNodeAuraLinux, from kHierarchicalLevel) export for both, and the one
// Orca reads for tree items.
if (data->heading_level > 0)
attrs[QStringLiteral("level")] = QString::number(data->heading_level);
else if (data->hierarchical_level > 0)
attrs[QStringLiteral("level")] = QString::number(data->hierarchical_level);
return QVariant::fromValue(attrs);
}
#endif
// QAccessibleTableCellInterface
int AccessibilityInterface::columnExtent() const
{
auto const* data = node_data();
return data ? data->column_span : 1;
}
QList<QAccessibleInterface*> AccessibilityInterface::columnHeaderCells() const
{
return {};
}
int AccessibilityInterface::columnIndex() const
{
auto const* data = node_data();
if (!data)
return 0;
// Prefer the colspan-aware index LibWeb already computed; the flat sibling loop below mis-reports every
// cell after a colspan>1 cell.
if (data->cell_column_index >= 0)
return data->cell_column_index;
auto const* row = m_manager->node(data->parent_id);
if (!row)
return 0;
int column = 0;
for (auto sibling_id : row->child_ids) {
if (sibling_id == m_node_id)
return column;
column++;
}
return 0;
}
int AccessibilityInterface::rowExtent() const
{
auto const* data = node_data();
return data ? data->row_span : 1;
}
QList<QAccessibleInterface*> AccessibilityInterface::rowHeaderCells() const
{
return {};
}
int AccessibilityInterface::rowIndex() const
{
auto const* data = node_data();
if (!data)
return 0;
i64 table_id = -1;
i64 ancestor_id = data->parent_id;
while (ancestor_id != -1) {
auto const* ancestor = m_manager->node(ancestor_id);
if (!ancestor)
break;
if (is_table_container_role(ancestor->role.bytes_as_string_view())) {
table_id = ancestor_id;
break;
}
ancestor_id = ancestor->parent_id;
}
if (table_id == -1)
return 0;
auto const* table = m_manager->node(table_id);
if (!table)
return 0;
int index = 0;
for (auto child_id : table->child_ids) {
auto const* child = m_manager->node(child_id);
if (!child)
continue;
if (child->role.bytes_as_string_view() == "row"sv) {
if (child->id == data->parent_id)
return index;
index++;
} else if (child->role.bytes_as_string_view() == "rowgroup"sv) {
for (auto gc_id : child->child_ids) {
auto const* gc = m_manager->node(gc_id);
if (gc && gc->role.bytes_as_string_view() == "row"sv) {
if (gc->id == data->parent_id)
return index;
index++;
}
}
}
}
return 0;
}
bool AccessibilityInterface::isSelected() const
{
return false;
}
QAccessibleInterface* AccessibilityInterface::table() const
{
auto const* data = node_data();
if (!data)
return nullptr;
i64 ancestor_id = data->parent_id;
while (ancestor_id != -1) {
auto const* ancestor = m_manager->node(ancestor_id);
if (!ancestor)
return nullptr;
if (is_table_container_role(ancestor->role.bytes_as_string_view()))
return m_view->accessibility_interface_for_node(ancestor_id);
ancestor_id = ancestor->parent_id;
}
return nullptr;
}
}