Truly independent web browser
LibWeb: Read accessible character offsets from layout’s glyph runs
sideshowbarkerf7ecdca8c764
diff --git a/Libraries/LibWeb/DOM/AccessibilityTreeNode.cpp b/Libraries/LibWeb/DOM/AccessibilityTreeNode.cppindex 2daf2d5f737..b6c637ec988 100644--- a/Libraries/LibWeb/DOM/AccessibilityTreeNode.cpp+++ b/Libraries/LibWeb/DOM/AccessibilityTreeNode.cpp@@ -4,6 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/AnyOf.h>#include <AK/Utf16String.h>#include <AK/Utf8View.h>#include <LibGC/Heap.h>@@ -663,6 +664,31 @@ void AccessibilityTreeNode::serialize_tree_as_node_data(Vector<WebView::Accessibtext_origin.set_y(min(text_origin.y(), rendered.rect.y()));}auto text_utf16 = text_node.data().utf16_view();++ // The document-absolute x where each DOM offset's character starts, and where each fragment's text+ // ends, from the glyph runs layout shaped the text into.+ struct CharacterXPositions {+ Vector<Optional<float>> start_x;+ Vector<Optional<float>> fragment_end_x;+ };+ CharacterXPositions x_positions;+ x_positions.start_x.resize(text_utf16.length_in_code_units() + 1);+ x_positions.fragment_end_x.resize(text_utf16.length_in_code_units() + 1);+ Layout::RustFFI::layout_script_text_character_x_positions(+ layout->document_host(), Layout::Node::slot_id(layout), &x_positions,+ [](void* context, size_t offset, float x, bool is_fragment_end) {+ auto& positions = *static_cast<CharacterXPositions*>(context);+ auto& list = is_fragment_end ? positions.fragment_end_x : positions.start_x;+ if (offset < list.size())+ list[offset] = x;+ });+ auto origin_x = text_origin.x().to_float();+ auto known_x = [&](Vector<Optional<float>> const& list, size_t offset) -> Optional<float> {+ if (offset >= list.size() || !list[offset].has_value())+ return {};+ return *list[offset] - origin_x;+ };+// Where the rendered text last reached: the position of the characters no line renders.Optional<Gfx::IntPoint> rendered_end;for (auto const& [line, line_rect] : rendered_lines) {@@ -682,16 +708,49 @@ void AccessibilityTreeNode::serialize_tree_as_node_data(Vector<WebView::Accessibnode_data.character_offsets.append(gap_position);node_data.line_break_character_offsets.append(node_data.line_break_character_offsets.is_empty() ? 0 : static_cast<i32>(line_character_start));node_data.line_heights.append(line_height);- // Walk each character in the line, accumulating x within the line.- float cumulative_x = static_cast<float>(line_left_x);+ // Each character's x is where layout's glyph run puts it. A character layout gives no position+ // to (whitespace that collapsed away) takes no width: It sits where the next positioned character+ // on the line starts, or where the line ends. Only a line layout positions nothing on (e.g. vertical+ // text) falls back to advancing each character by its own width, shaped on its own.auto utf8_start = view.byte_offset_of(line_character_start);auto utf8_end = view.byte_offset_of(line_character_end);Utf8View line_view { utf8.substring_view(utf8_start, utf8_end - utf8_start) };+ Vector<u32> line_code_points;+ Vector<Optional<float>> line_x;+ size_t code_unit_offset = line.start_offset;for (u32 code_point : line_view) {- node_data.character_offsets.append(Gfx::IntPoint { static_cast<i32>(cumulative_x), line_top_y });- cumulative_x += font ? glyph_advance(*font, code_point) : 0.0f;+ line_code_points.append(code_point);+ line_x.append(known_x(x_positions.start_x, code_unit_offset));+ code_unit_offset += code_point > 0xFFFF ? 2 : 1;+ }+ auto line_end_x = known_x(x_positions.fragment_end_x, line.end_offset);+ bool layout_positions_line = line_end_x.has_value() || any_of(line_x, [](auto const& x) { return x.has_value(); });++ float end_x = static_cast<float>(line_left_x);+ if (layout_positions_line) {+ Optional<float> next_x = line_end_x;+ for (size_t i = line_x.size(); i-- > 0;) {+ if (line_x[i].has_value())+ next_x = line_x[i];+ else+ line_x[i] = next_x;+ }+ Optional<float> previous_x;+ for (auto& x : line_x) {+ if (!x.has_value())+ x = previous_x.value_or(static_cast<float>(line_left_x));+ previous_x = x;+ }+ end_x = line_end_x.value_or(previous_x.value_or(static_cast<float>(line_left_x)));+ } else {+ for (size_t i = 0; i < line_x.size(); ++i) {+ line_x[i] = end_x;+ end_x += font ? glyph_advance(*font, line_code_points[i]) : 0.0f;+ }}- rendered_end = Gfx::IntPoint { static_cast<i32>(cumulative_x), line_top_y };+ for (auto const& x : line_x)+ node_data.character_offsets.append(Gfx::IntPoint { static_cast<i32>(*x), line_top_y });+ rendered_end = Gfx::IntPoint { static_cast<i32>(end_x), line_top_y };}// A trailing run that renders on no line, likewise.while (rendered_end.has_value() && node_data.character_offsets.size() < view.length())diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex 2de1b4acd78..29ce0f300ab 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -131,6 +131,7 @@#include <LibWebCommon/Page/InputEvent.h>#include <LibWebCommon/StorageAPI/StorageEndpoint.h>#include <LibWebCommon/WebDriver/Response.h>+#include <LibWebCommon/WebView/AccessibilityNodeData.h>namespace Web::Internals {@@ -1877,6 +1878,25 @@ Utf16String Internals::dump_accessibility_tree()return window().associated_document().dump_accessibility_tree_as_json();}+String Internals::accessibility_character_offsets(GC::Ref<DOM::Node> node)+{+ auto& document = node->document();+ document.update_layout(DOM::UpdateLayoutReason::InspectAccessibilityTree);+ auto node_id = static_cast<i64>(node->unique_id().value());+ StringBuilder builder;+ for (auto const& node_data : document.build_accessibility_node_data()) {+ if (node_data.id != node_id)+ continue;+ for (auto const& offset : node_data.character_offsets) {+ if (!builder.is_empty())+ builder.append(' ');+ builder.appendff("{},{}", offset.x(), offset.y());+ }+ break;+ }+ return builder.to_string_without_validation();+}+Utf16String Internals::dump_layout_tree(GC::Ref<DOM::Node> node){// The test API's read of the render state of the node's document.diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.hindex e82300aea89..73d08007c7e 100644--- a/Libraries/LibWeb/Internals/Internals.h+++ b/Libraries/LibWeb/Internals/Internals.h@@ -226,6 +226,7 @@ public:Utf16String dump_display_list();Utf16String dump_accessibility_tree();+ String accessibility_character_offsets(GC::Ref<DOM::Node>);Utf16String dump_layout_tree(GC::Ref<DOM::Node>);Utf16String dump_stacking_context_tree();Utf16String stacking_context_structure_verification_report();diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idlindex ce7ccca82b1..6460b3e48ab 100644--- a/Libraries/LibWeb/Internals/Internals.idl+++ b/Libraries/LibWeb/Internals/Internals.idl@@ -227,6 +227,8 @@ interface Internals {DOMString dumpDisplayList();DOMString dumpAccessibilityTree();+ // The per-character offsets that the accessibility tree reports for a text node, as space-separated "x,y" pairs.+ DOMString accessibilityCharacterOffsets(Node node);DOMString dumpLayoutTree(Node node);DOMString dumpStackingContextTree();DOMString stackingContextStructureVerificationReport();diff --git a/Libraries/LibWeb/Rust/src/layout/rendered_text.rs b/Libraries/LibWeb/Rust/src/layout/rendered_text.rsindex 33a4da0ce10..677abf304ac 100644--- a/Libraries/LibWeb/Rust/src/layout/rendered_text.rs+++ b/Libraries/LibWeb/Rust/src/layout/rendered_text.rs@@ -377,6 +377,70 @@ impl RenderedText {);rendered_text_offset_for_dom_offset(&self.edits, self.dom_start_offset, offset, boundary).min(self.text.len())}++ /// Calls `callback` with each DOM offset from `start` through `end`, in order, and the rendered offset that+ /// rendered_text_offset_for_dom_offset() maps it to, walking the edits once for the whole range rather than once+ /// per offset.+ pub(crate) fn for_each_rendered_text_offset_of_dom_offsets(+ &self,+ start: usize,+ end: usize,+ boundary: RenderedTextBoundary,+ mut callback: impl FnMut(usize, usize),+ ) {+ // Start past the edits that end before the first offset, since offsets only grow and the loop below would+ // just step over them; so a range late in a text with many edits doesn't walk them all again.+ let first = start.clamp(+ self.dom_start_offset,+ self.dom_start_offset + self.dom_length_in_code_units,+ );+ let mut edit_index = self+ .edits+ .partition_point(|edit| edit.dom_start_offset + edit.dom_length_in_code_units < first);+ let (mut previous_dom_end, mut previous_rendered_end) = match edit_index.checked_sub(1) {+ Some(index) => {+ let edit = &self.edits[index];+ (+ edit.dom_start_offset + edit.dom_length_in_code_units,+ edit.rendered_start_offset + edit.rendered_length_in_code_units,+ )+ }+ None => (self.dom_start_offset, 0),+ };+ for dom_offset in start..=end {+ let offset = dom_offset.clamp(+ self.dom_start_offset,+ self.dom_start_offset + self.dom_length_in_code_units,+ );+ let rendered_offset = loop {+ let Some(edit) = self.edits.get(edit_index) else {+ break previous_rendered_end + offset - previous_dom_end;+ };+ if offset < edit.dom_start_offset {+ break previous_rendered_end + offset - previous_dom_end;+ }+ let dom_end = edit.dom_start_offset + edit.dom_length_in_code_units;+ let rendered_end = edit.rendered_start_offset + edit.rendered_length_in_code_units;+ if offset <= dom_end {+ break if offset == edit.dom_start_offset {+ edit.rendered_start_offset+ } else if offset == dom_end {+ rendered_end+ } else {+ match boundary {+ RenderedTextBoundary::Start => edit.rendered_start_offset,+ RenderedTextBoundary::End => rendered_end,+ }+ };+ }+ // Offsets only grow, so an edit the offset is past is past every later offset too.+ previous_dom_end = dom_end;+ previous_rendered_end = rendered_end;+ edit_index += 1;+ };+ callback(dom_offset, rendered_offset.min(self.text.len()));+ }+ }}pub(super) fn rendered_text_offset_for_dom_offset(diff --git a/Libraries/LibWeb/Rust/src/layout/script_entries.rs b/Libraries/LibWeb/Rust/src/layout/script_entries.rsindex 9b70de0aee6..c3fa02382de 100644--- a/Libraries/LibWeb/Rust/src/layout/script_entries.rs+++ b/Libraries/LibWeb/Rust/src/layout/script_entries.rs@@ -223,6 +223,34 @@ pub extern "C" fn layout_script_text_caret_rect_in_dom_range(});}+/// Calls `push_position` with each DOM offset (in UTF-16 code units) of the text node `primary` that one of its+/// horizontal fragments renders, along with the document-absolute x coordinate where that offset's character starts,+/// read from the fragment's shaped glyph run. `is_fragment_end` marks the offset one past a fragment's last character,+/// whose x is where that fragment's text ends.+///+/// # Safety+///+/// The callback must be sound to call with `context`.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn layout_script_text_character_x_positions(+ host: &DocumentHost,+ primary: NodeSlotId,+ context: *mut c_void,+ push_position: unsafe extern "C" fn(*mut c_void, usize, f32, bool),+) {+ read_rows(host, |arena| {+ let fragments = arena.text_fragments(primary);+ crate::painting::text_fragment::for_each_fragment_of_nodes(arena, fragments.as_slice(), |_, _, fragment| {+ let end = fragment.dom_end_offset_in_node;+ crate::painting::text_fragment::for_each_dom_offset_x(arena, fragment, |dom_offset, x| {+ // SAFETY: The consumer copies the plain-data position synchronously.+ unsafe { push_position(context, dom_offset, x, dom_offset == end) };+ });+ true+ });+ });+}+#[unsafe(no_mangle)]pub extern "C" fn layout_script_text_caret_rect_for_position(host: &DocumentHost,diff --git a/Libraries/LibWeb/Rust/src/painting/text_fragment.rs b/Libraries/LibWeb/Rust/src/painting/text_fragment.rsindex 087d89729cd..a0fa71e44fc 100644--- a/Libraries/LibWeb/Rust/src/painting/text_fragment.rs+++ b/Libraries/LibWeb/Rust/src/painting/text_fragment.rs@@ -282,6 +282,57 @@ fn for_each_cluster_in_glyph_run(}}+/// Calls `callback` with each DOM offset (in UTF-16 code units) that the horizontal `fragment` renders, from its first+/// offset through the one past its last, along with the document-absolute x coordinate where that offset's character+/// starts (or, for the last one, where the fragment's text ends). The advances come from the fragment's shaped glyph+/// run, so kerning and ligatures are reflected; a cluster's advance is split evenly among its code units.+pub(crate) fn for_each_dom_offset_x(+ layout_arena: &impl PaintRead,+ fragment: &FragmentRecord,+ mut callback: impl FnMut(usize, f32),+) {+ if !is_horizontal(fragment) {+ return;+ }+ let Some(run) = &fragment.glyph_run else {+ return;+ };+ // FIXME: Report the positions of right-to-left text. Its glyphs are in visual order, so an advance accumulated in+ // glyph order doesn't belong to the character at the same logical offset.+ if run.glyphs.placed().any(|placed| placed.is_rtl) {+ return;+ }+ let Some(rendered_text) = layout_arena.rendered_text(fragment.layout_node) else {+ return;+ };+ let length = fragment.length_in_code_units;+ // advance_before[i] is the advance of the fragment's rendered text before its rendered offset i.+ let mut advance_before = vec![0.0f32; length + 1];+ let mut cursor = 0usize;+ for_each_cluster_in_glyph_run(&run.glyphs, length, |cluster_start, cluster_end, cluster_width| {+ let per_unit_advance = cluster_width / (cluster_end - cluster_start) as f32;+ for offset in cluster_start..cluster_end {+ advance_before[offset + 1] = advance_before[offset] + per_unit_advance;+ }+ cursor = cluster_end;+ true+ });+ // Code units past the last cluster take the end position.+ for offset in cursor..length {+ advance_before[offset + 1] = advance_before[offset];+ }+ let x = absolute_rect(layout_arena, fragment).x.to_float();+ rendered_text.for_each_rendered_text_offset_of_dom_offsets(+ fragment.dom_start_offset_in_node,+ fragment.dom_end_offset_in_node,+ crate::layout::RenderedTextBoundary::End,+ |dom_offset, rendered_offset| {+ let offset_in_fragment = rendered_offset.clamp(fragment.start, fragment.start + length) - fragment.start;+ callback(dom_offset, x + advance_before[offset_in_fragment]);+ },+ );+}+pub(crate) fn rect_for_selection_offsets(layout_arena: &impl PaintRead,fragment: &FragmentRecord,diff --git a/Tests/LibWeb/Text/expected/accessibility-tree-character-offsets.txt b/Tests/LibWeb/Text/expected/accessibility-tree-character-offsets.txtnew file mode 100644index 00000000000..80494eea630--- /dev/null+++ b/Tests/LibWeb/Text/expected/accessibility-tree-character-offsets.txt@@ -0,0 +1,15 @@+wrapping: 30 offsets for 30 characters+ rendered characters at layout's x: 26 of 26+ unrendered characters at the next rendered character's x: 2 of 2+ x decreases along a line: 0 times+ distinct line tops: 3+soft-hyphen: 5 offsets for 5 characters+ rendered characters at layout's x: 4 of 4+ unrendered characters at the next rendered character's x: 1 of 1+ x decreases along a line: 0 times+ distinct line tops: 1+uppercased: 27 offsets for 27 characters+ rendered characters at layout's x: 24 of 24+ unrendered characters at the next rendered character's x: 0 of 0+ x decreases along a line: 0 times+ distinct line tops: 4diff --git a/Tests/LibWeb/Text/input/accessibility-tree-character-offsets.html b/Tests/LibWeb/Text/input/accessibility-tree-character-offsets.htmlnew file mode 100644index 00000000000..c37587b5e2f--- /dev/null+++ b/Tests/LibWeb/Text/input/accessibility-tree-character-offsets.html@@ -0,0 +1,70 @@+<!DOCTYPE html>+<script src="include.js"></script>+<style>+ div {+ width: 120px;+ font: 16px SerenitySans;+ }+</style>+<!-- The accessibility tree reports each character of a text node at the position where layout renders it, relative to+ the top-left of the text: The x of each rendered character is where a range around just that character starts. A+ character that renders nothing (whitespace that collapsed away) takes no width: It's at the x of the next+ rendered character on its line. -->+<div id="wrapping">AVA Wave to the wrapped line</div>+<div id="soft-hyphen">ab­cd</div>+<div id="uppercased" style="text-transform: uppercase">straße straße straße straße</div>+<script>+ function check(id) {+ const text = document.getElementById(id).firstChild;+ const offsets = internals.accessibilityCharacterOffsets(text).split(" ").map(pair => pair.split(",").map(Number));+ println(`${id}: ${offsets.length} offsets for ${text.data.length} characters`);++ const range = document.createRange();+ range.selectNodeContents(text);+ const textRect = range.getBoundingClientRect();+ const rendered = [];+ for (let i = 0; i < text.data.length; i++) {+ range.setStart(text, i);+ range.setEnd(text, i + 1);+ const rects = range.getClientRects();+ rendered.push(rects.length > 0 && rects[0].width > 0 ? rects[0].x - textRect.x : null);+ }++ let renderedCount = 0;+ let matching = 0;+ let unrenderedCount = 0;+ let unrenderedMatching = 0;+ let decreases = 0;+ for (let i = 0; i < text.data.length; i++) {+ if (i > 0 && offsets[i][1] === offsets[i - 1][1] && offsets[i][0] < offsets[i - 1][0])+ decreases++;+ if (rendered[i] !== null) {+ renderedCount++;+ if (Math.abs(offsets[i][0] - rendered[i]) <= 1)+ matching++;+ else+ println(` character ${i} (${JSON.stringify(text.data[i])}): x ${offsets[i][0]}, layout ${rendered[i].toFixed(2)}`);+ continue;+ }+ // The next rendered character on the same line, if there is one.+ const next = offsets.findIndex((offset, j) => j > i && rendered[j] !== null);+ if (next === -1 || offsets[next][1] !== offsets[i][1])+ continue;+ unrenderedCount++;+ if (offsets[i][0] === offsets[next][0])+ unrenderedMatching++;+ else+ println(` unrendered character ${i}: x ${offsets[i][0]}, next rendered character's x ${offsets[next][0]}`);+ }+ println(` rendered characters at layout's x: ${matching} of ${renderedCount}`);+ println(` unrendered characters at the next rendered character's x: ${unrenderedMatching} of ${unrenderedCount}`);+ println(` x decreases along a line: ${decreases} times`);+ println(` distinct line tops: ${new Set(offsets.map(offset => offset[1])).size}`);+ }++ test(() => {+ check("wrapping");+ check("soft-hyphen");+ check("uppercased");+ });+</script>