Skip to content

Truly independent web browser

LibWebView+WebContent: Send only what changed in the accessibility tree

sideshowbarkerd3bf3e092ec2
diff --git a/Libraries/LibWebCommon/CMakeLists.txt b/Libraries/LibWebCommon/CMakeLists.txt
index 749b47537a4..b788d17b74b 100644
--- a/Libraries/LibWebCommon/CMakeLists.txt
+++ b/Libraries/LibWebCommon/CMakeLists.txt
@@ -77,6 +77,7 @@ set(SOURCES
WebDriver/Response.cpp
WebDriver/TimeoutsConfiguration.cpp
WebDriver/UserPrompt.cpp
+ WebView/AccessibilityTreePublisher.cpp
WebView/Attribute.cpp
WebView/BrowsingBehavior.cpp
WebView/ConsoleOutput.cpp
diff --git a/Libraries/LibWebCommon/Forward.h b/Libraries/LibWebCommon/Forward.h
index 9e47cb3ae4d..5ff2f87b833 100644
--- a/Libraries/LibWebCommon/Forward.h
+++ b/Libraries/LibWebCommon/Forward.h
@@ -119,6 +119,7 @@ struct StorageEndpoint;
namespace WebView {
struct AccessibilityNodeData;
+struct AccessibilityTreeDelta;
struct Attribute;
struct ConsoleOutput;
struct DOMNodeProperties;
diff --git a/Libraries/LibWebCommon/WebView/AccessibilityNodeData.ipc b/Libraries/LibWebCommon/WebView/AccessibilityNodeData.ipc
index 917dd551dd1..f94c331a8ca 100644
--- a/Libraries/LibWebCommon/WebView/AccessibilityNodeData.ipc
+++ b/Libraries/LibWebCommon/WebView/AccessibilityNodeData.ipc
@@ -85,3 +85,9 @@ struct WebView::AccessibilityNodeData {
Vector<i32> line_break_character_offsets;
Vector<i32> line_heights;
}
+
+[ExistingCpp]
+struct WebView::AccessibilityTreeDelta {
+ Vector<WebView::AccessibilityNodeData> changed_nodes;
+ Vector<i64> removed_ids;
+}
diff --git a/Libraries/LibWebCommon/WebView/AccessibilityTreePublisher.cpp b/Libraries/LibWebCommon/WebView/AccessibilityTreePublisher.cpp
new file mode 100644
index 00000000000..143e0dfd45a
--- /dev/null
+++ b/Libraries/LibWebCommon/WebView/AccessibilityTreePublisher.cpp
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/HashTable.h>
+#include <LibWebCommon/WebView/AccessibilityTreePublisher.h>
+
+namespace WebView {
+
+AccessibilityTreePublisher::Update AccessibilityTreePublisher::publish(i64 document_id, Vector<AccessibilityNodeData> nodes, bool whole_tree_requested)
+{
+ auto remember = [&](Vector<AccessibilityNodeData> const& published) {
+ m_document_id = document_id;
+ m_published_nodes.clear();
+ m_published_nodes.ensure_capacity(published.size());
+ for (auto const& node : published)
+ m_published_nodes.set(node.id, node);
+ };
+
+ if (whole_tree_requested || m_document_id != document_id) {
+ remember(nodes);
+ return WholeTree { ++m_sequence, move(nodes) };
+ }
+
+ // Every node that's new or whose data changed goes in the change, in the order the tree lists them. A node whose
+ // children changed is among them, so a node that moved is listed by its new parent, and dropped by its old one.
+ // The tree sent keeps each node's new data, moved from the tree just built rather than copied again.
+ AccessibilityTreeDelta delta;
+ Vector<size_t> new_node_indices;
+ size_t surviving_count = 0;
+ for (size_t i = 0; i < nodes.size(); ++i) {
+ auto& node = nodes[i];
+ auto published = m_published_nodes.find(node.id);
+ if (published == m_published_nodes.end()) {
+ delta.changed_nodes.append(node);
+ new_node_indices.append(i);
+ continue;
+ }
+ ++surviving_count;
+ if (published->value == node)
+ continue;
+ delta.changed_nodes.append(node);
+ published->value = move(node);
+ }
+
+ // Only when fewer nodes of the tree sent survive than it had are any of them gone. (A node moved from still has its
+ // ID: Moving an integer copies it.)
+ if (surviving_count < m_published_nodes.size()) {
+ HashTable<i64> current_ids;
+ current_ids.ensure_capacity(nodes.size());
+ for (auto const& node : nodes)
+ current_ids.set(node.id);
+ for (auto const& [id, node] : m_published_nodes) {
+ if (!current_ids.contains(id))
+ delta.removed_ids.append(id);
+ }
+ for (auto id : delta.removed_ids)
+ m_published_nodes.remove(id);
+ }
+ for (auto i : new_node_indices)
+ m_published_nodes.set(nodes[i].id, move(nodes[i]));
+
+ if (delta.changed_nodes.is_empty() && delta.removed_ids.is_empty())
+ return NothingChanged {};
+
+ auto base_sequence = m_sequence;
+ return Change { base_sequence, ++m_sequence, move(delta) };
+}
+
+}
diff --git a/Libraries/LibWebCommon/WebView/AccessibilityTreePublisher.h b/Libraries/LibWebCommon/WebView/AccessibilityTreePublisher.h
new file mode 100644
index 00000000000..49253bd00d7
--- /dev/null
+++ b/Libraries/LibWebCommon/WebView/AccessibilityTreePublisher.h
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/HashMap.h>
+#include <AK/Variant.h>
+#include <AK/Vector.h>
+#include <LibWebCommon/Export.h>
+#include <LibWebCommon/WebView/AccessibilityNodeData.h>
+
+namespace WebView {
+
+// Decides what a page sends the UI process for each accessibility tree it builds: the whole tree when the UI process
+// asks for it or the page has a new document, and otherwise only what changed since the last tree sent. Each tree sent
+// gets the next sequence number, and a change names the number of the tree it applies to, so the UI process can tell
+// when it doesn't hold that tree and has to ask for the whole one again.
+class WEBCOMMON_API AccessibilityTreePublisher {
+public:
+ struct WholeTree {
+ u64 sequence { 0 };
+ Vector<AccessibilityNodeData> nodes;
+ };
+ struct Change {
+ u64 base_sequence { 0 };
+ u64 sequence { 0 };
+ AccessibilityTreeDelta delta;
+ };
+ struct NothingChanged { };
+ using Update = Variant<NothingChanged, WholeTree, Change>;
+
+ // The nodes are a whole tree in tree order, as the document builds it.
+ Update publish(i64 document_id, Vector<AccessibilityNodeData> nodes, bool whole_tree_requested);
+
+private:
+ Optional<i64> m_document_id;
+ HashMap<i64, AccessibilityNodeData> m_published_nodes;
+ u64 m_sequence { 0 };
+};
+
+}
diff --git a/Libraries/LibWebView/AccessibilityTreeManager.cpp b/Libraries/LibWebView/AccessibilityTreeManager.cpp
index f8f4bb4e7ee..0be9d332e33 100644
--- a/Libraries/LibWebView/AccessibilityTreeManager.cpp
+++ b/Libraries/LibWebView/AccessibilityTreeManager.cpp
@@ -23,9 +23,10 @@ namespace {
// from overflowing the UI process stack.
constexpr size_t max_accessibility_tree_depth = 1000;
-Vector<AccessibilityNodeData> sanitize_tree(Vector<AccessibilityNodeData> nodes, i64& out_root_id)
+Vector<AccessibilityNodeData> sanitize_tree(Vector<AccessibilityNodeData> nodes, i64& out_root_id, bool& out_repaired)
{
out_root_id = -1;
+ out_repaired = false;
// Index nodes by id, keeping the first occurrence of any duplicated id, and take the first node that claims to be
// the root (parent_id == -1) as the single root.
@@ -88,10 +89,16 @@ Vector<AccessibilityNodeData> sanitize_tree(Vector<AccessibilityNodeData> nodes,
if (!visited.contains(node.id) || emitted.contains(node.id))
continue;
emitted.set(node.id);
- node.parent_id = parent_of.get(node.id).value();
- node.child_ids = move(accepted_children.find(node.id)->value);
+ auto parent_id = parent_of.get(node.id).value();
+ auto& child_ids = accepted_children.find(node.id)->value;
+ if (node.parent_id != parent_id || node.child_ids != child_ids)
+ out_repaired = true;
+ node.parent_id = parent_id;
+ node.child_ids = move(child_ids);
result.append(move(node));
}
+ if (result.size() != nodes.size())
+ out_repaired = true;
out_root_id = root_id;
return result;
@@ -102,7 +109,8 @@ Vector<AccessibilityNodeData> sanitize_tree(Vector<AccessibilityNodeData> nodes,
void AccessibilityTreeManager::update_tree(Vector<AccessibilityNodeData> nodes)
{
i64 root_id = -1;
- auto sanitized = sanitize_tree(move(nodes), root_id);
+ bool repaired = false;
+ auto sanitized = sanitize_tree(move(nodes), root_id, repaired);
// Detect live-region content changes before replacing the tree. Needs an index of the new nodes by id — so the
// ancestor walk below is O(depth) rather than O(N) per step. Without this, a full traversal of an N-node tree would
@@ -158,10 +166,16 @@ void AccessibilityTreeManager::update_tree(Vector<AccessibilityNodeData> nodes)
m_nodes.clear();
m_root_id = root_id;
+ m_whole_tree_was_repaired = repaired;
+ m_focus_shown_on_root = false;
+ m_focused_id_from_content = {};
++m_generation;
- for (auto& node : sanitized)
+ for (auto& node : sanitized) {
+ if (node.is_focused)
+ m_focused_id_from_content = node.id;
m_nodes.set(node.id, move(node));
+ }
}
Optional<Vector<i64>> AccessibilityTreeManager::apply_delta(AccessibilityTreeDelta const& delta)
@@ -361,6 +375,18 @@ Optional<Vector<i64>> AccessibilityTreeManager::apply_delta(AccessibilityTreeDel
auto& stored = m_nodes.ensure(changed_node.id);
stored = changed_node;
stored.parent_id = parent_id;
+ if (changed_node.is_focused)
+ m_focused_id_from_content = changed_node.id;
+ else if (m_focused_id_from_content == changed_node.id)
+ m_focused_id_from_content = {};
+ }
+ if (m_focused_id_from_content.has_value() && !m_nodes.contains(*m_focused_id_from_content))
+ m_focused_id_from_content = {};
+ // A whole tree would have replaced the root's focus that show_focus_on_root() put there, so a change does too.
+ if (m_focus_shown_on_root) {
+ m_focus_shown_on_root = false;
+ for (auto& [id, node] : m_nodes)
+ node.is_focused = id == m_focused_id_from_content;
}
++m_generation;
@@ -370,6 +396,22 @@ Optional<Vector<i64>> AccessibilityTreeManager::apply_delta(AccessibilityTreeDel
return removed_ids;
}
+void AccessibilityTreeManager::update_tree(Vector<AccessibilityNodeData> nodes, u64 sequence)
+{
+ update_tree(move(nodes));
+ m_sequence = sequence;
+}
+
+Optional<Vector<i64>> AccessibilityTreeManager::apply_delta(AccessibilityTreeDelta const& delta, u64 base_sequence, u64 sequence)
+{
+ if (m_whole_tree_was_repaired || base_sequence != m_sequence)
+ return {};
+ auto removed_ids = apply_delta(delta);
+ if (removed_ids.has_value())
+ m_sequence = sequence;
+ return removed_ids;
+}
+
AccessibilityNodeData const* AccessibilityTreeManager::node(i64 id) const
{
auto it = m_nodes.find(id);
@@ -419,10 +461,19 @@ AccessibilityNodeData const* AccessibilityTreeManager::hit_test(Gfx::IntPoint po
void AccessibilityTreeManager::set_focused_node(i64 node_id)
{
+ m_focused_id_from_content = node_id;
+ m_focus_shown_on_root = false;
for (auto& [id, node] : m_nodes)
node.is_focused = (id == node_id);
}
+void AccessibilityTreeManager::show_focus_on_root()
+{
+ m_focus_shown_on_root = true;
+ for (auto& [id, node] : m_nodes)
+ node.is_focused = (id == m_root_id);
+}
+
Optional<i64> AccessibilityTreeManager::focused_node_id() const
{
for (auto const& [id, node] : m_nodes) {
diff --git a/Libraries/LibWebView/AccessibilityTreeManager.h b/Libraries/LibWebView/AccessibilityTreeManager.h
index 62aabf8e705..c3387343729 100644
--- a/Libraries/LibWebView/AccessibilityTreeManager.h
+++ b/Libraries/LibWebView/AccessibilityTreeManager.h
@@ -24,12 +24,22 @@ public:
// too deep) changes nothing, and announces nothing: The caller should get the whole tree again instead.
Optional<Vector<i64>> apply_delta(AccessibilityTreeDelta const&);
+ // The same, for the trees WebContent numbers as it sends them: A whole tree replaces the tree held, and a change
+ // applies only to the tree with the number it names. No change applies to a whole tree that had to be repaired to
+ // hold, since that's no longer the tree WebContent changes: Each update then takes the whole tree again.
+ void update_tree(Vector<AccessibilityNodeData>, u64 sequence);
+ Optional<Vector<i64>> apply_delta(AccessibilityTreeDelta const&, u64 base_sequence, u64 sequence);
+
Function<void(String, String)> on_live_region_changed;
AccessibilityNodeData const* node(i64 id) const;
AccessibilityNodeData const* root() const;
AccessibilityNodeData const* hit_test(Gfx::IntPoint point) const;
+ // Marks the node WebContent reports focused.
void set_focused_node(i64 node_id);
+ // Marks the root focused for the assistive technology alone, until the next tree update puts back the focus that
+ // WebContent reports.
+ void show_focus_on_root();
Optional<i64> focused_node_id() const;
i64 root_id() const { return m_root_id; }
@@ -47,6 +57,10 @@ private:
HashMap<i64, AccessibilityNodeData> m_nodes;
i64 m_root_id { -1 };
+ u64 m_sequence { 0 };
+ bool m_whole_tree_was_repaired { false };
+ Optional<i64> m_focused_id_from_content;
+ bool m_focus_shown_on_root { false };
u64 m_generation { 0 };
};
diff --git a/Libraries/LibWebView/ViewImplementation.h b/Libraries/LibWebView/ViewImplementation.h
index 9ddf06cb960..112c8a5f5a8 100644
--- a/Libraries/LibWebView/ViewImplementation.h
+++ b/Libraries/LibWebView/ViewImplementation.h
@@ -626,7 +626,8 @@ public:
Function<void(Optional<JsonObject>)> on_received_current_grid;
Function<void(Optional<JsonObject>)> on_received_current_flexbox;
Function<void(JsonObject)> on_received_accessibility_tree;
- Function<void(Vector<AccessibilityNodeData>)> on_accessibility_tree_received;
+ Function<void(u64 sequence, Vector<AccessibilityNodeData>)> on_accessibility_tree_received;
+ Function<void(u64 base_sequence, u64 sequence, AccessibilityTreeDelta)> on_accessibility_tree_changed;
Function<void(i64)> on_accessibility_focus_changed;
Function<void(Web::UniqueNodeID)> on_received_hovered_node_id;
Function<void(Mutation)> on_dom_mutation_received;
diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cpp
index f0c7fc833eb..026ae7a84d2 100644
--- a/Libraries/LibWebView/WebContentPage.cpp
+++ b/Libraries/LibWebView/WebContentPage.cpp
@@ -1150,11 +1150,19 @@ void WebContentPage::did_inspect_accessibility_tree(String accessibility_tree)
}
}
-void WebContentPage::did_get_accessibility_tree(Vector<AccessibilityNodeData> nodes)
+void WebContentPage::did_get_accessibility_tree(u64 sequence, Vector<AccessibilityNodeData> nodes)
{
if (displays_tab()) {
if (view().on_accessibility_tree_received)
- view().on_accessibility_tree_received(move(nodes));
+ view().on_accessibility_tree_received(sequence, move(nodes));
+ }
+}
+
+void WebContentPage::did_change_accessibility_tree(u64 base_sequence, u64 sequence, AccessibilityTreeDelta delta)
+{
+ if (displays_tab()) {
+ if (view().on_accessibility_tree_changed)
+ view().on_accessibility_tree_changed(base_sequence, sequence, move(delta));
}
}
diff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.h
index c5b8e80768e..43266466105 100644
--- a/Libraries/LibWebView/WebContentPage.h
+++ b/Libraries/LibWebView/WebContentPage.h
@@ -228,7 +228,8 @@ private:
virtual void did_inspect_current_flexbox(String flexbox_layout) override;
virtual void did_inspect_indexed_database(u64 request_id, String result) override;
virtual void did_inspect_accessibility_tree(String accessibility_tree) override;
- virtual void did_get_accessibility_tree(Vector<AccessibilityNodeData> nodes) override;
+ virtual void did_get_accessibility_tree(u64 sequence, Vector<AccessibilityNodeData> nodes) override;
+ virtual void did_change_accessibility_tree(u64 base_sequence, u64 sequence, AccessibilityTreeDelta delta) override;
virtual void did_accessibility_focus_change(i64 focused_node_id) override;
virtual void did_get_hovered_node_id(Web::UniqueNodeID node_id) override;
virtual void did_get_node_id_at_position(u64 request_id, Web::UniqueNodeID node_id) override;
diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cpp
index 897601a9a4e..a73635dca0f 100644
--- a/Services/WebContent/ConnectionFromClient.cpp
+++ b/Services/WebContent/ConnectionFromClient.cpp
@@ -1981,14 +1981,7 @@ void ConnectionFromClient::request_accessibility_tree(Web::PageId page_id)
// path, so they pay for neither.
if (auto page = this->page(page_id); page.has_value()) {
page->page().set_accessibility_interested(true);
- // A request can arrive after the tab's document moved to another process, which leaves this page's traversable
- // remote, with no document of its own to report.
- if (!page->page().has_local_traversable())
- return;
- if (auto doc = page->page().local_traversable()->active_document()) {
- doc->update_layout(Web::DOM::UpdateLayoutReason::InspectAccessibilityTree);
- async_did_get_accessibility_tree(page_id, doc->build_accessibility_node_data());
- }
+ page->publish_accessibility_tree(true);
}
}
diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cpp
index 1709a536695..8cd5faa478d 100644
--- a/Services/WebContent/PageClient.cpp
+++ b/Services/WebContent/PageClient.cpp
@@ -1181,14 +1181,7 @@ void PageClient::schedule_accessibility_tree_update()
m_accessibility_update_timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(200), [this] {
if (m_is_closed)
return;
- // The tab's document can move to another process before the timer fires, which leaves this page's
- // traversable remote, with no document of its own to report.
- if (!page().has_local_traversable())
- return;
- if (auto doc = page().local_traversable()->active_document()) {
- doc->update_layout(Web::DOM::UpdateLayoutReason::InspectAccessibilityTree);
- client().async_did_get_accessibility_tree(m_id, doc->build_accessibility_node_data());
- }
+ publish_accessibility_tree(false);
});
}
@@ -1202,6 +1195,28 @@ void PageClient::schedule_accessibility_tree_update()
m_accessibility_update_timer->start();
}
+void PageClient::publish_accessibility_tree(bool whole_tree_requested)
+{
+ // The tab's document can move to another process, which leaves this page's traversable remote, with no document of
+ // its own to report.
+ if (!page().has_local_traversable())
+ return;
+ auto document = page().local_traversable()->active_document();
+ if (!document)
+ return;
+ document->update_layout(Web::DOM::UpdateLayoutReason::InspectAccessibilityTree);
+
+ auto update = m_accessibility_tree_publisher.publish(static_cast<i64>(document->unique_id().value()), document->build_accessibility_node_data(), whole_tree_requested);
+ update.visit(
+ [](WebView::AccessibilityTreePublisher::NothingChanged) { },
+ [&](WebView::AccessibilityTreePublisher::WholeTree& tree) {
+ client().async_did_get_accessibility_tree(m_id, tree.sequence, move(tree.nodes));
+ },
+ [&](WebView::AccessibilityTreePublisher::Change& change) {
+ client().async_did_change_accessibility_tree(m_id, change.base_sequence, change.sequence, move(change.delta));
+ });
+}
+
void PageClient::page_did_finish_test(Utf16String const& text)
{
if (auto* test_connection = client().test_connection())
diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.h
index cf96bf7e0ac..26bea514560 100644
--- a/Services/WebContent/PageClient.h
+++ b/Services/WebContent/PageClient.h
@@ -33,6 +33,7 @@
#include <LibWebCommon/WebDriver/Capabilities.h>
#include <LibWebCommon/WebDriver/Response.h>
#include <LibWebCommon/WebDriver/UserPrompt.h>
+#include <LibWebCommon/WebView/AccessibilityTreePublisher.h>
#include <LibWebCommon/WebView/ConsoleOutputBuffer.h>
#include <LibWebCommon/WebView/Geolocation.h>
#include <LibWebCommon/WebView/Mutation.h>
@@ -169,6 +170,8 @@ public:
void did_delete_all_cookies(u64 request_id);
void schedule_accessibility_tree_update();
+ // Sends the UI process what changed in the accessibility tree since the last tree sent, or the whole tree.
+ void publish_accessibility_tree(bool whole_tree_requested);
private:
struct PendingDOMMutation {
@@ -489,6 +492,7 @@ private:
Optional<Web::HTML::CrossProcessId> m_pending_root_navigable_id;
RefPtr<Core::Timer> m_accessibility_update_timer;
+ WebView::AccessibilityTreePublisher m_accessibility_tree_publisher;
RefPtr<Core::Timer> m_accessibility_focus_timer;
Optional<i64> m_pending_accessibility_focus;
diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipc
index 5c629faa330..6df58c7baef 100644
--- a/Services/WebContent/WebContentClient.ipc
+++ b/Services/WebContent/WebContentClient.ipc
@@ -154,7 +154,8 @@ endpoint WebContentClient routed by Web::PageId page_id
did_inspect_current_flexbox(Web::PageId page_id, String flexbox_layout) =|
did_inspect_indexed_database(Web::PageId page_id, u64 request_id, String result) =|
did_inspect_accessibility_tree(Web::PageId page_id, String accessibility_tree) =|
- did_get_accessibility_tree(Web::PageId page_id, Vector<WebView::AccessibilityNodeData> nodes) =|
+ did_get_accessibility_tree(Web::PageId page_id, u64 sequence, Vector<WebView::AccessibilityNodeData> nodes) =|
+ did_change_accessibility_tree(Web::PageId page_id, u64 base_sequence, u64 sequence, WebView::AccessibilityTreeDelta delta) =|
did_accessibility_focus_change(Web::PageId page_id, i64 focused_node_id) =|
did_get_hovered_node_id(Web::PageId page_id, Web::UniqueNodeID node_id) =|
did_get_node_id_at_position(Web::PageId page_id, u64 request_id, Web::UniqueNodeID node_id) =|
diff --git a/Tests/LibWebView/TestAccessibilityTreeManager.cpp b/Tests/LibWebView/TestAccessibilityTreeManager.cpp
index 2cd284977e5..3ed5315a39d 100644
--- a/Tests/LibWebView/TestAccessibilityTreeManager.cpp
+++ b/Tests/LibWebView/TestAccessibilityTreeManager.cpp
@@ -6,6 +6,7 @@
#include <AK/HashTable.h>
#include <LibTest/TestCase.h>
+#include <LibWebCommon/WebView/AccessibilityTreePublisher.h>
#include <LibWebView/AccessibilityTreeManager.h>
namespace {
@@ -512,3 +513,242 @@ TEST_CASE(delta_announces_live_region_changes)
EXPECT(manager.apply_delta(new_region).has_value());
EXPECT(announcements.is_empty());
}
+
+namespace {
+
+using Publisher = WebView::AccessibilityTreePublisher;
+
+Vector<WebView::AccessibilityNodeData> base_tree_nodes()
+{
+ Vector<WebView::AccessibilityNodeData> nodes;
+ nodes.append(make_node(0, -1, { 1, 2 }));
+ nodes.append(make_node(1, 0, { 3 }));
+ nodes.append(make_node(2, 0));
+ nodes.append(make_node(3, 1));
+ return nodes;
+}
+
+// Applies what the publisher sent to the manager, as the UI process does, and returns whether the manager took it.
+bool deliver(WebView::AccessibilityTreeManager& manager, Publisher::Update update)
+{
+ return update.visit(
+ [](Publisher::NothingChanged) { return true; },
+ [&](Publisher::WholeTree& tree) {
+ manager.update_tree(move(tree.nodes), tree.sequence);
+ return true;
+ },
+ [&](Publisher::Change& change) {
+ return manager.apply_delta(change.delta, change.base_sequence, change.sequence).has_value();
+ });
+}
+
+}
+
+TEST_CASE(publisher_sends_the_whole_tree_only_when_it_has_to)
+{
+ Publisher publisher;
+
+ auto first = publisher.publish(7, base_tree_nodes(), false);
+ EXPECT(first.has<Publisher::WholeTree>());
+ EXPECT_EQ(first.get<Publisher::WholeTree>().sequence, 1u);
+ EXPECT_EQ(first.get<Publisher::WholeTree>().nodes.size(), 4u);
+
+ EXPECT(publisher.publish(7, base_tree_nodes(), false).has<Publisher::NothingChanged>());
+
+ // Rename 3 and remove 2: The change holds just 3 and the root, whose children changed, and names 2 as removed.
+ auto nodes = base_tree_nodes();
+ nodes[0].child_ids = { 1 };
+ nodes.remove(2);
+ nodes[2].name = "renamed"_string;
+ auto second = publisher.publish(7, nodes, false);
+ EXPECT(second.has<Publisher::Change>());
+ auto const& change = second.get<Publisher::Change>();
+ EXPECT_EQ(change.base_sequence, 1u);
+ EXPECT_EQ(change.sequence, 2u);
+ EXPECT_EQ(change.delta.changed_nodes.size(), 2u);
+ EXPECT_EQ(change.delta.changed_nodes[0].id, 0);
+ EXPECT_EQ(change.delta.changed_nodes[1].id, 3);
+ EXPECT_EQ(change.delta.removed_ids, Vector<i64> { 2 });
+
+ // The whole tree goes out when the UI process asks for it, and for a new document.
+ auto requested = publisher.publish(7, nodes, true);
+ EXPECT(requested.has<Publisher::WholeTree>());
+ EXPECT_EQ(requested.get<Publisher::WholeTree>().sequence, 3u);
+ auto new_document = publisher.publish(8, nodes, false);
+ EXPECT(new_document.has<Publisher::WholeTree>());
+ EXPECT_EQ(new_document.get<Publisher::WholeTree>().sequence, 4u);
+}
+
+TEST_CASE(change_to_a_tree_the_manager_does_not_hold_is_rejected)
+{
+ Publisher publisher;
+ WebView::AccessibilityTreeManager manager;
+ EXPECT(deliver(manager, publisher.publish(7, base_tree_nodes(), false)));
+
+ // The manager misses a change, so the next one names a tree it doesn't hold.
+ auto nodes = base_tree_nodes();
+ nodes[3].name = "first"_string;
+ (void)publisher.publish(7, nodes, false);
+ nodes[3].name = "second"_string;
+ auto before = describe_tree(manager);
+ EXPECT(!deliver(manager, publisher.publish(7, nodes, false)));
+ EXPECT_EQ(describe_tree(manager), before);
+
+ // The whole tree brings it back in step, and the changes after it apply again.
+ EXPECT(deliver(manager, publisher.publish(7, nodes, true)));
+ nodes[3].name = "third"_string;
+ EXPECT(deliver(manager, publisher.publish(7, nodes, false)));
+ EXPECT_EQ(manager.node(3)->name, "third"sv);
+}
+
+TEST_CASE(changes_the_publisher_sends_keep_the_manager_tree_identical)
+{
+ // A tree held as parent and child lists, edited at random, and serialized in tree order the way a document builds
+ // its node data.
+ struct Node {
+ i64 parent { -1 };
+ Vector<i64> children;
+ String name;
+ };
+ HashMap<i64, Node> tree;
+ tree.set(0, {});
+ i64 next_id = 1;
+
+ u64 state = 0x9e3779b97f4a7c15;
+ auto random = [&](size_t bound) -> size_t {
+ state = state * 6364136223846793005ULL + 1442695040888963407ULL;
+ return static_cast<size_t>((state >> 33) % bound);
+ };
+ auto random_node = [&]() {
+ auto keys = tree.keys();
+ return keys[random(keys.size())];
+ };
+ auto is_in_subtree = [&](i64 id, i64 subtree_root) {
+ for (auto current = id; current != -1; current = tree.get(current)->parent) {
+ if (current == subtree_root)
+ return true;
+ }
+ return false;
+ };
+ auto serialize = [&]() {
+ Vector<WebView::AccessibilityNodeData> nodes;
+ Vector<i64> stack { 0 };
+ while (!stack.is_empty()) {
+ auto id = stack.take_last();
+ auto const& node = *tree.get(id);
+ auto data = make_node(id, node.parent, node.children);
+ data.name = node.name;
+ nodes.append(move(data));
+ for (size_t i = node.children.size(); i > 0; --i)
+ stack.append(node.children[i - 1]);
+ }
+ return nodes;
+ };
+
+ Publisher publisher;
+ WebView::AccessibilityTreeManager manager;
+ for (size_t round = 0; round < 400; ++round) {
+ for (size_t edit = 0; edit < 5; ++edit) {
+ auto kind = tree.size() < 3 ? 0 : random(5);
+ if (kind == 0) {
+ // Insert a new node.
+ auto parent = random_node();
+ auto& children = tree.find(parent)->value.children;
+ children.insert(random(children.size() + 1), next_id);
+ tree.set(next_id, { parent, {}, MUST(String::formatted("node {}", next_id)) });
+ ++next_id;
+ } else if (kind == 1) {
+ // Remove a subtree.
+ auto root = random_node();
+ if (root == 0)
+ continue;
+ tree.find(tree.get(root)->parent)->value.children.remove_first_matching([&](i64 child) { return child == root; });
+ Vector<i64> doomed { root };
+ while (!doomed.is_empty()) {
+ auto id = doomed.take_last();
+ doomed.extend(tree.get(id)->children);
+ tree.remove(id);
+ }
+ } else if (kind == 2) {
+ // Move a subtree.
+ auto moved = random_node();
+ auto new_parent = random_node();
+ if (moved == 0 || is_in_subtree(new_parent, moved))
+ continue;
+ tree.find(tree.get(moved)->parent)->value.children.remove_first_matching([&](i64 child) { return child == moved; });
+ auto& children = tree.find(new_parent)->value.children;
+ children.insert(random(children.size() + 1), moved);
+ tree.find(moved)->value.parent = new_parent;
+ } else if (kind == 3) {
+ // Rename a node.
+ tree.find(random_node())->value.name = MUST(String::formatted("renamed in round {}", round));
+ } else {
+ // Reverse a node's children.
+ auto& children = tree.find(random_node())->value.children;
+ children.reverse();
+ }
+ }
+
+ auto nodes = serialize();
+ auto update = publisher.publish(1, nodes, false);
+ // After the first round, nothing goes out but changes.
+ if (round > 0)
+ EXPECT(!update.has<Publisher::WholeTree>());
+ EXPECT(deliver(manager, move(update)));
+
+ EXPECT_EQ(manager.root_id(), 0);
+ size_t reachable = assert_valid_tree_and_collect(manager).size();
+ EXPECT_EQ(reachable, nodes.size());
+ for (auto const& expected : nodes) {
+ auto const* held = manager.node(expected.id);
+ EXPECT(held && *held == expected);
+ }
+ // And every node removed is gone, not just unreachable.
+ for (i64 id = 0; id < next_id; ++id) {
+ if (!tree.contains(id))
+ EXPECT(!manager.node(id));
+ }
+ }
+}
+
+TEST_CASE(no_change_applies_to_a_repaired_whole_tree)
+{
+ // A chain deeper than the manager allows: It keeps the chain only down to its depth limit, so it holds a tree that
+ // isn't the one WebContent changes, and every change has to be refused for the whole tree to come again.
+ Vector<WebView::AccessibilityNodeData> nodes;
+ for (i64 id = 0; id <= 1001; ++id)
+ nodes.append(make_node(id, id - 1, id < 1001 ? Vector<i64> { id + 1 } : Vector<i64> {}));
+ Publisher publisher;
+ WebView::AccessibilityTreeManager manager;
+ EXPECT(deliver(manager, publisher.publish(7, nodes, false)));
+ EXPECT(!manager.node(1001));
+
+ // Move 500 under the root: 1001 would fit again, but only a whole tree can bring it.
+ nodes[0].child_ids = { 1, 500 };
+ nodes[499].child_ids = {};
+ nodes[500].parent_id = 0;
+ EXPECT(!deliver(manager, publisher.publish(7, nodes, false)));
+ EXPECT(deliver(manager, publisher.publish(7, nodes, true)));
+ EXPECT(manager.node(1001));
+}
+
+TEST_CASE(root_focus_shown_for_the_assistive_technology_lasts_until_the_next_change)
+{
+ Publisher publisher;
+ WebView::AccessibilityTreeManager manager;
+ auto nodes = base_tree_nodes();
+ nodes[3].is_focused = true;
+ EXPECT(deliver(manager, publisher.publish(7, nodes, false)));
+ EXPECT_EQ(manager.focused_node_id(), 3);
+
+ manager.show_focus_on_root();
+ EXPECT(manager.root()->is_focused);
+ EXPECT(!manager.node(3)->is_focused);
+
+ // A change that doesn't touch 3 still puts back the focus WebContent reports, as a whole tree would.
+ nodes[2].name = "renamed"_string;
+ EXPECT(deliver(manager, publisher.publish(7, nodes, false)));
+ EXPECT(!manager.root()->is_focused);
+ EXPECT(manager.node(3)->is_focused);
+ EXPECT_EQ(manager.focused_node_id(), 3);
+}
diff --git a/UI/Qt/WebContentView.cpp b/UI/Qt/WebContentView.cpp
index 545f231f0f5..7bfd48cf600 100644
--- a/UI/Qt/WebContentView.cpp
+++ b/UI/Qt/WebContentView.cpp
@@ -242,60 +242,25 @@ WebContentView::WebContentView(QWidget* window, Optional<WebView::CanonicalTrave
QAccessible::installActivationObserver(this);
#endif
- on_accessibility_tree_received = [this](auto nodes) {
- m_accessibility_manager->update_tree(AK::move(nodes));
-
-#if defined(Q_OS_MACOS)
- // Only the first tree for a page announces the load. WebContent rebuilds the tree on DOM mutations too, and
- // announcing each of those would move VoiceOver's cursor back to the top of the page while the user is reading
- // it. Same gate as the AT-SPI focus post in the branch below.
- // NB: A page load never moves the keyboard focus, with or without an assistive technology. For example, a new
- // tab's location editor keeps the focus while the new tab page loads.
- auto const announce_load = !m_posted_initial_accessibility_focus && m_accessibility_manager && !m_accessibility_manager->is_empty();
- if (announce_load)
- m_posted_initial_accessibility_focus = true;
- // An assistive technology that turned up mid-page got no focused element from its first queries: The first tree
- // has AppKit look the focus up again — if the page has the keyboard focus (update_accessibility_tree() checks).
- auto const report_focus = m_report_accessibility_focus_with_next_tree && m_accessibility_manager && !m_accessibility_manager->is_empty();
- if (report_focus)
- m_report_accessibility_focus_with_next_tree = false;
- QTimer::singleShot(100, this, [this, announce_load, report_focus] {
- update_accessibility_tree(this, announce_load, report_focus);
- });
-#elif !defined(Q_OS_WIN)
- // Prune interfaces for nodes no longer in the tree.
- QList<i64> stale_ids;
- for (auto it = m_accessibility_elements.begin(); it != m_accessibility_elements.end(); ++it) {
- if (!it.value()->isValid())
- stale_ids.append(it.key());
- }
- for (auto id : stale_ids) {
- auto* iface = m_accessibility_elements.take(id);
- QAccessible::deleteAccessibleInterface(QAccessible::uniqueId(iface));
- }
-
- // An assistive technology that turned up mid-page found no tree to take the focus from: Tell it where the focus
- // is now that there's one — if the page has the keyboard focus at all.
- if (m_report_accessibility_focus_with_next_tree && m_accessibility_manager && !m_accessibility_manager->is_empty()) {
- m_report_accessibility_focus_with_next_tree = false;
- if (hasFocus())
- announce_accessibility_focus();
- }
+ on_accessibility_tree_received = [this](u64 sequence, auto nodes) {
+ m_accessibility_whole_tree_pending = false;
+ m_accessibility_manager->update_tree(AK::move(nodes), sequence);
+ did_update_accessibility_tree({});
+ };
- // Post a Focus AT-SPI2 event on the document root the first time a tree arrives. This is what lets Orca's
- // browse-mode commands (H/K/L structural nav) work on page load — without the user having to Tab/click into the
- // page first. The event is posted unconditionally — even when the address bar has Qt focus — because our Orca
- // script re-suspends browse-mode commands when it later sees a focus event for an editable chrome widget. So if
- // the user explicitly focuses the address bar (Ctrl+L, mouse click), typing there still works. Firing this on
- // every subsequent tree update would be wrong: it would re-focus the document root while the user is
- // mid-navigation — causing Orca to re-present the current structural-nav target.
- if (!m_posted_initial_accessibility_focus && m_accessibility_manager && !m_accessibility_manager->is_empty()) {
- m_posted_initial_accessibility_focus = true;
- QTimer::singleShot(1000, this, [this] {
- notify_accessibility_focus_on_document_root();
- });
+ on_accessibility_tree_changed = [this](u64 base_sequence, u64 sequence, auto delta) {
+ // Once the whole tree has been asked for, every change before it arrives is to a tree this view doesn't hold.
+ if (m_accessibility_whole_tree_pending)
+ return;
+ auto removed_ids = m_accessibility_manager->apply_delta(delta, base_sequence, sequence);
+ if (!removed_ids.has_value()) {
+ // A change to a tree this view doesn't hold (one it dropped while it didn't display the tab, e.g.), or one
+ // that doesn't fit the tree it holds: Start over from the whole tree.
+ m_accessibility_whole_tree_pending = true;
+ request_accessibility_tree();
+ return;
}
-#endif
+ did_update_accessibility_tree(removed_ids.release_value());
};
on_accessibility_focus_changed = [this](i64 node_id) {
@@ -2115,7 +2080,7 @@ void WebContentView::notify_accessibility_focus_on_document_root()
// Mark the root as focused in the shared tree data *before* posting the Qt Focus event. Otherwise, state()
// reports focused=false and Qt's AT-SPI2 bridge emits the focus event with detail1=0 (focus lost) rather
// than detail1=1 (focus gained) — defeating the announcement.
- m_accessibility_manager->set_focused_node(root->id);
+ m_accessibility_manager->show_focus_on_root();
auto* root_iface = accessibility_interface_for_node(root->id);
if (root_iface) {
QAccessibleEvent focus_event(root_iface, QAccessible::Focus);
@@ -2145,6 +2110,69 @@ void WebContentView::announce_accessibility_focus()
}
#endif
+void WebContentView::did_update_accessibility_tree([[maybe_unused]] Optional<Vector<i64>> removed_ids)
+{
+#if defined(Q_OS_MACOS)
+ // Only the first tree for a page announces the load. WebContent rebuilds the tree on DOM mutations too, and
+ // announcing each of those would move VoiceOver's cursor back to the top of the page while the user is reading
+ // it. Same gate as the AT-SPI focus post in the branch below.
+ // NB: A page load never moves the keyboard focus, with or without an assistive technology. For example, a new
+ // tab's location editor keeps the focus while the new tab page loads.
+ auto const announce_load = !m_posted_initial_accessibility_focus && m_accessibility_manager && !m_accessibility_manager->is_empty();
+ if (announce_load)
+ m_posted_initial_accessibility_focus = true;
+ // An assistive technology that turned up mid-page got no focused element from its first queries: The first tree
+ // has AppKit look the focus up again — if the page has the keyboard focus (update_accessibility_tree() checks).
+ auto const report_focus = m_report_accessibility_focus_with_next_tree && m_accessibility_manager && !m_accessibility_manager->is_empty();
+ if (report_focus)
+ m_report_accessibility_focus_with_next_tree = false;
+ QTimer::singleShot(100, this, [this, announce_load, report_focus, removed_ids = AK::move(removed_ids)] {
+ update_accessibility_tree(this, announce_load, report_focus, removed_ids);
+ });
+#elif !defined(Q_OS_WIN)
+ // Prune interfaces for nodes no longer in the tree: after a change, the ones it removed; after a whole new tree,
+ // every one whose node is gone.
+ QList<i64> stale_ids;
+ if (removed_ids.has_value()) {
+ for (auto id : *removed_ids) {
+ if (m_accessibility_elements.contains(id))
+ stale_ids.append(id);
+ }
+ } else {
+ for (auto it = m_accessibility_elements.begin(); it != m_accessibility_elements.end(); ++it) {
+ if (!it.value()->isValid())
+ stale_ids.append(it.key());
+ }
+ }
+ for (auto id : stale_ids) {
+ auto* iface = m_accessibility_elements.take(id);
+ QAccessible::deleteAccessibleInterface(QAccessible::uniqueId(iface));
+ }
+
+ // An assistive technology that turned up mid-page found no tree to take the focus from: Tell it where the focus
+ // is now that there's one — if the page has the keyboard focus at all.
+ if (m_report_accessibility_focus_with_next_tree && m_accessibility_manager && !m_accessibility_manager->is_empty()) {
+ m_report_accessibility_focus_with_next_tree = false;
+ if (hasFocus())
+ announce_accessibility_focus();
+ }
+
+ // Post a Focus AT-SPI2 event on the document root the first time a tree arrives. This is what lets Orca's
+ // browse-mode commands (H/K/L structural nav) work on page load — without the user having to Tab/click into the
+ // page first. The event is posted unconditionally — even when the address bar has Qt focus — because our Orca
+ // script re-suspends browse-mode commands when it later sees a focus event for an editable chrome widget. So if
+ // the user explicitly focuses the address bar (Ctrl+L, mouse click), typing there still works. Firing this on
+ // every subsequent tree update would be wrong: it would re-focus the document root while the user is
+ // mid-navigation — causing Orca to re-present the current structural-nav target.
+ if (!m_posted_initial_accessibility_focus && m_accessibility_manager && !m_accessibility_manager->is_empty()) {
+ m_posted_initial_accessibility_focus = true;
+ QTimer::singleShot(1000, this, [this] {
+ notify_accessibility_focus_on_document_root();
+ });
+ }
+#endif
+}
+
#if !defined(Q_OS_WIN)
void WebContentView::fetch_accessibility_tree()
{
diff --git a/UI/Qt/WebContentView.h b/UI/Qt/WebContentView.h
index 886ab2d352a..369a0089c55 100644
--- a/UI/Qt/WebContentView.h
+++ b/UI/Qt/WebContentView.h
@@ -302,10 +302,15 @@ private:
friend class WebContentViewAccessible;
#endif
+ // Takes the steps that follow each tree update: after a change, with the IDs of the nodes it removed.
+ void did_update_accessibility_tree(Optional<Vector<i64>> removed_ids);
+
OwnPtr<WebView::AccessibilityTreeManager> m_accessibility_manager;
bool m_posted_initial_accessibility_focus { false };
// Set once this view has asked WebContent for the tree; from then on, WebContent pushes every change on its own.
bool m_requested_accessibility_tree { false };
+ // Set while the whole tree is on its way, after a change this view couldn't apply.
+ bool m_accessibility_whole_tree_pending { false };
#if !defined(Q_OS_WIN)
// Set when an assistive technology turns up mid-page: The next tree to arrive reports the focus to it.
bool m_report_accessibility_focus_with_next_tree { false };
diff --git a/UI/Qt/WebContentViewAccessibility.h b/UI/Qt/WebContentViewAccessibility.h
index 568c64be025..c3143bf5953 100644
--- a/UI/Qt/WebContentViewAccessibility.h
+++ b/UI/Qt/WebContentViewAccessibility.h
@@ -21,7 +21,7 @@ void install_accessibility(WebContentView* view);
// announce_load: a page's first tree announces the load and has AppKit look the focus up again; the trees DOM mutations
// bring do neither. report_focus: the first tree an assistive technology that arrived mid-page gets has AppKit look the
// focus up again. Both only while the view holds the keyboard focus in the key window.
-void update_accessibility_tree(WebContentView* view, bool announce_load, bool report_focus);
+void update_accessibility_tree(WebContentView* view, bool announce_load, bool report_focus, Optional<Vector<i64>> const& removed_ids);
void post_accessibility_focus_changed(WebContentView* view, i64 node_id);
void post_accessibility_announcement(String const& text, String const& live_value);
diff --git a/UI/Qt/WebContentViewAccessibility.mm b/UI/Qt/WebContentViewAccessibility.mm
index 5bf12015589..7b8411cbb88 100644
--- a/UI/Qt/WebContentViewAccessibility.mm
+++ b/UI/Qt/WebContentViewAccessibility.mm
@@ -459,7 +459,7 @@ static bool view_holds_keyboard_focus(WebContentView* view, WebContentAccessibil
return overlay.window.isKeyWindow && view->hasFocus();
}
-void update_accessibility_tree(WebContentView* view, bool announce_load, bool report_focus)
+void update_accessibility_tree(WebContentView* view, bool announce_load, bool report_focus, Optional<Vector<i64>> const& removed_ids)
{
auto* overlay = get_overlay(view);
if (!overlay)
@@ -472,10 +472,20 @@ void update_accessibility_tree(WebContentView* view, bool announce_load, bool re
// assistive technology holds stay good across a mutation. Elements of nodes that are gone get invalidated before
// they leave the cache: they hold a raw pointer into the manager, and invalidating them makes sure nothing that
// still references one can reach it through them.
+ // After a change, those are the nodes it removed; after a whole new tree, every node no longer in it.
NSMutableArray<NSNumber*>* stale_keys = [NSMutableArray array];
- for (NSNumber* key in overlay.elements) {
- if (!overlay.manager->node([key longLongValue]))
- [stale_keys addObject:key];
+ if (removed_ids.has_value()) {
+ // A node can come back before this runs (in a whole tree asked for meanwhile, e.g.), and its element stays.
+ for (auto id : *removed_ids) {
+ NSNumber* key = @(id);
+ if (overlay.elements[key] && !overlay.manager->node(id))
+ [stale_keys addObject:key];
+ }
+ } else {
+ for (NSNumber* key in overlay.elements) {
+ if (!overlay.manager->node([key longLongValue]))
+ [stale_keys addObject:key];
+ }
}
for (NSNumber* key in stale_keys) {
[overlay.elements[key] invalidate];