Skip to content

Truly independent web browser

LibWeb: Add ClusterGeometry and share it between both text directions

Aliaksandr Kalenik620625909a29
diff --git a/Libraries/LibWeb/Rust/src/layout/inline_content.rs b/Libraries/LibWeb/Rust/src/layout/inline_content.rs
index 8a53be57e01..6850760d860 100644
--- a/Libraries/LibWeb/Rust/src/layout/inline_content.rs
+++ b/Libraries/LibWeb/Rust/src/layout/inline_content.rs
@@ -184,12 +184,201 @@ pub struct GlyphRunRecord {
pub is_upright: bool,
// Conservative painted bounds in CSS pixels, relative to the run's baseline origin.
pub bounding_box: libgfx_rust::FloatRect,
+ /// Built the first time a caret, selection or hit-testing query asks.
+ pub cluster_geometry: std::sync::OnceLock<ClusterGeometry>,
}
impl GlyphRunRecord {
pub fn glyph_intercepts(&self, scale: f32, y_top: f32, y_bottom: f32) -> Vec<f32> {
libgfx_rust::text_layout::glyph_run_glyph_intercepts(&self.font, &self.glyphs, scale, y_top, y_bottom)
}
+
+ pub fn cluster_geometry(&self) -> &ClusterGeometry {
+ self.cluster_geometry.get_or_init(|| ClusterGeometry::of(self))
+ }
+}
+
+/// Where each cluster of a glyph run lies along the inline axis, in logical order, with offsets in code units of the
+/// run's text and coordinates from the run's inline start. A cluster's advance is split evenly among its code units.
+#[derive(Default)]
+pub struct ClusterGeometry {
+ clusters: Vec<ClusterExtent>,
+}
+
+#[derive(Clone, Copy)]
+struct ClusterExtent {
+ start: usize,
+ end: usize,
+ left: f32,
+ right: f32,
+ is_rtl: bool,
+}
+
+impl ClusterExtent {
+ fn x_at(&self, offset: usize) -> f32 {
+ let advance = (self.right - self.left) * (offset - self.start) as f32 / (self.end - self.start) as f32;
+ if self.is_rtl {
+ self.right - advance
+ } else {
+ self.left + advance
+ }
+ }
+}
+
+impl ClusterGeometry {
+ fn of(run: &GlyphRunRecord) -> Self {
+ let mut clusters: Vec<ClusterExtent> = Vec::new();
+ let mut pen = 0.0f32;
+ for placed in run.glyphs.placed() {
+ // NB: Upright glyphs are placed across the line, so their advances give their inline positions.
+ let left = if run.is_upright { pen } else { placed.x };
+ let right = left + placed.glyph.advance;
+ pen += placed.glyph.advance;
+ let length = placed.glyph.length_in_code_units();
+ if length > 0 {
+ let start = placed.cluster_start as usize;
+ clusters.push(ClusterExtent {
+ start,
+ end: start + length,
+ left,
+ right,
+ is_rtl: placed.is_rtl,
+ });
+ } else if let Some(cluster) = clusters.last_mut() {
+ // Another glyph of the cluster before it in glyph order.
+ cluster.left = cluster.left.min(left);
+ cluster.right = cluster.right.max(right);
+ }
+ }
+ clusters.sort_by_key(|cluster| cluster.start);
+ Self { clusters }
+ }
+
+ /// The inline coordinate of the caret at `offset`. Where one cluster ends and another starts, `downstream` picks
+ /// the one that starts there.
+ pub fn x_for_offset(&self, offset: usize, downstream: bool) -> Option<f32> {
+ let mut fallback = None;
+ for cluster in self.clusters.iter().filter(|c| (c.start..=c.end).contains(&offset)) {
+ let x = cluster.x_at(offset);
+ if offset != if downstream { cluster.end } else { cluster.start } {
+ return Some(x);
+ }
+ fallback = Some(x);
+ }
+ fallback
+ }
+
+ /// The physical extents (left, right) of the code units `start..end` of the first `length`, from left to right, one
+ /// for each piece of the line they are drawn in: a cluster of other code units between two of theirs, as in text
+ /// that mixes directions, starts a new piece. Clusters that do not advance are left out.
+ pub fn range_extents(&self, start: usize, end: usize, length: usize) -> Vec<(f32, f32)> {
+ let mut clusters_left_to_right: Vec<&ClusterExtent> = self
+ .clusters
+ .iter()
+ .filter(|cluster| cluster.right > cluster.left && cluster.start < length)
+ .collect();
+ clusters_left_to_right.sort_by(|a, b| a.left.total_cmp(&b.left));
+ let mut extents: Vec<(f32, f32)> = Vec::new();
+ let mut extends_last_piece = false;
+ for cluster in clusters_left_to_right {
+ let (from, to) = (start.max(cluster.start), end.min(cluster.end).min(length));
+ if from >= to {
+ extends_last_piece = false;
+ continue;
+ }
+ let (a, b) = (cluster.x_at(from), cluster.x_at(to));
+ match extents.last_mut() {
+ Some(last) if extends_last_piece => *last = (last.0.min(a.min(b)), last.1.max(a.max(b))),
+ _ => extents.push((a.min(b), a.max(b))),
+ }
+ extends_last_piece = true;
+ }
+ extents
+ }
+
+ /// The physical extent (left, right) of all pieces of the code units `start..end` of the first `length`, or where
+ /// the caret at `start` is when they draw nothing.
+ pub fn range_extent(&self, start: usize, end: usize, length: usize) -> (f32, f32) {
+ self.range_extents(start, end, length)
+ .into_iter()
+ .reduce(|(l1, r1), (l2, r2)| (l1.min(l2), r1.max(r2)))
+ .unwrap_or_else(|| {
+ let x = self.x_for_offset(start, true).unwrap_or_else(|| self.end_x(length));
+ (x, x)
+ })
+ }
+
+ /// Where the first `length` code units end along the inline axis.
+ pub fn end_x(&self, length: usize) -> f32 {
+ self.x_for_offset(length, false).unwrap_or_default()
+ }
+
+ /// How far `x` lies past the end of the first `length` code units, in the direction their last cluster runs.
+ pub fn distance_past_end(&self, x: f32, length: usize) -> f32 {
+ let end_x = self.end_x(length);
+ let ends_right_to_left = self
+ .clusters
+ .iter()
+ .rfind(|cluster| cluster.start < length)
+ .is_some_and(|cluster| cluster.is_rtl);
+ if ends_right_to_left { end_x - x } else { x - end_x }
+ }
+
+ /// The offset for the inline coordinate `x` within the first `length` code units: the nearer edge of the grapheme
+ /// under `x`, the right one at its middle, or else the nearest grapheme edge. Also returns how far `x` is from the
+ /// text, zero within it.
+ pub fn offset_for_x(
+ &self,
+ x: f32,
+ length: usize,
+ next_grapheme_boundary: impl Fn(usize) -> Option<usize>,
+ ) -> (usize, f32) {
+ let mut nearest = (0, f32::INFINITY);
+ for cluster in self.clusters.iter().filter(|cluster| cluster.start < length) {
+ let end = cluster.end.min(length);
+ let mut grapheme_start = cluster.start;
+ while grapheme_start < end {
+ let grapheme_end = next_grapheme_boundary(grapheme_start)
+ .filter(|&next| next > grapheme_start)
+ .map_or(end, |next| next.min(end));
+ let mut left = (grapheme_start, cluster.x_at(grapheme_start));
+ let mut right = (grapheme_end, cluster.x_at(grapheme_end));
+ if cluster.is_rtl {
+ std::mem::swap(&mut left, &mut right);
+ }
+ if x >= left.1 && x <= right.1 {
+ return (if x - left.1 < right.1 - x { left.0 } else { right.0 }, 0.0);
+ }
+ let edge = if x < left.1 {
+ (left.0, left.1 - x)
+ } else {
+ (right.0, x - right.1)
+ };
+ if edge.1 < nearest.1 {
+ nearest = edge;
+ }
+ grapheme_start = grapheme_end;
+ }
+ }
+ nearest
+ }
+
+ /// The boundary at the physical left or right edge of the clusters that advance, and whether it ends its cluster.
+ pub fn edge_offset(&self, left: bool) -> Option<(usize, bool)> {
+ let edge = self
+ .clusters
+ .iter()
+ .filter(|cluster| cluster.right > cluster.left)
+ .min_by(|a, b| {
+ if left {
+ a.left.total_cmp(&b.left)
+ } else {
+ b.right.total_cmp(&a.right)
+ }
+ })?;
+ let at_end = left == edge.is_rtl;
+ Some((if at_end { edge.end } else { edge.start }, at_end))
+ }
}
#[derive(Clone, PartialEq)]
@@ -281,6 +470,7 @@ impl InlineContent {
font: glyph_data.font,
is_upright: glyph_data.is_upright,
bounding_box,
+ cluster_geometry: Default::default(),
})
});
fragment.record.line_index = line_index as u32;
@@ -538,6 +728,7 @@ impl InlineContent {
font: run.font.clone(),
is_upright: true,
bounding_box,
+ cluster_geometry: Default::default(),
}));
fragment.baseline = CssPixels::nearest_value_for_f32(ascent);
fragment.writing_mode = crate::css::css_enums::writing_mode::HORIZONTAL_TB;
diff --git a/Libraries/LibWeb/Rust/src/painting/caret.rs b/Libraries/LibWeb/Rust/src/painting/caret.rs
index 0b9b453190d..a2e64f7a782 100644
--- a/Libraries/LibWeb/Rust/src/painting/caret.rs
+++ b/Libraries/LibWeb/Rust/src/painting/caret.rs
@@ -28,7 +28,10 @@ fn caret_rect_in_fragment(
let mut rect = text_fragment::range_rect(layout_arena, fragment, SELECTION_STATE_START_AND_END, offset, offset);
if let Some(offsets) =
text_fragment::compute_selection_offsets(layout_arena, fragment, SELECTION_STATE_START_AND_END, offset, offset)
- && let Some(coordinate) = text_fragment::caret_inline_offset(fragment, offsets.start, affinity_is_downstream)
+ && let Some(run) = &fragment.glyph_run
+ && let Some(coordinate) = run
+ .cluster_geometry()
+ .x_for_offset(offsets.start, affinity_is_downstream)
{
let origin = text_fragment::absolute_rect(layout_arena, fragment);
let coordinate = CssPixels::nearest_value_for_f32(coordinate);
diff --git a/Libraries/LibWeb/Rust/src/painting/text_fragment.rs b/Libraries/LibWeb/Rust/src/painting/text_fragment.rs
index c846504003a..43336b7c985 100644
--- a/Libraries/LibWeb/Rust/src/painting/text_fragment.rs
+++ b/Libraries/LibWeb/Rust/src/painting/text_fragment.rs
@@ -250,115 +250,9 @@ pub(crate) fn selection_offsets_for_dom_range(
})
}
-/// Calls `callback` with each cluster of a fragment's glyph run, in glyph order: the code units it covers
-/// (`cluster_start..cluster_end`) and its advance. Each glyph that covers code units starts a cluster, even one with no
-/// advance (e.g. a soft hyphen's), and a glyph that covers none (another glyph of the same cluster) adds its advance to
-/// the cluster before it. Stops early when `callback` returns false.
-fn for_each_cluster_in_glyph_run(
- glyphs: &[libgfx_rust::text_layout::DrawGlyph],
- fragment_length_in_code_units: usize,
- mut callback: impl FnMut(usize, usize, f32) -> bool,
-) {
- let mut cursor = 0usize;
- // The cluster whose glyphs are still being added up, and the advance of glyphs that came before any code unit.
- let mut pending: Option<(usize, usize, f32)> = None;
- let mut leading_advance = 0.0f32;
- for glyph in glyphs {
- if glyph.length_in_code_units() == 0 {
- match &mut pending {
- Some((_, _, width)) => *width += glyph.advance,
- None => leading_advance += glyph.advance,
- }
- continue;
- }
- let cluster_start = cursor;
- let cluster_end = (cursor + glyph.length_in_code_units()).min(fragment_length_in_code_units);
- cursor = cluster_end;
- if let Some((start, end, width)) = pending.take()
- && !callback(start, end, width)
- {
- return;
- }
- if cluster_end > cluster_start {
- pending = Some((
- cluster_start,
- cluster_end,
- glyph.advance + std::mem::take(&mut leading_advance),
- ));
- }
- }
- if let Some((start, end, width)) = pending {
- callback(start, end, width);
- }
-}
-
-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
-/// run, so kerning and ligatures are reflected; a cluster's advance is split evenly among its code units.
+/// offset through the one past its last, along with the document-absolute x coordinate of the caret in front of that
+/// offset's character (or, for the last one, where the fragment's text ends), read from the fragment's shaped glyphs.
pub(crate) fn for_each_dom_offset_x(
layout_arena: &impl PaintRead,
fragment: &FragmentRecord,
@@ -370,30 +264,11 @@ pub(crate) fn for_each_dom_offset_x(
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 geometry = run.cluster_geometry();
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,
@@ -401,7 +276,10 @@ pub(crate) fn for_each_dom_offset_x(
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]);
+ let inline_x = geometry
+ .x_for_offset(offset_in_fragment, true)
+ .unwrap_or_else(|| geometry.end_x(length));
+ callback(dom_offset, x + inline_x);
},
);
}
@@ -430,46 +308,11 @@ pub(crate) fn rect_for_selection_offsets(
pixel_offset = CssPixels::from_raw(0);
pixel_width = primary_size(rect, horizontal);
} else {
- let mut offset_accumulator = 0.0f32;
- let mut width_accumulator = 0.0f32;
- if let Some(run) = &fragment.glyph_run {
- for_each_cluster_in_glyph_run(&run.glyphs, length, |cluster_start, cluster_end, cluster_width| {
- if cluster_end <= start_in_text {
- offset_accumulator += cluster_width;
- return true;
- }
- if cluster_start >= end_in_text {
- return true;
- }
- let per_unit_advance = cluster_width / (cluster_end - cluster_start) as f32;
- if cluster_start < start_in_text {
- offset_accumulator += per_unit_advance * (start_in_text - cluster_start) as f32;
- }
- let in_sel_start = cluster_start.max(start_in_text);
- let in_sel_end = cluster_end.min(end_in_text);
- width_accumulator += per_unit_advance * (in_sel_end - in_sel_start) as f32;
- true
- });
- }
- 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);
- }
- }
+ let (left, right) = fragment.glyph_run.as_ref().map_or((0.0, 0.0), |run| {
+ run.cluster_geometry().range_extent(start_in_text, end_in_text, length)
+ });
+ pixel_offset = CssPixels::nearest_value_for_f32(left);
+ pixel_width = CssPixels::nearest_value_for_f32(right - left);
}
if offsets.start > length || offsets.end > length {
@@ -525,24 +368,28 @@ pub(crate) fn rects_for_selection_offsets(
) -> 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));
+ let extents = fragment.glyph_run.as_ref().map_or_else(Vec::new, |run| {
+ run.cluster_geometry()
+ .range_extents(offsets.start.min(length), offsets.end.min(length), length)
+ });
if extents.len() < 2 {
return vec![rect];
}
- let x = absolute_rect(layout_arena, fragment).x;
+ let horizontal = is_horizontal(fragment);
+ let origin = absolute_rect(layout_arena, fragment);
extents
.into_iter()
- .map(|(left, right)| {
+ .map(|(start, end)| {
let mut piece = rect;
- piece.x = x + CssPixels::nearest_value_for_f32(left);
- piece.width = CssPixels::nearest_value_for_f32(right - left);
+ let offset = CssPixels::nearest_value_for_f32(start);
+ let size = CssPixels::nearest_value_for_f32(end - start);
+ if horizontal {
+ piece.x = origin.x + offset;
+ piece.width = size;
+ } else {
+ piece.y = origin.y + offset;
+ piece.height = size;
+ }
piece
})
.collect()
@@ -580,104 +427,22 @@ pub(crate) fn first_available_font(
.map(|style| style.first_available_font())
}
-struct GraphemeEdgeTracker {
- target_width: f32,
- left_edge: usize,
- right_edge: usize,
- width_to_left_edge: f32,
- width_to_right_edge: f32,
-}
-
-impl GraphemeEdgeTracker {
- fn new(target_width: f32) -> Self {
- Self {
- target_width,
- left_edge: 0,
- right_edge: 0,
- width_to_left_edge: 0.0,
- width_to_right_edge: 0.0,
- }
- }
-
- fn update(&mut self, grapheme_length_in_code_units: usize, grapheme_width: f32) -> bool {
- if grapheme_width == 0.0 {
- return true;
- }
- self.right_edge += grapheme_length_in_code_units;
- self.width_to_right_edge += grapheme_width;
- if self.width_to_right_edge >= self.target_width {
- return false;
- }
- self.left_edge = self.right_edge;
- self.width_to_left_edge = self.width_to_right_edge;
- true
- }
-
- fn resolve(&self) -> usize {
- if (self.target_width - self.width_to_left_edge) < (self.width_to_right_edge - self.target_width) {
- return self.left_edge;
- }
- self.right_edge
- }
-}
-
pub(crate) fn physical_edge_offset(
arena: &impl PaintRead,
fragment: &FragmentRecord,
left: bool,
) -> Option<(usize, bool)> {
- let run = fragment.glyph_run.as_ref()?;
- let placed = run
- .glyphs
- .placed()
- .filter(|placed| placed.glyph.length_in_code_units() > 0 && placed.glyph.advance > 0.0)
- .min_by(|a, b| {
- if left {
- a.x.total_cmp(&b.x)
- } else {
- (b.x + b.glyph.advance).total_cmp(&(a.x + a.glyph.advance))
- }
- })?;
- let boundary = placed.cluster_start as usize
- + if left == placed.is_rtl {
- placed.glyph.length_in_code_units()
- } else {
- 0
- };
+ let (boundary, at_cluster_end) = fragment.glyph_run.as_ref()?.cluster_geometry().edge_offset(left)?;
Some((
arena.dom_offset_for_rendered_text_offset(
fragment.layout_node,
fragment.start + boundary,
crate::layout::RenderedTextBoundary::End,
),
- left == placed.is_rtl,
+ at_cluster_end,
))
}
-pub(crate) fn caret_inline_offset(fragment: &FragmentRecord, offset: usize, downstream: bool) -> Option<f32> {
- let run = fragment.glyph_run.as_ref()?;
- let mut fallback = None;
- for placed in run
- .glyphs
- .placed()
- .filter(|placed| placed.glyph.length_in_code_units() > 0)
- {
- let start = placed.cluster_start as usize;
- let length = placed.glyph.length_in_code_units();
- let end = start + length;
- if offset < start || offset > end {
- continue;
- }
- let fraction = (offset - start) as f32 / length as f32;
- let coordinate = placed.x + placed.glyph.advance * if placed.is_rtl { 1.0 - fraction } else { fraction };
- if (offset > start && offset < end) || (downstream && offset == start) || (!downstream && offset == end) {
- return Some(coordinate);
- }
- fallback = Some(coordinate);
- }
- fallback
-}
-
pub(crate) fn index_in_node_for_point(
layout_arena: &impl PaintRead,
fragment: &FragmentRecord,
@@ -689,179 +454,37 @@ pub(crate) fn index_in_node_for_point(
{
return 0;
}
-
let rect = absolute_rect(layout_arena, fragment);
- let relative_inline_offset = if is_horizontal(fragment) {
+ let x = if is_horizontal(fragment) {
(position.x - rect.x).to_float()
} 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;
- }
-
- let mut tracker = GraphemeEdgeTracker::new(relative_inline_offset);
- let mut reached_target = false;
-
+ let mut offset = 0;
if let Some(run) = &fragment.glyph_run {
- layout_arena.with_grapheme_segmenter(fragment.layout_node, |segmenter| {
- for_each_cluster_in_glyph_run(
- &run.glyphs,
- fragment.length_in_code_units,
- |cluster_start, cluster_end, cluster_width| {
- let per_unit_advance = cluster_width / (cluster_end - cluster_start) as f32;
- let mut grapheme_start = fragment.start + cluster_start;
- let cluster_absolute_end = fragment.start + cluster_end;
- while grapheme_start < cluster_absolute_end {
- let grapheme_end = segmenter
- .next_boundary(grapheme_start, false)
- .unwrap_or(cluster_absolute_end)
- .min(cluster_absolute_end);
- if grapheme_end <= grapheme_start {
- break;
- }
- let grapheme_units = grapheme_end - grapheme_start;
- let grapheme_width = per_unit_advance * grapheme_units as f32;
- if !tracker.update(grapheme_units, grapheme_width) {
- reached_target = true;
- return false;
- }
- grapheme_start = grapheme_end;
- }
- true
- },
- );
- });
- }
-
- if !reached_target && fragment.trailing_whitespace_length_in_code_units > 0 {
- let font = match &fragment.glyph_run {
- Some(run) => Some(run.font.clone()),
- None => first_available_font(layout_arena, fragment),
- };
- if let Some(font) = font {
- let space_width = font.glyph_width(' ' as u32);
- for _ in 0..fragment.trailing_whitespace_length_in_code_units {
- if !tracker.update(1, space_width) {
- break;
- }
- }
+ let geometry = run.cluster_geometry();
+ let length = fragment.length_in_code_units;
+ let (nearest, distance) = layout_arena
+ .with_grapheme_segmenter(fragment.layout_node, |segmenter| {
+ geometry.offset_for_x(x, length, |offset| {
+ segmenter
+ .next_boundary(fragment.start + offset, false)
+ .map(|boundary| boundary - fragment.start)
+ })
+ })
+ .unwrap_or_default();
+ offset = nearest;
+ let space_width = run.font.glyph_width(' ' as u32);
+ let past_end = geometry.distance_past_end(x, length);
+ let trailing_spaces =
+ ((past_end / space_width).round().max(0.0) as usize).min(fragment.trailing_whitespace_length_in_code_units);
+ if trailing_spaces > 0 && (past_end - space_width * trailing_spaces as f32).abs() <= distance {
+ offset = length + trailing_spaces;
}
}
-
layout_arena.dom_offset_for_rendered_text_offset(
fragment.layout_node,
- fragment.start + tracker.resolve(),
+ fragment.start + offset,
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/Ref/expected/selection-highlight-rtl-partial-ref.html b/Tests/LibWeb/Ref/expected/selection-highlight-rtl-partial-ref.html
new file mode 100644
index 00000000000..1b5afba7a06
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/selection-highlight-rtl-partial-ref.html
@@ -0,0 +1,9 @@
+<!DOCTYPE html>
+<style>
+@font-face { font-family: TestHebrew; src: url(wpt-import/fonts/mplus-1p-regular.woff); }
+body { margin: 0; font: 40px TestHebrew; }
+p { margin: 10px; }
+#highlight { position: absolute; left: 724.13px; top: 10px; width: 43.31px; height: 56px; background-color: red; z-index: -1; }
+</style>
+<div id="highlight"></div>
+<p dir="rtl"><span>אבגדה</span></p>
diff --git a/Tests/LibWeb/Ref/input/selection-highlight-rtl-partial.html b/Tests/LibWeb/Ref/input/selection-highlight-rtl-partial.html
new file mode 100644
index 00000000000..75b52fee374
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/selection-highlight-rtl-partial.html
@@ -0,0 +1,15 @@
+<!DOCTYPE html>
+<link rel="match" href="../expected/selection-highlight-rtl-partial-ref.html">
+<style>
+@font-face { font-family: TestHebrew; src: url(wpt-import/fonts/mplus-1p-regular.woff); }
+body { margin: 0; font: 40px TestHebrew; }
+p { margin: 10px; }
+::selection { background-color: red; color: black; }
+</style>
+<p dir="rtl"><span id="text">אבגדה</span></p>
+<script>
+ // The second and third characters of right-to-left text are drawn second and third from the right, and the
+ // selection of them highlights them there.
+ const text = document.getElementById("text").firstChild;
+ getSelection().setBaseAndExtent(text, 1, text, 3);
+</script>