feat: Implement display for text selection and caret (#35830)

This PR introduces an initial, straightforward implementation for
displaying text selection and the caret.

This is achieved by passing the selection range and insertion point
index down to `TextFragment`, along with the starting offset of each
`TextFragment` to determine the proper range for displaying the caret
and text selection. Additionally, the `selected_style` was passed into
`TextFragment` to specify the background color.

During the final build phase, although whitespace is typically ignored
when constructing glyphs, we still need to retrieve it to render both
the caret and text selection at the correct location. This ensures that
whitespace is not overlooked when the `TextFragment` contains an
insertion point or selection range.

There are several improvements yet to be made, including:

- The caret is static and does not flash.
- The caret is not rendered when the input field is empty. (I suppose
there should be an easy fix somewhere but I haven't found it yet)

**Working Examples**

macOS


https://github.com/user-attachments/assets/f3622cbe-9fa6-40c0-b2d8-b3a8f9842c28

Windows


https://github.com/user-attachments/assets/9b008a0d-0011-4c76-a2e2-0e35869a216c

Linux

[Screencast from 03-07-2025 11_05_41
AM.webm](https://github.com/user-attachments/assets/09a311ad-f975-4450-a66c-b20be525a5ed)



---
- [x] `./mach build -d` does not report any errors
- [x] `./mach test-tidy` does not report any errors
- [x] These changes fix part of #33237 (But the cursor isn't blinking
yet)
- [x] These changes do not require tests because there's no behavior
change

Signed-off-by: DK Liao <dklassic@gmail.com>
This commit is contained in:
DK Liao 2025-04-10 23:40:38 +09:00 committed by GitHub
parent e6595619e1
commit e62aecb103
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 172 additions and 11 deletions

View file

@ -5,7 +5,7 @@
use std::cell::{OnceCell, RefCell};
use std::sync::Arc;
use app_units::Au;
use app_units::{AU_PER_PX, Au};
use base::WebRenderEpochToU16;
use base::id::ScrollTreeNodeId;
use compositing_traits::display_list::{AxesScrollSensitivity, CompositorDisplayListInfo};
@ -13,6 +13,7 @@ use embedder_traits::Cursor;
use euclid::{Point2D, SideOffsets2D, Size2D, UnknownUnit};
use fonts::GlyphStore;
use gradient::WebRenderGradient;
use range::Range as ServoRange;
use servo_geometry::MaxRect;
use style::Zero;
use style::color::{AbsoluteColor, ColorSpace};
@ -68,6 +69,7 @@ pub struct WebRenderImageInfo {
// webrender's `ItemTag` is private.
type ItemTag = (u64, u16);
type HitInfo = Option<ItemTag>;
const INSERTION_POINT_LOGICAL_WIDTH: Au = Au(AU_PER_PX);
/// Where the information that's used to build display lists is stored. This
/// includes both a [wr::DisplayListBuilder] for building up WebRender-specific
@ -388,6 +390,7 @@ impl Fragment {
&fragment.glyphs,
baseline_origin,
fragment.justification_adjustment,
!fragment.has_selection(),
);
if glyphs.is_empty() {
return;
@ -424,7 +427,6 @@ impl Fragment {
);
}
// Underline.
if fragment
.text_decoration_line
.contains(TextDecorationLine::UNDERLINE)
@ -435,7 +437,6 @@ impl Fragment {
self.build_display_list_for_text_decoration(fragment, builder, &rect, &color);
}
// Overline.
if fragment
.text_decoration_line
.contains(TextDecorationLine::OVERLINE)
@ -445,7 +446,70 @@ impl Fragment {
self.build_display_list_for_text_decoration(fragment, builder, &rect, &color);
}
// Text.
// TODO: This caret/text selection implementation currently does not account for vertical text
// and RTL text properly.
if let Some(range) = fragment.selection_range {
let baseline_origin = rect.origin;
if !range.is_empty() {
let start = glyphs_advance_by_index(
&fragment.glyphs,
range.begin(),
baseline_origin,
fragment.justification_adjustment,
);
let end = glyphs_advance_by_index(
&fragment.glyphs,
range.end(),
baseline_origin,
fragment.justification_adjustment,
);
let selection_rect = LayoutRect::new(
Point2D::new(start.x.to_f32_px(), containing_block.min_y().to_f32_px()),
Point2D::new(end.x.to_f32_px(), containing_block.max_y().to_f32_px()),
);
if let Some(selection_color) = fragment
.selected_style
.clone_background_color()
.as_absolute()
{
let selection_common =
builder.common_properties(selection_rect, &fragment.parent_style);
builder.wr().push_rect(
&selection_common,
selection_rect,
rgba(*selection_color),
);
}
} else {
let insertion_point = glyphs_advance_by_index(
&fragment.glyphs,
range.begin(),
baseline_origin,
fragment.justification_adjustment,
);
let insertion_point_rect = LayoutRect::new(
Point2D::new(
insertion_point.x.to_f32_px(),
containing_block.min_y().to_f32_px(),
),
Point2D::new(
insertion_point.x.to_f32_px() + INSERTION_POINT_LOGICAL_WIDTH.to_f32_px(),
containing_block.max_y().to_f32_px(),
),
);
let insertion_point_common =
builder.common_properties(insertion_point_rect, &fragment.parent_style);
// TODO: The color of the caret is currently hardcoded to the text color.
// We should be retrieving the caret color from the style properly.
builder
.wr()
.push_rect(&insertion_point_common, insertion_point_rect, rgba(color));
}
}
builder.wr().push_text(
&common,
rect.to_webrender(),
@ -455,7 +519,6 @@ impl Fragment {
None,
);
// Line-through.
if fragment
.text_decoration_line
.contains(TextDecorationLine::LINE_THROUGH)
@ -1130,6 +1193,7 @@ fn glyphs(
glyph_runs: &[Arc<GlyphStore>],
mut baseline_origin: PhysicalPoint<Au>,
justification_adjustment: Au,
ignore_whitespace: bool,
) -> Vec<wr::GlyphInstance> {
use fonts_traits::ByteIndex;
use range::Range;
@ -1137,7 +1201,7 @@ fn glyphs(
let mut glyphs = vec![];
for run in glyph_runs {
for glyph in run.iter_glyphs_for_byte_range(&Range::new(ByteIndex(0), run.len())) {
if !run.is_whitespace() {
if !run.is_whitespace() || !ignore_whitespace {
let glyph_offset = glyph.offset().unwrap_or(Point2D::zero());
let point = units::LayoutPoint::new(
baseline_origin.x.to_f32_px() + glyph_offset.x.to_f32_px(),
@ -1159,6 +1223,26 @@ fn glyphs(
glyphs
}
// TODO: This implementation has not been tested against `TextFragment` with mutiple runs.
// It is possible that the `glyphs` function above will need to be modified to
// handle multiple runs correctly.
fn glyphs_advance_by_index(
glyph_runs: &[Arc<GlyphStore>],
index: fonts_traits::ByteIndex,
baseline_origin: PhysicalPoint<Au>,
justification_adjustment: Au,
) -> PhysicalPoint<Au> {
let mut point = baseline_origin;
for run in glyph_runs {
let total_advance = run.advance_for_byte_range(
&ServoRange::new(fonts::ByteIndex(0), index),
justification_adjustment,
);
point.x += total_advance;
}
point
}
fn cursor(kind: CursorKind, auto_cursor: Cursor) -> Cursor {
match kind {
CursorKind::Auto => auto_cursor,