Truly independent web browser
LibWeb: Place selections in right-to-left text where its glyphs are
sideshowbarker6c6cad25cf7a
diff --git a/Libraries/LibWeb/Rust/src/painting/record/paint/text.rs b/Libraries/LibWeb/Rust/src/painting/record/paint/text.rsindex 0f44676cdb4..98d9389af74 100644--- a/Libraries/LibWeb/Rust/src/painting/record/paint/text.rs+++ b/Libraries/LibWeb/Rust/src/painting/record/paint/text.rs@@ -564,14 +564,15 @@ pub(crate) fn paint_fragments<O: Observer>(recorder: &mut PaintRecorder<'_, O>,// highlight overlay, painting it immediately below any positioned descendants.for (span, overlay) in overlays() {if Color(overlay.background_color).alpha() > 0 {- let highlight_rect = highlight_rect(recorder, block, span);let converter = recorder.converter;let previous = recorder.recorder.set_contrast_backdrop(highlight_backdrop);- recorder.recorder.fill_rect(- converter.rounded_device_rect(highlight_rect),- Color(overlay.background_color),- ForceDarkRole::Selection,- );+ for highlight_rect in highlight_rects(recorder, block, span) {+ recorder.recorder.fill_rect(+ converter.rounded_device_rect(highlight_rect),+ Color(overlay.background_color),+ ForceDarkRole::Selection,+ );+ }recorder.recorder.set_contrast_backdrop(previous);}}@@ -589,14 +590,18 @@ pub(crate) fn paint_fragments<O: Observer>(recorder: &mut PaintRecorder<'_, O>,}}-fn highlight_rect<O: Observer>(recorder: &PaintRecorder<'_, O>, block: NodeSlotId, span: &RenderSpan) -> CssPixelRect {+fn highlight_rects<O: Observer>(+ recorder: &PaintRecorder<'_, O>,+ block: NodeSlotId,+ span: &RenderSpan,+) -> Vec<CssPixelRect> {let side = recorder.source.committed_side_data(block);let fragment = &side.fragments()[span.fragment_index as usize];let offsets = SelectionOffsets {start: span.start_code_unit,end: span.end_code_unit,};- text_fragment::rect_for_selection_offsets(recorder.source, fragment, offsets, || {+ text_fragment::rects_for_selection_offsets(recorder.source, fragment, offsets, || {text_fragment::first_available_font(recorder.source, fragment)})}@@ -767,13 +772,14 @@ fn paint_text_fragment<O: Observer>(orientation,glyph_bounding_rect,} = glyph_run_emission(fragment, run, fragment_absolute_rect, fragment_device_rect, scale);- let run_for_recording = GlyphRunForRecording {- font_smoothing: recorder- .source- .node_style_if_live(fragment.style_source)- .unwrap()- .inherited_text()- .font_smoothing,+ let font_smoothing = recorder+ .source+ .node_style_if_live(fragment.style_source)+ .unwrap()+ .inherited_text()+ .font_smoothing;+ let run_for_recording = || GlyphRunForRecording {+ font_smoothing,font_id: FontResourceId(font_id),glyphs: run.glyphs@@ -788,7 +794,7 @@ fn paint_text_fragment<O: Observer>(if is_full_fragment {recorder.recorder.draw_glyph_run(baseline_start,- run_for_recording,+ run_for_recording(),Color(span.text_color),fragment_device_rect,scale,@@ -797,27 +803,30 @@ fn paint_text_fragment<O: Observer>(ForceDarkRole::Foreground,);} else {- let range_rect = text_fragment::rect_for_selection_offsets(- recorder.source,- fragment,- SelectionOffsets {- start: span.start_code_unit,- end: span.end_code_unit,- },- || text_fragment::first_available_font(recorder.source, fragment),- );- let span_rect = converter.rounded_device_rect(range_rect);- recorder.recorder.record_clipped_to(span_rect, |recorder| {- recorder.draw_glyph_run(- baseline_start,- run_for_recording,- Color(span.text_color),- fragment_device_rect,- scale,- orientation,- glyph_bounding_rect,- ForceDarkRole::Foreground,- );+ let offsets = SelectionOffsets {+ start: span.start_code_unit,+ end: span.end_code_unit,+ };+ let range_rects = text_fragment::rects_for_selection_offsets(recorder.source, fragment, offsets, || {+ text_fragment::first_available_font(recorder.source, fragment)+ });+ for range_rect in &range_rects {+ let span_rect = converter.rounded_device_rect(*range_rect);+ recorder.recorder.record_clipped_to(span_rect, |recorder| {+ recorder.draw_glyph_run(+ baseline_start,+ run_for_recording(),+ Color(span.text_color),+ fragment_device_rect,+ scale,+ orientation,+ glyph_bounding_rect,+ ForceDarkRole::Foreground,+ );+ });+ }+ let range_rect = text_fragment::rect_for_selection_offsets(recorder.source, fragment, offsets, || {+ text_fragment::first_available_font(recorder.source, fragment)});decoration_box.x = range_rect.x;decoration_box.width = range_rect.width;diff --git a/Libraries/LibWeb/Rust/src/painting/text_fragment.rs b/Libraries/LibWeb/Rust/src/painting/text_fragment.rsindex c821f842d75..c846504003a 100644--- a/Libraries/LibWeb/Rust/src/painting/text_fragment.rs+++ b/Libraries/LibWeb/Rust/src/painting/text_fragment.rs@@ -292,6 +292,69 @@ fn for_each_cluster_in_glyph_run(}}+fn run_has_rtl_glyphs(run: &crate::layout::inline_content::GlyphRunRecord) -> bool {+ run.glyphs.placed().any(|placed| placed.is_rtl)+}++/// The inline extents, relative to the fragment's start, of the glyphs that draw the code units `start..end`, in visual+/// order. Glyphs that are next to each other on the line share an extent; a new one starts only where a glyph of other+/// code units lies between them. A glyph that draws only part of the range contributes the part of its advance that+/// the range covers, measured from its right edge when it's right-to-left.+fn inline_extents_of_code_units(+ run: &crate::layout::inline_content::GlyphRunRecord,+ start: usize,+ end: usize,+) -> Vec<(f32, f32)> {+ // Every glyph of a cluster reports the cluster's start; the cluster's length comes from the glyph that covers it.+ let mut cluster_lengths = std::collections::HashMap::new();+ for placed in run.glyphs.placed() {+ if placed.glyph.length_in_code_units() > 0 {+ cluster_lengths.insert(placed.cluster_start as usize, placed.glyph.length_in_code_units());+ }+ }+ // Each glyph with an advance, as its left edge and the part of it the range covers, if any.+ let mut glyphs: Vec<(f32, Option<(f32, f32)>)> = Vec::new();+ for placed in run.glyphs.placed() {+ let cluster_start = placed.cluster_start as usize;+ let Some(&cluster_length) = cluster_lengths.get(&cluster_start) else {+ continue;+ };+ if placed.glyph.advance <= 0.0 {+ continue;+ }+ let left = placed.x;+ let covered_start = start.max(cluster_start);+ let covered_end = end.min(cluster_start + cluster_length);+ let covered = (covered_start < covered_end).then(|| {+ let mut from = (covered_start - cluster_start) as f32 / cluster_length as f32;+ let mut to = (covered_end - cluster_start) as f32 / cluster_length as f32;+ if placed.is_rtl {+ (from, to) = (1.0 - to, 1.0 - from);+ }+ (left + placed.glyph.advance * from, left + placed.glyph.advance * to)+ });+ glyphs.push((left, covered));+ }+ glyphs.sort_by(|a, b| a.0.total_cmp(&b.0));+ let mut extents: Vec<(f32, f32)> = Vec::new();+ let mut extending = false;+ for (_, covered) in glyphs {+ match covered {+ Some((left, right)) if extending => {+ let last = extents.last_mut().unwrap();+ last.0 = last.0.min(left);+ last.1 = last.1.max(right);+ }+ Some(extent) => {+ extents.push(extent);+ extending = true;+ }+ None => extending = false,+ }+ }+ extents+}+/// 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@@ -390,6 +453,23 @@ pub(crate) fn rect_for_selection_offsets(}pixel_offset = CssPixels::nearest_value_for_f32(offset_accumulator);pixel_width = CssPixels::nearest_value_for_f32(width_accumulator);+ // Right-to-left glyphs are in visual order, so a range of code units is where their own glyphs are, not where+ // an advance added up in glyph order would put it.+ if let Some(run) = fragment+ .glyph_run+ .as_ref()+ .filter(|run| horizontal && run_has_rtl_glyphs(run))+ {+ let extents = inline_extents_of_code_units(run, start_in_text, end_in_text);+ if let (Some(first), Some(last)) = (extents.first(), extents.last()) {+ pixel_offset = CssPixels::nearest_value_for_f32(first.0);+ pixel_width = CssPixels::nearest_value_for_f32(last.1 - first.0);+ } else if start_in_text == end_in_text+ && let Some(x) = caret_inline_offset(fragment, start_in_text, true)+ {+ pixel_offset = CssPixels::nearest_value_for_f32(x);+ }+ }}if offsets.start > length || offsets.end > length {@@ -435,6 +515,39 @@ pub(crate) fn rect_for_selection_offsets(rect}+/// Like `rect_for_selection_offsets()`, but with one rect for each visually separate piece of the range: Code units+/// that are adjacent in the text can be apart on the line when the fragment mixes directions.+pub(crate) fn rects_for_selection_offsets(+ layout_arena: &impl PaintRead,+ fragment: &FragmentRecord,+ offsets: SelectionOffsets,+ first_available_font: impl FnOnce() -> Option<libgfx_rust::font::FontHandle>,+) -> Vec<CssPixelRect> {+ let rect = rect_for_selection_offsets(layout_arena, fragment, offsets, first_available_font);+ let length = fragment.length_in_code_units;+ let Some(run) = fragment+ .glyph_run+ .as_ref()+ .filter(|run| is_horizontal(fragment) && run_has_rtl_glyphs(run))+ else {+ return vec![rect];+ };+ let extents = inline_extents_of_code_units(run, offsets.start.min(length), offsets.end.min(length));+ if extents.len() < 2 {+ return vec![rect];+ }+ let x = absolute_rect(layout_arena, fragment).x;+ extents+ .into_iter()+ .map(|(left, right)| {+ let mut piece = rect;+ piece.x = x + CssPixels::nearest_value_for_f32(left);+ piece.width = CssPixels::nearest_value_for_f32(right - left);+ piece+ })+ .collect()+}+pub(crate) fn whole_range_rect(layout_arena: &impl PaintRead,fragment: &FragmentRecord,@@ -583,6 +696,19 @@ pub(crate) fn index_in_node_for_point(} else {(position.y - rect.y).to_float()};+ if let Some(run) = fragment+ .glyph_run+ .as_ref()+ .filter(|run| is_horizontal(fragment) && run_has_rtl_glyphs(run))+ && let Some(offset) = rtl_offset_for_inline_position(layout_arena, fragment, run, relative_inline_offset)+ {+ return layout_arena.dom_offset_for_rendered_text_offset(+ fragment.layout_node,+ fragment.start + offset,+ crate::layout::RenderedTextBoundary::End,+ );+ }+if relative_inline_offset < 0.0 {return 0;}@@ -642,3 +768,100 @@ pub(crate) fn index_in_node_for_point(crate::layout::RenderedTextBoundary::End,)}++/// The offset within `fragment` of the grapheme boundary nearest to the inline position `position` (relative to the+/// fragment's start), found from the cluster drawn there — or the nearest one — rather than from advances added up in+/// glyph order, which right-to-left glyphs don't follow. A position past the edge where the fragment's text ends falls+/// among its trailing whitespace, a space's width at a time.+fn rtl_offset_for_inline_position(+ layout_arena: &impl PaintRead,+ fragment: &FragmentRecord,+ run: &crate::layout::inline_content::GlyphRunRecord,+ position: f32,+) -> Option<usize> {+ // Each cluster's code units and the extent of all its glyphs, including those that cover no code units.+ struct Cluster {+ start: usize,+ end: usize,+ left: f32,+ right: f32,+ is_rtl: bool,+ }+ let mut clusters: Vec<Cluster> = Vec::new();+ for placed in run.glyphs.placed() {+ let start = placed.cluster_start as usize;+ let (left, right) = (placed.x, placed.x + placed.glyph.advance.max(0.0));+ if let Some(cluster) = clusters.iter_mut().find(|cluster| cluster.start == start) {+ cluster.left = cluster.left.min(left);+ cluster.right = cluster.right.max(right);+ cluster.end = cluster.end.max(start + placed.glyph.length_in_code_units());+ continue;+ }+ clusters.push(Cluster {+ start,+ end: start + placed.glyph.length_in_code_units(),+ left,+ right,+ is_rtl: placed.is_rtl,+ });+ }+ let length = fragment.length_in_code_units;+ // A truncated fragment can keep glyphs of code units past its end.+ clusters.retain(|cluster| cluster.end > cluster.start && cluster.start < length);++ // Past the edge where the text ends, the position is in the trailing whitespace.+ if fragment.trailing_whitespace_length_in_code_units > 0+ && let Some(last) = clusters.iter().find(|cluster| cluster.end >= length)+ {+ let beyond = if last.is_rtl {+ last.left - position+ } else {+ position - last.right+ };+ let space_width = run.font.glyph_width(' ' as u32);+ if beyond > 0.0 && space_width > 0.0 {+ let spaces =+ ((beyond / space_width).round() as usize).min(fragment.trailing_whitespace_length_in_code_units);+ return Some(length + spaces);+ }+ }++ let distance = |cluster: &Cluster| {+ if position < cluster.left {+ cluster.left - position+ } else {+ (position - cluster.right).max(0.0)+ }+ };+ let cluster = clusters.iter().min_by(|a, b| distance(a).total_cmp(&distance(b)))?;+ let cluster_start = cluster.start;+ let cluster_end = cluster.end.min(length);+ let width = cluster.right - cluster.left;+ let mut fraction = if width > 0.0 {+ ((position - cluster.left) / width).clamp(0.0, 1.0)+ } else {+ 0.0+ };+ if cluster.is_rtl {+ fraction = 1.0 - fraction;+ }+ let target = cluster_start as f32 + fraction * (cluster_end - cluster_start) as f32;++ let mut boundaries = vec![cluster_start];+ layout_arena.with_grapheme_segmenter(fragment.layout_node, |segmenter| {+ let mut boundary = fragment.start + cluster_start;+ while let Some(next) = segmenter.next_boundary(boundary, false) {+ if next <= boundary || next > fragment.start + cluster_end {+ break;+ }+ boundaries.push(next - fragment.start);+ boundary = next;+ }+ });+ if *boundaries.last().unwrap() != cluster_end {+ boundaries.push(cluster_end);+ }+ boundaries+ .into_iter()+ .min_by(|a, b| (*a as f32 - target).abs().total_cmp(&(*b as f32 - target).abs()))+}diff --git a/Tests/LibWeb/Text/expected/DOM/range-client-rects-and-caret-in-rtl-text.txt b/Tests/LibWeb/Text/expected/DOM/range-client-rects-and-caret-in-rtl-text.txtnew file mode 100644index 00000000000..c31911d88f5--- /dev/null+++ b/Tests/LibWeb/Text/expected/DOM/range-client-rects-and-caret-in-rtl-text.txt@@ -0,0 +1,7 @@+first word ends the line on the right: true+first word is in the line's right half: true+last word starts the line on the left: true+last word is in the line's left half: true+offset at the line's right end: 0+offset at the line's left end: true+offset just inside the first word's left edge: 5diff --git a/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-matches-the-host.txt b/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-matches-the-host.txtindex 7e6bf7a5678..a785bbf7633 100644--- a/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-matches-the-host.txt+++ b/Tests/LibWeb/Text/expected/HTML/frame-in-flight/clock-lane-drag-selection-matches-the-host.txt@@ -61,10 +61,10 @@ same: "<P> | <B> | <I> | <U> | <P> | <P> | <SPAN> | <P> | <P> | <P> | <SPAN> | <same: "<P> | <B> | <I> | <U> | <P> | <P> | <SPAN> | <P> | <P> | <P> | <SPAN> | <P> | <SPAN> | <P> | <P> | <IMG> | <P> | <P> | <TABLE> | <TBODY> | <TR> | <TD> | st line of plain text | some | bold | and | italic | underlined | text | text | around | comments | words | in a block | before | after | kept | kept again | around | all of this | the element | outside | kept in here | again outside | outer | inside contents | outer again | words | more words | light text | left c"same: "<P> | <B> | <I> | <U> | <P> | <P> | <SPAN> | <P> | <P> | <P> | <SPAN> | <P> | <SPAN> | <P> | <P> | <IMG> | <P> | <P> | <TABLE> | <TBODY> | <TR> | <TD> | <TD> | st line of plain text | some | bold | and | italic | underlined | text | text | around | comments | words | in a block | before | after | kept | kept again | around | all of this | the element | outside | kept in here | again outside | outer | inside contents | outer again | words | more words | light text | left cell | right cell"same: "<TD> | cell | right cell"-same: "<TD> | <P> | cell | right cell | שלום "+same: "<TD> | <P> | cell | right cell | שלום"same: "<TD> | <P> | <DIV> | <P> | <P> | <P> | <P> | <P> | <SPAN> | <P> | <DIV> | <P> | <P> | <P> | <SPAN> | <P> | <A> | <IMG> | <P> (rgb(255, 0, 0) on rgb(255, 255, 0)) | <P> | <A> | <A> | <IFRAME> | <svg> | <text> | <P> | cell | right cell | שלום עולם | scrolled line one | scrolled line two | scrolled line three | scrolled line four | floated text | text around the float | text moved by a transform | placed out of the flow | text after generated content | one line | another line | words | in a block | more words | words | around | boxes | end | text with a selection style (rgb(255, 0, 0) on rgb(255, 255, 0)) | before | the link text | after | a link to drag | text of a vector | the very"same: ""-same: "<TD> | <P> | | right cell | שלום עול"+same: "<TD> | <P> | | right cell | ש"same: "ted text"same: "ted text | text around t"same: "<P> | ted text | text around the float | text moved by"diff --git a/Tests/LibWeb/Text/input/DOM/range-client-rects-and-caret-in-rtl-text.html b/Tests/LibWeb/Text/input/DOM/range-client-rects-and-caret-in-rtl-text.htmlnew file mode 100644index 00000000000..d5d28dc6751--- /dev/null+++ b/Tests/LibWeb/Text/input/DOM/range-client-rects-and-caret-in-rtl-text.html@@ -0,0 +1,36 @@+<!DOCTYPE html>+<style>+ p {+ font-size: 20px;+ width: 600px;+ margin: 0;+ }+</style>+<p id="text" dir="rtl">بوران سی و دومین</p>+<script src="../include.js"></script>+<script>+ // Right-to-left glyphs are laid out right to left, so the first characters of the text are at the line's right end.+ test(() => {+ const node = document.getElementById("text").firstChild;+ const length = node.length;+ const rectOf = (start, end) => {+ const range = document.createRange();+ range.setStart(node, start);+ range.setEnd(node, end);+ return range.getBoundingClientRect();+ };+ const whole = rectOf(0, length);+ const first = rectOf(0, 5);+ const last = rectOf(length - 5, length);+ println(`first word ends the line on the right: ${Math.abs(first.right - whole.right) < 1}`);+ println(`first word is in the line's right half: ${first.left > whole.left + whole.width / 2}`);+ println(`last word starts the line on the left: ${Math.abs(last.left - whole.left) < 1}`);+ println(`last word is in the line's left half: ${last.right < whole.left + whole.width / 2}`);++ const y = whole.top + whole.height / 2;+ const offsetAt = x => document.caretPositionFromPoint(x, y).offset;+ println(`offset at the line's right end: ${offsetAt(whole.right - 1)}`);+ println(`offset at the line's left end: ${offsetAt(whole.left + 1) === length}`);+ println(`offset just inside the first word's left edge: ${offsetAt(first.left + 1)}`);+ });+</script>