Present Servo BGRA hardware surfaces

This commit is contained in:
2026-05-13 00:22:00 -04:00
parent bf1ebfb6fe
commit 05a7a0d67f
154 changed files with 84157 additions and 115 deletions
+21
View File
@@ -0,0 +1,21 @@
use std::sync::Arc;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
/// The fallback fonts that can be configured for a given font.
/// Fallback fonts family names are stored here.
#[derive(Default, Clone, Eq, PartialEq, Hash, Debug, Deserialize, Serialize, JsonSchema)]
pub struct FontFallbacks(pub Arc<Vec<String>>);
impl FontFallbacks {
/// Get the fallback fonts family names
pub fn fallback_list(&self) -> &[String] {
self.0.as_slice()
}
/// Create a font fallback from a list of strings
pub fn from_fonts(fonts: Vec<String>) -> Self {
FontFallbacks(Arc::new(fonts))
}
}
+154
View File
@@ -0,0 +1,154 @@
use std::borrow::Cow;
use std::sync::Arc;
use schemars::{JsonSchema, json_schema};
/// The OpenType features that can be configured for a given font.
#[derive(Default, Clone, Eq, PartialEq, Hash)]
pub struct FontFeatures(pub Arc<Vec<(String, u32)>>);
impl FontFeatures {
/// Disables `calt`.
pub fn disable_ligatures() -> Self {
Self(Arc::new(vec![("calt".into(), 0)]))
}
/// Get the tag name list of the font OpenType features
/// only enabled or disabled features are returned
pub fn tag_value_list(&self) -> &[(String, u32)] {
self.0.as_slice()
}
/// Returns whether the `calt` feature is enabled.
///
/// Returns `None` if the feature is not present.
pub fn is_calt_enabled(&self) -> Option<bool> {
self.0
.iter()
.find(|(feature, _)| feature == "calt")
.map(|(_, value)| *value == 1)
}
}
impl std::fmt::Debug for FontFeatures {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut debug = f.debug_struct("FontFeatures");
for (tag, value) in self.tag_value_list() {
debug.field(tag, value);
}
debug.finish()
}
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
enum FeatureValue {
Bool(bool),
Number(serde_json::Number),
}
impl<'de> serde::Deserialize<'de> for FontFeatures {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::{MapAccess, Visitor};
use std::fmt;
struct FontFeaturesVisitor;
impl<'de> Visitor<'de> for FontFeaturesVisitor {
type Value = FontFeatures;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a map of font features")
}
fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
where
M: MapAccess<'de>,
{
let mut feature_list = Vec::new();
while let Some((key, value)) =
access.next_entry::<String, Option<FeatureValue>>()?
{
if !is_valid_feature_tag(&key) {
log::error!("Incorrect font feature tag: {}", key);
continue;
}
if let Some(value) = value {
match value {
FeatureValue::Bool(enable) => {
if enable {
feature_list.push((key, 1));
} else {
feature_list.push((key, 0));
}
}
FeatureValue::Number(value) => {
if value.is_u64() {
feature_list.push((key, value.as_u64().unwrap() as u32));
} else {
log::error!(
"Incorrect font feature value {} for feature tag {}",
value,
key
);
continue;
}
}
}
}
}
Ok(FontFeatures(Arc::new(feature_list)))
}
}
let features = deserializer.deserialize_map(FontFeaturesVisitor)?;
Ok(features)
}
}
impl serde::Serialize for FontFeatures {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
use serde::ser::SerializeMap;
let mut map = serializer.serialize_map(None)?;
for (tag, value) in self.tag_value_list() {
map.serialize_entry(tag, value)?;
}
map.end()
}
}
impl JsonSchema for FontFeatures {
fn schema_name() -> Cow<'static, str> {
"FontFeatures".into()
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
json_schema!({
"type": "object",
"patternProperties": {
"[0-9a-zA-Z]{4}$": {
"type": ["boolean", "integer"],
"minimum": 0,
"multipleOf": 1
}
},
"additionalProperties": false
})
}
}
fn is_valid_feature_tag(tag: &str) -> bool {
tag.len() == 4 && tag.chars().all(|c| c.is_ascii_alphanumeric())
}
+591
View File
@@ -0,0 +1,591 @@
use crate::{
App, Bounds, Half, Hsla, LineLayout, Pixels, Point, Result, SharedString, StrikethroughStyle,
TextAlign, UnderlineStyle, Window, WrapBoundary, WrappedLineLayout, black, fill, point, px,
size,
};
use derive_more::{Deref, DerefMut};
use smallvec::SmallVec;
use std::sync::Arc;
/// Set the text decoration for a run of text.
#[derive(Debug, Clone)]
pub struct DecorationRun {
/// The length of the run in utf-8 bytes.
pub len: u32,
/// The color for this run
pub color: Hsla,
/// The background color for this run
pub background_color: Option<Hsla>,
/// The underline style for this run
pub underline: Option<UnderlineStyle>,
/// The strikethrough style for this run
pub strikethrough: Option<StrikethroughStyle>,
}
/// A line of text that has been shaped and decorated.
#[derive(Clone, Default, Debug, Deref, DerefMut)]
pub struct ShapedLine {
#[deref]
#[deref_mut]
pub(crate) layout: Arc<LineLayout>,
/// The text that was shaped for this line.
pub text: SharedString,
pub(crate) decoration_runs: SmallVec<[DecorationRun; 32]>,
}
impl ShapedLine {
/// The length of the line in utf-8 bytes.
#[allow(clippy::len_without_is_empty)]
pub fn len(&self) -> usize {
self.layout.len
}
/// Override the len, useful if you're rendering text a
/// as text b (e.g. rendering invisibles).
pub fn with_len(mut self, len: usize) -> Self {
let layout = self.layout.as_ref();
self.layout = Arc::new(LineLayout {
font_size: layout.font_size,
width: layout.width,
ascent: layout.ascent,
descent: layout.descent,
runs: layout.runs.clone(),
len,
});
self
}
/// Paint the line of text to the window.
pub fn paint(
&self,
origin: Point<Pixels>,
line_height: Pixels,
window: &mut Window,
cx: &mut App,
) -> Result<()> {
paint_line(
origin,
&self.layout,
line_height,
TextAlign::default(),
None,
&self.decoration_runs,
&[],
window,
cx,
)?;
Ok(())
}
/// Paint the background of the line to the window.
pub fn paint_background(
&self,
origin: Point<Pixels>,
line_height: Pixels,
window: &mut Window,
cx: &mut App,
) -> Result<()> {
paint_line_background(
origin,
&self.layout,
line_height,
TextAlign::default(),
None,
&self.decoration_runs,
&[],
window,
cx,
)?;
Ok(())
}
}
/// A line of text that has been shaped, decorated, and wrapped by the text layout system.
#[derive(Clone, Default, Debug, Deref, DerefMut)]
pub struct WrappedLine {
#[deref]
#[deref_mut]
pub(crate) layout: Arc<WrappedLineLayout>,
/// The text that was shaped for this line.
pub text: SharedString,
pub(crate) decoration_runs: SmallVec<[DecorationRun; 32]>,
}
impl WrappedLine {
/// The length of the underlying, unwrapped layout, in utf-8 bytes.
#[allow(clippy::len_without_is_empty)]
pub fn len(&self) -> usize {
self.layout.len()
}
/// Paint this line of text to the window.
pub fn paint(
&self,
origin: Point<Pixels>,
line_height: Pixels,
align: TextAlign,
bounds: Option<Bounds<Pixels>>,
window: &mut Window,
cx: &mut App,
) -> Result<()> {
let align_width = match bounds {
Some(bounds) => Some(bounds.size.width),
None => self.layout.wrap_width,
};
paint_line(
origin,
&self.layout.unwrapped_layout,
line_height,
align,
align_width,
&self.decoration_runs,
&self.wrap_boundaries,
window,
cx,
)?;
Ok(())
}
/// Paint the background of line of text to the window.
pub fn paint_background(
&self,
origin: Point<Pixels>,
line_height: Pixels,
align: TextAlign,
bounds: Option<Bounds<Pixels>>,
window: &mut Window,
cx: &mut App,
) -> Result<()> {
let align_width = match bounds {
Some(bounds) => Some(bounds.size.width),
None => self.layout.wrap_width,
};
paint_line_background(
origin,
&self.layout.unwrapped_layout,
line_height,
align,
align_width,
&self.decoration_runs,
&self.wrap_boundaries,
window,
cx,
)?;
Ok(())
}
}
fn paint_line(
origin: Point<Pixels>,
layout: &LineLayout,
line_height: Pixels,
align: TextAlign,
align_width: Option<Pixels>,
decoration_runs: &[DecorationRun],
wrap_boundaries: &[WrapBoundary],
window: &mut Window,
cx: &mut App,
) -> Result<()> {
let line_bounds = Bounds::new(
origin,
size(
layout.width,
line_height * (wrap_boundaries.len() as f32 + 1.),
),
);
window.paint_layer(line_bounds, |window| {
let padding_top = (line_height - layout.ascent - layout.descent) / 2.;
let baseline_offset = point(px(0.), padding_top + layout.ascent);
let mut decoration_runs = decoration_runs.iter();
let mut wraps = wrap_boundaries.iter().peekable();
let mut run_end = 0;
let mut color = black();
let mut current_underline: Option<(Point<Pixels>, UnderlineStyle)> = None;
let mut current_strikethrough: Option<(Point<Pixels>, StrikethroughStyle)> = None;
let text_system = cx.text_system().clone();
let mut glyph_origin = point(
aligned_origin_x(
origin,
align_width.unwrap_or(layout.width),
px(0.0),
&align,
layout,
wraps.peek(),
),
origin.y,
);
let mut prev_glyph_position = Point::default();
let mut max_glyph_size = size(px(0.), px(0.));
let mut first_glyph_x = origin.x;
for (run_ix, run) in layout.runs.iter().enumerate() {
max_glyph_size = text_system.bounding_box(run.font_id, layout.font_size).size;
for (glyph_ix, glyph) in run.glyphs.iter().enumerate() {
glyph_origin.x += glyph.position.x - prev_glyph_position.x;
if glyph_ix == 0 && run_ix == 0 {
first_glyph_x = glyph_origin.x;
}
if wraps.peek() == Some(&&WrapBoundary { run_ix, glyph_ix }) {
wraps.next();
if let Some((underline_origin, underline_style)) = current_underline.as_mut() {
if glyph_origin.x == underline_origin.x {
underline_origin.x -= max_glyph_size.width.half();
};
window.paint_underline(
*underline_origin,
glyph_origin.x - underline_origin.x,
underline_style,
);
underline_origin.x = origin.x;
underline_origin.y += line_height;
}
if let Some((strikethrough_origin, strikethrough_style)) =
current_strikethrough.as_mut()
{
if glyph_origin.x == strikethrough_origin.x {
strikethrough_origin.x -= max_glyph_size.width.half();
};
window.paint_strikethrough(
*strikethrough_origin,
glyph_origin.x - strikethrough_origin.x,
strikethrough_style,
);
strikethrough_origin.x = origin.x;
strikethrough_origin.y += line_height;
}
glyph_origin.x = aligned_origin_x(
origin,
align_width.unwrap_or(layout.width),
glyph.position.x,
&align,
layout,
wraps.peek(),
);
glyph_origin.y += line_height;
}
prev_glyph_position = glyph.position;
let mut finished_underline: Option<(Point<Pixels>, UnderlineStyle)> = None;
let mut finished_strikethrough: Option<(Point<Pixels>, StrikethroughStyle)> = None;
if glyph.index >= run_end {
let mut style_run = decoration_runs.next();
// ignore style runs that apply to a partial glyph
while let Some(run) = style_run {
if glyph.index < run_end + (run.len as usize) {
break;
}
run_end += run.len as usize;
style_run = decoration_runs.next();
}
if let Some(style_run) = style_run {
if let Some((_, underline_style)) = &mut current_underline
&& style_run.underline.as_ref() != Some(underline_style)
{
finished_underline = current_underline.take();
}
if let Some(run_underline) = style_run.underline.as_ref() {
current_underline.get_or_insert((
point(
glyph_origin.x,
glyph_origin.y + baseline_offset.y + (layout.descent * 0.618),
),
UnderlineStyle {
color: Some(run_underline.color.unwrap_or(style_run.color)),
thickness: run_underline.thickness,
wavy: run_underline.wavy,
},
));
}
if let Some((_, strikethrough_style)) = &mut current_strikethrough
&& style_run.strikethrough.as_ref() != Some(strikethrough_style)
{
finished_strikethrough = current_strikethrough.take();
}
if let Some(run_strikethrough) = style_run.strikethrough.as_ref() {
current_strikethrough.get_or_insert((
point(
glyph_origin.x,
glyph_origin.y
+ (((layout.ascent * 0.5) + baseline_offset.y) * 0.5),
),
StrikethroughStyle {
color: Some(run_strikethrough.color.unwrap_or(style_run.color)),
thickness: run_strikethrough.thickness,
},
));
}
run_end += style_run.len as usize;
color = style_run.color;
} else {
run_end = layout.len;
finished_underline = current_underline.take();
finished_strikethrough = current_strikethrough.take();
}
}
if let Some((mut underline_origin, underline_style)) = finished_underline {
if underline_origin.x == glyph_origin.x {
underline_origin.x -= max_glyph_size.width.half();
};
window.paint_underline(
underline_origin,
glyph_origin.x - underline_origin.x,
&underline_style,
);
}
if let Some((mut strikethrough_origin, strikethrough_style)) =
finished_strikethrough
{
if strikethrough_origin.x == glyph_origin.x {
strikethrough_origin.x -= max_glyph_size.width.half();
};
window.paint_strikethrough(
strikethrough_origin,
glyph_origin.x - strikethrough_origin.x,
&strikethrough_style,
);
}
let max_glyph_bounds = Bounds {
origin: glyph_origin,
size: max_glyph_size,
};
let content_mask = window.content_mask();
if max_glyph_bounds.intersects(&content_mask.bounds) {
if glyph.is_emoji {
window.paint_emoji(
glyph_origin + baseline_offset,
run.font_id,
glyph.id,
layout.font_size,
)?;
} else {
window.paint_glyph(
glyph_origin + baseline_offset,
run.font_id,
glyph.id,
layout.font_size,
color,
)?;
}
}
}
}
let mut last_line_end_x = first_glyph_x + layout.width;
if let Some(boundary) = wrap_boundaries.last() {
let run = &layout.runs[boundary.run_ix];
let glyph = &run.glyphs[boundary.glyph_ix];
last_line_end_x -= glyph.position.x;
}
if let Some((mut underline_start, underline_style)) = current_underline.take() {
if last_line_end_x == underline_start.x {
underline_start.x -= max_glyph_size.width.half()
};
window.paint_underline(
underline_start,
last_line_end_x - underline_start.x,
&underline_style,
);
}
if let Some((mut strikethrough_start, strikethrough_style)) = current_strikethrough.take() {
if last_line_end_x == strikethrough_start.x {
strikethrough_start.x -= max_glyph_size.width.half()
};
window.paint_strikethrough(
strikethrough_start,
last_line_end_x - strikethrough_start.x,
&strikethrough_style,
);
}
Ok(())
})
}
fn paint_line_background(
origin: Point<Pixels>,
layout: &LineLayout,
line_height: Pixels,
align: TextAlign,
align_width: Option<Pixels>,
decoration_runs: &[DecorationRun],
wrap_boundaries: &[WrapBoundary],
window: &mut Window,
cx: &mut App,
) -> Result<()> {
let line_bounds = Bounds::new(
origin,
size(
layout.width,
line_height * (wrap_boundaries.len() as f32 + 1.),
),
);
window.paint_layer(line_bounds, |window| {
let mut decoration_runs = decoration_runs.iter();
let mut wraps = wrap_boundaries.iter().peekable();
let mut run_end = 0;
let mut current_background: Option<(Point<Pixels>, Hsla)> = None;
let text_system = cx.text_system().clone();
let mut glyph_origin = point(
aligned_origin_x(
origin,
align_width.unwrap_or(layout.width),
px(0.0),
&align,
layout,
wraps.peek(),
),
origin.y,
);
let mut prev_glyph_position = Point::default();
let mut max_glyph_size = size(px(0.), px(0.));
for (run_ix, run) in layout.runs.iter().enumerate() {
max_glyph_size = text_system.bounding_box(run.font_id, layout.font_size).size;
for (glyph_ix, glyph) in run.glyphs.iter().enumerate() {
glyph_origin.x += glyph.position.x - prev_glyph_position.x;
if wraps.peek() == Some(&&WrapBoundary { run_ix, glyph_ix }) {
wraps.next();
if let Some((background_origin, background_color)) = current_background.as_mut()
{
if glyph_origin.x == background_origin.x {
background_origin.x -= max_glyph_size.width.half()
}
window.paint_quad(fill(
Bounds {
origin: *background_origin,
size: size(glyph_origin.x - background_origin.x, line_height),
},
*background_color,
));
background_origin.x = origin.x;
background_origin.y += line_height;
}
glyph_origin.x = aligned_origin_x(
origin,
align_width.unwrap_or(layout.width),
glyph.position.x,
&align,
layout,
wraps.peek(),
);
glyph_origin.y += line_height;
}
prev_glyph_position = glyph.position;
let mut finished_background: Option<(Point<Pixels>, Hsla)> = None;
if glyph.index >= run_end {
let mut style_run = decoration_runs.next();
// ignore style runs that apply to a partial glyph
while let Some(run) = style_run {
if glyph.index < run_end + (run.len as usize) {
break;
}
run_end += run.len as usize;
style_run = decoration_runs.next();
}
if let Some(style_run) = style_run {
if let Some((_, background_color)) = &mut current_background
&& style_run.background_color.as_ref() != Some(background_color)
{
finished_background = current_background.take();
}
if let Some(run_background) = style_run.background_color {
current_background.get_or_insert((
point(glyph_origin.x, glyph_origin.y),
run_background,
));
}
run_end += style_run.len as usize;
} else {
run_end = layout.len;
finished_background = current_background.take();
}
}
if let Some((mut background_origin, background_color)) = finished_background {
let mut width = glyph_origin.x - background_origin.x;
if background_origin.x == glyph_origin.x {
background_origin.x -= max_glyph_size.width.half();
};
window.paint_quad(fill(
Bounds {
origin: background_origin,
size: size(width, line_height),
},
background_color,
));
}
}
}
let mut last_line_end_x = origin.x + layout.width;
if let Some(boundary) = wrap_boundaries.last() {
let run = &layout.runs[boundary.run_ix];
let glyph = &run.glyphs[boundary.glyph_ix];
last_line_end_x -= glyph.position.x;
}
if let Some((mut background_origin, background_color)) = current_background.take() {
if last_line_end_x == background_origin.x {
background_origin.x -= max_glyph_size.width.half()
};
window.paint_quad(fill(
Bounds {
origin: background_origin,
size: size(last_line_end_x - background_origin.x, line_height),
},
background_color,
));
}
Ok(())
})
}
fn aligned_origin_x(
origin: Point<Pixels>,
align_width: Pixels,
last_glyph_x: Pixels,
align: &TextAlign,
layout: &LineLayout,
wrap_boundary: Option<&&WrapBoundary>,
) -> Pixels {
let end_of_line = if let Some(WrapBoundary { run_ix, glyph_ix }) = wrap_boundary {
layout.runs[*run_ix].glyphs[*glyph_ix].position.x
} else {
layout.width
};
let line_width = end_of_line - last_glyph_x;
match align {
TextAlign::Left => origin.x,
TextAlign::Center => (origin.x * 2.0 + align_width - line_width) / 2.0,
TextAlign::Right => origin.x + align_width - line_width,
}
}
+672
View File
@@ -0,0 +1,672 @@
use crate::{FontId, GlyphId, Pixels, PlatformTextSystem, Point, SharedString, Size, point, px};
use collections::FxHashMap;
use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
use smallvec::SmallVec;
use std::{
borrow::Borrow,
hash::{Hash, Hasher},
ops::Range,
sync::Arc,
};
use super::LineWrapper;
/// A laid out and styled line of text
#[derive(Default, Debug)]
pub struct LineLayout {
/// The font size for this line
pub font_size: Pixels,
/// The width of the line
pub width: Pixels,
/// The ascent of the line
pub ascent: Pixels,
/// The descent of the line
pub descent: Pixels,
/// The shaped runs that make up this line
pub runs: Vec<ShapedRun>,
/// The length of the line in utf-8 bytes
pub len: usize,
}
/// A run of text that has been shaped .
#[derive(Debug, Clone)]
pub struct ShapedRun {
/// The font id for this run
pub font_id: FontId,
/// The glyphs that make up this run
pub glyphs: Vec<ShapedGlyph>,
}
/// A single glyph, ready to paint.
#[derive(Clone, Debug)]
pub struct ShapedGlyph {
/// The ID for this glyph, as determined by the text system.
pub id: GlyphId,
/// The position of this glyph in its containing line.
pub position: Point<Pixels>,
/// The index of this glyph in the original text.
pub index: usize,
/// Whether this glyph is an emoji
pub is_emoji: bool,
}
impl LineLayout {
/// The index for the character at the given x coordinate
pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
if x >= self.width {
None
} else {
for run in self.runs.iter().rev() {
for glyph in run.glyphs.iter().rev() {
if glyph.position.x <= x {
return Some(glyph.index);
}
}
}
Some(0)
}
}
/// closest_index_for_x returns the character boundary closest to the given x coordinate
/// (e.g. to handle aligning up/down arrow keys)
pub fn closest_index_for_x(&self, x: Pixels) -> usize {
let mut prev_index = 0;
let mut prev_x = px(0.);
for run in self.runs.iter() {
for glyph in run.glyphs.iter() {
if glyph.position.x >= x {
if glyph.position.x - x < x - prev_x {
return glyph.index;
} else {
return prev_index;
}
}
prev_index = glyph.index;
prev_x = glyph.position.x;
}
}
if self.len == 1 {
if x > self.width / 2. {
return 1;
} else {
return 0;
}
}
self.len
}
/// The x position of the character at the given index
pub fn x_for_index(&self, index: usize) -> Pixels {
for run in &self.runs {
for glyph in &run.glyphs {
if glyph.index >= index {
return glyph.position.x;
}
}
}
self.width
}
/// The corresponding Font at the given index
pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
for run in &self.runs {
for glyph in &run.glyphs {
if glyph.index >= index {
return Some(run.font_id);
}
}
}
None
}
fn compute_wrap_boundaries(
&self,
text: &str,
wrap_width: Pixels,
max_lines: Option<usize>,
) -> SmallVec<[WrapBoundary; 1]> {
let mut boundaries = SmallVec::new();
let mut first_non_whitespace_ix = None;
let mut last_candidate_ix = None;
let mut last_candidate_x = px(0.);
let mut last_boundary = WrapBoundary {
run_ix: 0,
glyph_ix: 0,
};
let mut last_boundary_x = px(0.);
let mut prev_ch = '\0';
let mut glyphs = self
.runs
.iter()
.enumerate()
.flat_map(move |(run_ix, run)| {
run.glyphs.iter().enumerate().map(move |(glyph_ix, glyph)| {
let character = text[glyph.index..].chars().next().unwrap();
(
WrapBoundary { run_ix, glyph_ix },
character,
glyph.position.x,
)
})
})
.peekable();
while let Some((boundary, ch, x)) = glyphs.next() {
if ch == '\n' {
continue;
}
// Here is very similar to `LineWrapper::wrap_line` to determine text wrapping,
// but there are some differences, so we have to duplicate the code here.
if LineWrapper::is_word_char(ch) {
if prev_ch == ' ' && ch != ' ' && first_non_whitespace_ix.is_some() {
last_candidate_ix = Some(boundary);
last_candidate_x = x;
}
} else {
if ch != ' ' && first_non_whitespace_ix.is_some() {
last_candidate_ix = Some(boundary);
last_candidate_x = x;
}
}
if ch != ' ' && first_non_whitespace_ix.is_none() {
first_non_whitespace_ix = Some(boundary);
}
let next_x = glyphs.peek().map_or(self.width, |(_, _, x)| *x);
let width = next_x - last_boundary_x;
if width > wrap_width && boundary > last_boundary {
// When used line_clamp, we should limit the number of lines.
if let Some(max_lines) = max_lines
&& boundaries.len() >= max_lines - 1
{
break;
}
if let Some(last_candidate_ix) = last_candidate_ix.take() {
last_boundary = last_candidate_ix;
last_boundary_x = last_candidate_x;
} else {
last_boundary = boundary;
last_boundary_x = x;
}
boundaries.push(last_boundary);
}
prev_ch = ch;
}
boundaries
}
}
/// A line of text that has been wrapped to fit a given width
#[derive(Default, Debug)]
pub struct WrappedLineLayout {
/// The line layout, pre-wrapping.
pub unwrapped_layout: Arc<LineLayout>,
/// The boundaries at which the line was wrapped
pub wrap_boundaries: SmallVec<[WrapBoundary; 1]>,
/// The width of the line, if it was wrapped
pub wrap_width: Option<Pixels>,
}
/// A boundary at which a line was wrapped
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct WrapBoundary {
/// The index in the run just before the line was wrapped
pub run_ix: usize,
/// The index of the glyph just before the line was wrapped
pub glyph_ix: usize,
}
impl WrappedLineLayout {
/// The length of the underlying text, in utf8 bytes.
#[allow(clippy::len_without_is_empty)]
pub fn len(&self) -> usize {
self.unwrapped_layout.len
}
/// The width of this line, in pixels, whether or not it was wrapped.
pub fn width(&self) -> Pixels {
self.wrap_width
.unwrap_or(Pixels::MAX)
.min(self.unwrapped_layout.width)
}
/// The size of the whole wrapped text, for the given line_height.
/// can span multiple lines if there are multiple wrap boundaries.
pub fn size(&self, line_height: Pixels) -> Size<Pixels> {
Size {
width: self.width(),
height: line_height * (self.wrap_boundaries.len() + 1),
}
}
/// The ascent of a line in this layout
pub fn ascent(&self) -> Pixels {
self.unwrapped_layout.ascent
}
/// The descent of a line in this layout
pub fn descent(&self) -> Pixels {
self.unwrapped_layout.descent
}
/// The wrap boundaries in this layout
pub fn wrap_boundaries(&self) -> &[WrapBoundary] {
&self.wrap_boundaries
}
/// The font size of this layout
pub fn font_size(&self) -> Pixels {
self.unwrapped_layout.font_size
}
/// The runs in this layout, sans wrapping
pub fn runs(&self) -> &[ShapedRun] {
&self.unwrapped_layout.runs
}
/// The index corresponding to a given position in this layout for the given line height.
///
/// See also [`Self::closest_index_for_position`].
pub fn index_for_position(
&self,
position: Point<Pixels>,
line_height: Pixels,
) -> Result<usize, usize> {
self._index_for_position(position, line_height, false)
}
/// The closest index to a given position in this layout for the given line height.
///
/// Closest means the character boundary closest to the given position.
///
/// See also [`LineLayout::closest_index_for_x`].
pub fn closest_index_for_position(
&self,
position: Point<Pixels>,
line_height: Pixels,
) -> Result<usize, usize> {
self._index_for_position(position, line_height, true)
}
fn _index_for_position(
&self,
mut position: Point<Pixels>,
line_height: Pixels,
closest: bool,
) -> Result<usize, usize> {
let wrapped_line_ix = (position.y / line_height) as usize;
let wrapped_line_start_index;
let wrapped_line_start_x;
if wrapped_line_ix > 0 {
let Some(line_start_boundary) = self.wrap_boundaries.get(wrapped_line_ix - 1) else {
return Err(0);
};
let run = &self.unwrapped_layout.runs[line_start_boundary.run_ix];
let glyph = &run.glyphs[line_start_boundary.glyph_ix];
wrapped_line_start_index = glyph.index;
wrapped_line_start_x = glyph.position.x;
} else {
wrapped_line_start_index = 0;
wrapped_line_start_x = Pixels::ZERO;
};
let wrapped_line_end_index;
let wrapped_line_end_x;
if wrapped_line_ix < self.wrap_boundaries.len() {
let next_wrap_boundary_ix = wrapped_line_ix;
let next_wrap_boundary = self.wrap_boundaries[next_wrap_boundary_ix];
let run = &self.unwrapped_layout.runs[next_wrap_boundary.run_ix];
let glyph = &run.glyphs[next_wrap_boundary.glyph_ix];
wrapped_line_end_index = glyph.index;
wrapped_line_end_x = glyph.position.x;
} else {
wrapped_line_end_index = self.unwrapped_layout.len;
wrapped_line_end_x = self.unwrapped_layout.width;
};
let mut position_in_unwrapped_line = position;
position_in_unwrapped_line.x += wrapped_line_start_x;
if position_in_unwrapped_line.x < wrapped_line_start_x {
Err(wrapped_line_start_index)
} else if position_in_unwrapped_line.x >= wrapped_line_end_x {
Err(wrapped_line_end_index)
} else {
if closest {
Ok(self
.unwrapped_layout
.closest_index_for_x(position_in_unwrapped_line.x))
} else {
Ok(self
.unwrapped_layout
.index_for_x(position_in_unwrapped_line.x)
.unwrap())
}
}
}
/// Returns the pixel position for the given byte index.
pub fn position_for_index(&self, index: usize, line_height: Pixels) -> Option<Point<Pixels>> {
let mut line_start_ix = 0;
let mut line_end_indices = self
.wrap_boundaries
.iter()
.map(|wrap_boundary| {
let run = &self.unwrapped_layout.runs[wrap_boundary.run_ix];
let glyph = &run.glyphs[wrap_boundary.glyph_ix];
glyph.index
})
.chain([self.len()])
.enumerate();
for (ix, line_end_ix) in line_end_indices {
let line_y = ix as f32 * line_height;
if index < line_start_ix {
break;
} else if index > line_end_ix {
line_start_ix = line_end_ix;
continue;
} else {
let line_start_x = self.unwrapped_layout.x_for_index(line_start_ix);
let x = self.unwrapped_layout.x_for_index(index) - line_start_x;
return Some(point(x, line_y));
}
}
None
}
}
pub(crate) struct LineLayoutCache {
previous_frame: Mutex<FrameCache>,
current_frame: RwLock<FrameCache>,
platform_text_system: Arc<dyn PlatformTextSystem>,
}
#[derive(Default)]
struct FrameCache {
lines: FxHashMap<Arc<CacheKey>, Arc<LineLayout>>,
wrapped_lines: FxHashMap<Arc<CacheKey>, Arc<WrappedLineLayout>>,
used_lines: Vec<Arc<CacheKey>>,
used_wrapped_lines: Vec<Arc<CacheKey>>,
}
#[derive(Clone, Default)]
pub(crate) struct LineLayoutIndex {
lines_index: usize,
wrapped_lines_index: usize,
}
impl LineLayoutCache {
pub fn new(platform_text_system: Arc<dyn PlatformTextSystem>) -> Self {
Self {
previous_frame: Mutex::default(),
current_frame: RwLock::default(),
platform_text_system,
}
}
pub fn layout_index(&self) -> LineLayoutIndex {
let frame = self.current_frame.read();
LineLayoutIndex {
lines_index: frame.used_lines.len(),
wrapped_lines_index: frame.used_wrapped_lines.len(),
}
}
pub fn reuse_layouts(&self, range: Range<LineLayoutIndex>) {
let mut previous_frame = &mut *self.previous_frame.lock();
let mut current_frame = &mut *self.current_frame.write();
for key in &previous_frame.used_lines[range.start.lines_index..range.end.lines_index] {
if let Some((key, line)) = previous_frame.lines.remove_entry(key) {
current_frame.lines.insert(key, line);
}
current_frame.used_lines.push(key.clone());
}
for key in &previous_frame.used_wrapped_lines
[range.start.wrapped_lines_index..range.end.wrapped_lines_index]
{
if let Some((key, line)) = previous_frame.wrapped_lines.remove_entry(key) {
current_frame.wrapped_lines.insert(key, line);
}
current_frame.used_wrapped_lines.push(key.clone());
}
}
pub fn truncate_layouts(&self, index: LineLayoutIndex) {
let mut current_frame = &mut *self.current_frame.write();
current_frame.used_lines.truncate(index.lines_index);
current_frame
.used_wrapped_lines
.truncate(index.wrapped_lines_index);
}
pub fn finish_frame(&self) {
let mut prev_frame = self.previous_frame.lock();
let mut curr_frame = self.current_frame.write();
std::mem::swap(&mut *prev_frame, &mut *curr_frame);
curr_frame.lines.clear();
curr_frame.wrapped_lines.clear();
curr_frame.used_lines.clear();
curr_frame.used_wrapped_lines.clear();
}
pub fn layout_wrapped_line<Text>(
&self,
text: Text,
font_size: Pixels,
runs: &[FontRun],
wrap_width: Option<Pixels>,
max_lines: Option<usize>,
) -> Arc<WrappedLineLayout>
where
Text: AsRef<str>,
SharedString: From<Text>,
{
let key = &CacheKeyRef {
text: text.as_ref(),
font_size,
runs,
wrap_width,
force_width: None,
} as &dyn AsCacheKeyRef;
let current_frame = self.current_frame.upgradable_read();
if let Some(layout) = current_frame.wrapped_lines.get(key) {
return layout.clone();
}
let previous_frame_entry = self.previous_frame.lock().wrapped_lines.remove_entry(key);
if let Some((key, layout)) = previous_frame_entry {
let mut current_frame = RwLockUpgradableReadGuard::upgrade(current_frame);
current_frame
.wrapped_lines
.insert(key.clone(), layout.clone());
current_frame.used_wrapped_lines.push(key);
layout
} else {
drop(current_frame);
let text = SharedString::from(text);
let unwrapped_layout = self.layout_line::<&SharedString>(&text, font_size, runs, None);
let wrap_boundaries = if let Some(wrap_width) = wrap_width {
unwrapped_layout.compute_wrap_boundaries(text.as_ref(), wrap_width, max_lines)
} else {
SmallVec::new()
};
let layout = Arc::new(WrappedLineLayout {
unwrapped_layout,
wrap_boundaries,
wrap_width,
});
let key = Arc::new(CacheKey {
text,
font_size,
runs: SmallVec::from(runs),
wrap_width,
force_width: None,
});
let mut current_frame = self.current_frame.write();
current_frame
.wrapped_lines
.insert(key.clone(), layout.clone());
current_frame.used_wrapped_lines.push(key);
layout
}
}
pub fn layout_line<Text>(
&self,
text: Text,
font_size: Pixels,
runs: &[FontRun],
force_width: Option<Pixels>,
) -> Arc<LineLayout>
where
Text: AsRef<str>,
SharedString: From<Text>,
{
let key = &CacheKeyRef {
text: text.as_ref(),
font_size,
runs,
wrap_width: None,
force_width,
} as &dyn AsCacheKeyRef;
let current_frame = self.current_frame.upgradable_read();
if let Some(layout) = current_frame.lines.get(key) {
return layout.clone();
}
let mut current_frame = RwLockUpgradableReadGuard::upgrade(current_frame);
if let Some((key, layout)) = self.previous_frame.lock().lines.remove_entry(key) {
current_frame.lines.insert(key.clone(), layout.clone());
current_frame.used_lines.push(key);
layout
} else {
let text = SharedString::from(text);
let mut layout = self
.platform_text_system
.layout_line(&text, font_size, runs);
if let Some(force_width) = force_width {
let mut glyph_pos = 0;
for run in layout.runs.iter_mut() {
for glyph in run.glyphs.iter_mut() {
if (glyph.position.x - glyph_pos * force_width).abs() > px(1.) {
glyph.position.x = glyph_pos * force_width;
}
glyph_pos += 1;
}
}
}
let key = Arc::new(CacheKey {
text,
font_size,
runs: SmallVec::from(runs),
wrap_width: None,
force_width,
});
let layout = Arc::new(layout);
current_frame.lines.insert(key.clone(), layout.clone());
current_frame.used_lines.push(key);
layout
}
}
}
/// A run of text with a single font.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct FontRun {
pub(crate) len: usize,
pub(crate) font_id: FontId,
}
trait AsCacheKeyRef {
fn as_cache_key_ref(&self) -> CacheKeyRef<'_>;
}
#[derive(Clone, Debug, Eq)]
struct CacheKey {
text: SharedString,
font_size: Pixels,
runs: SmallVec<[FontRun; 1]>,
wrap_width: Option<Pixels>,
force_width: Option<Pixels>,
}
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
struct CacheKeyRef<'a> {
text: &'a str,
font_size: Pixels,
runs: &'a [FontRun],
wrap_width: Option<Pixels>,
force_width: Option<Pixels>,
}
impl PartialEq for dyn AsCacheKeyRef + '_ {
fn eq(&self, other: &dyn AsCacheKeyRef) -> bool {
self.as_cache_key_ref() == other.as_cache_key_ref()
}
}
impl Eq for dyn AsCacheKeyRef + '_ {}
impl Hash for dyn AsCacheKeyRef + '_ {
fn hash<H: Hasher>(&self, state: &mut H) {
self.as_cache_key_ref().hash(state)
}
}
impl AsCacheKeyRef for CacheKey {
fn as_cache_key_ref(&self) -> CacheKeyRef<'_> {
CacheKeyRef {
text: &self.text,
font_size: self.font_size,
runs: self.runs.as_slice(),
wrap_width: self.wrap_width,
force_width: self.force_width,
}
}
}
impl PartialEq for CacheKey {
fn eq(&self, other: &Self) -> bool {
self.as_cache_key_ref().eq(&other.as_cache_key_ref())
}
}
impl Hash for CacheKey {
fn hash<H: Hasher>(&self, state: &mut H) {
self.as_cache_key_ref().hash(state);
}
}
impl<'a> Borrow<dyn AsCacheKeyRef + 'a> for Arc<CacheKey> {
fn borrow(&self) -> &(dyn AsCacheKeyRef + 'a) {
self.as_ref() as &dyn AsCacheKeyRef
}
}
impl AsCacheKeyRef for CacheKeyRef<'_> {
fn as_cache_key_ref(&self) -> CacheKeyRef<'_> {
*self
}
}
+743
View File
@@ -0,0 +1,743 @@
use crate::{FontId, FontRun, Pixels, PlatformTextSystem, SharedString, TextRun, px};
use collections::HashMap;
use std::{iter, sync::Arc};
/// The GPUI line wrapper, used to wrap lines of text to a given width.
pub struct LineWrapper {
platform_text_system: Arc<dyn PlatformTextSystem>,
pub(crate) font_id: FontId,
pub(crate) font_size: Pixels,
cached_ascii_char_widths: [Option<Pixels>; 128],
cached_other_char_widths: HashMap<char, Pixels>,
}
impl LineWrapper {
/// The maximum indent that can be applied to a line.
pub const MAX_INDENT: u32 = 256;
pub(crate) fn new(
font_id: FontId,
font_size: Pixels,
text_system: Arc<dyn PlatformTextSystem>,
) -> Self {
Self {
platform_text_system: text_system,
font_id,
font_size,
cached_ascii_char_widths: [None; 128],
cached_other_char_widths: HashMap::default(),
}
}
/// Wrap a line of text to the given width with this wrapper's font and font size.
pub fn wrap_line<'a>(
&'a mut self,
fragments: &'a [LineFragment],
wrap_width: Pixels,
) -> impl Iterator<Item = Boundary> + 'a {
let mut width = px(0.);
let mut first_non_whitespace_ix = None;
let mut indent = None;
let mut last_candidate_ix = 0;
let mut last_candidate_width = px(0.);
let mut last_wrap_ix = 0;
let mut prev_c = '\0';
let mut index = 0;
let mut candidates = fragments
.iter()
.flat_map(move |fragment| fragment.wrap_boundary_candidates())
.peekable();
iter::from_fn(move || {
for candidate in candidates.by_ref() {
let ix = index;
index += candidate.len_utf8();
let mut new_prev_c = prev_c;
let item_width = match candidate {
WrapBoundaryCandidate::Char { character: c } => {
if c == '\n' {
continue;
}
if Self::is_word_char(c) {
if prev_c == ' ' && c != ' ' && first_non_whitespace_ix.is_some() {
last_candidate_ix = ix;
last_candidate_width = width;
}
} else {
// CJK may not be space separated, e.g.: `Hello world你好世界`
if c != ' ' && first_non_whitespace_ix.is_some() {
last_candidate_ix = ix;
last_candidate_width = width;
}
}
if c != ' ' && first_non_whitespace_ix.is_none() {
first_non_whitespace_ix = Some(ix);
}
new_prev_c = c;
self.width_for_char(c)
}
WrapBoundaryCandidate::Element {
width: element_width,
..
} => {
if prev_c == ' ' && first_non_whitespace_ix.is_some() {
last_candidate_ix = ix;
last_candidate_width = width;
}
if first_non_whitespace_ix.is_none() {
first_non_whitespace_ix = Some(ix);
}
element_width
}
};
width += item_width;
if width > wrap_width && ix > last_wrap_ix {
if let (None, Some(first_non_whitespace_ix)) = (indent, first_non_whitespace_ix)
{
indent = Some(
Self::MAX_INDENT.min((first_non_whitespace_ix - last_wrap_ix) as u32),
);
}
if last_candidate_ix > 0 {
last_wrap_ix = last_candidate_ix;
width -= last_candidate_width;
last_candidate_ix = 0;
} else {
last_wrap_ix = ix;
width = item_width;
}
if let Some(indent) = indent {
width += self.width_for_char(' ') * indent as f32;
}
return Some(Boundary::new(last_wrap_ix, indent.unwrap_or(0)));
}
prev_c = new_prev_c;
}
None
})
}
/// Truncate a line of text to the given width with this wrapper's font and font size.
pub fn truncate_line(
&mut self,
line: SharedString,
truncate_width: Pixels,
truncation_suffix: &str,
runs: &mut Vec<TextRun>,
) -> SharedString {
let mut width = px(0.);
let mut suffix_width = truncation_suffix
.chars()
.map(|c| self.width_for_char(c))
.fold(px(0.0), |a, x| a + x);
let mut char_indices = line.char_indices();
let mut truncate_ix = 0;
for (ix, c) in char_indices {
if width + suffix_width < truncate_width {
truncate_ix = ix;
}
let char_width = self.width_for_char(c);
width += char_width;
if width.floor() > truncate_width {
let result =
SharedString::from(format!("{}{}", &line[..truncate_ix], truncation_suffix));
update_runs_after_truncation(&result, truncation_suffix, runs);
return result;
}
}
line
}
/// Any character in this list should be treated as a word character,
/// meaning it can be part of a word that should not be wrapped.
pub(crate) fn is_word_char(c: char) -> bool {
// ASCII alphanumeric characters, for English, numbers: `Hello123`, etc.
c.is_ascii_alphanumeric() ||
// Latin script in Unicode for French, German, Spanish, etc.
// Latin-1 Supplement
// https://en.wikipedia.org/wiki/Latin-1_Supplement
matches!(c, '\u{00C0}'..='\u{00FF}') ||
// Latin Extended-A
// https://en.wikipedia.org/wiki/Latin_Extended-A
matches!(c, '\u{0100}'..='\u{017F}') ||
// Latin Extended-B
// https://en.wikipedia.org/wiki/Latin_Extended-B
matches!(c, '\u{0180}'..='\u{024F}') ||
// Cyrillic for Russian, Ukrainian, etc.
// https://en.wikipedia.org/wiki/Cyrillic_script_in_Unicode
matches!(c, '\u{0400}'..='\u{04FF}') ||
// Some other known special characters that should be treated as word characters,
// e.g. `a-b`, `var_name`, `I'm`, '@mention`, `#hashtag`, `100%`, `3.1415`,
// `2^3`, `a~b`, `a=1`, `Self::new`, etc.
matches!(c, '-' | '_' | '.' | '\'' | '$' | '%' | '@' | '#' | '^' | '~' | ',' | '=' | ':') ||
// `⋯` character is special used in Zed, to keep this at the end of the line.
matches!(c, '⋯')
}
#[inline(always)]
fn width_for_char(&mut self, c: char) -> Pixels {
if (c as u32) < 128 {
if let Some(cached_width) = self.cached_ascii_char_widths[c as usize] {
cached_width
} else {
let width = self.compute_width_for_char(c);
self.cached_ascii_char_widths[c as usize] = Some(width);
width
}
} else if let Some(cached_width) = self.cached_other_char_widths.get(&c) {
*cached_width
} else {
let width = self.compute_width_for_char(c);
self.cached_other_char_widths.insert(c, width);
width
}
}
fn compute_width_for_char(&self, c: char) -> Pixels {
let mut buffer = [0; 4];
let buffer = c.encode_utf8(&mut buffer);
self.platform_text_system
.layout_line(
buffer,
self.font_size,
&[FontRun {
len: buffer.len(),
font_id: self.font_id,
}],
)
.width
}
}
fn update_runs_after_truncation(result: &str, ellipsis: &str, runs: &mut Vec<TextRun>) {
let mut truncate_at = result.len() - ellipsis.len();
for (run_index, run) in runs.iter_mut().enumerate() {
if run.len <= truncate_at {
truncate_at -= run.len;
} else {
run.len = truncate_at + ellipsis.len();
runs.truncate(run_index + 1);
break;
}
}
}
/// A fragment of a line that can be wrapped.
pub enum LineFragment<'a> {
/// A text fragment consisting of characters.
Text {
/// The text content of the fragment.
text: &'a str,
},
/// A non-text element with a fixed width.
Element {
/// The width of the element in pixels.
width: Pixels,
/// The UTF-8 encoded length of the element.
len_utf8: usize,
},
}
impl<'a> LineFragment<'a> {
/// Creates a new text fragment from the given text.
pub fn text(text: &'a str) -> Self {
LineFragment::Text { text }
}
/// Creates a new non-text element with the given width and UTF-8 encoded length.
pub fn element(width: Pixels, len_utf8: usize) -> Self {
LineFragment::Element { width, len_utf8 }
}
fn wrap_boundary_candidates(&self) -> impl Iterator<Item = WrapBoundaryCandidate> {
let text = match self {
LineFragment::Text { text } => text,
LineFragment::Element { .. } => "\0",
};
text.chars().map(move |character| {
if let LineFragment::Element { width, len_utf8 } = self {
WrapBoundaryCandidate::Element {
width: *width,
len_utf8: *len_utf8,
}
} else {
WrapBoundaryCandidate::Char { character }
}
})
}
}
enum WrapBoundaryCandidate {
Char { character: char },
Element { width: Pixels, len_utf8: usize },
}
impl WrapBoundaryCandidate {
pub fn len_utf8(&self) -> usize {
match self {
WrapBoundaryCandidate::Char { character } => character.len_utf8(),
WrapBoundaryCandidate::Element { len_utf8: len, .. } => *len,
}
}
}
/// A boundary between two lines of text.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Boundary {
/// The index of the last character in a line
pub ix: usize,
/// The indent of the next line.
pub next_indent: u32,
}
impl Boundary {
fn new(ix: usize, next_indent: u32) -> Self {
Self { ix, next_indent }
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
Font, FontFeatures, FontStyle, FontWeight, Hsla, TestAppContext, TestDispatcher, font,
};
#[cfg(target_os = "macos")]
use crate::{TextRun, WindowTextSystem, WrapBoundary};
use rand::prelude::*;
fn build_wrapper() -> LineWrapper {
let dispatcher = TestDispatcher::new(StdRng::seed_from_u64(0));
let cx = TestAppContext::build(dispatcher, None);
let id = cx.text_system().resolve_font(&font(".ZedMono"));
LineWrapper::new(id, px(16.), cx.text_system().platform_text_system.clone())
}
fn generate_test_runs(input_run_len: &[usize]) -> Vec<TextRun> {
input_run_len
.iter()
.map(|run_len| TextRun {
len: *run_len,
font: Font {
family: "Dummy".into(),
features: FontFeatures::default(),
fallbacks: None,
weight: FontWeight::default(),
style: FontStyle::Normal,
},
color: Hsla::default(),
background_color: None,
underline: None,
strikethrough: None,
})
.collect()
}
#[test]
fn test_wrap_line() {
let mut wrapper = build_wrapper();
assert_eq!(
wrapper
.wrap_line(&[LineFragment::text("aa bbb cccc ddddd eeee")], px(72.))
.collect::<Vec<_>>(),
&[
Boundary::new(7, 0),
Boundary::new(12, 0),
Boundary::new(18, 0)
],
);
assert_eq!(
wrapper
.wrap_line(&[LineFragment::text("aaa aaaaaaaaaaaaaaaaaa")], px(72.0))
.collect::<Vec<_>>(),
&[
Boundary::new(4, 0),
Boundary::new(11, 0),
Boundary::new(18, 0)
],
);
assert_eq!(
wrapper
.wrap_line(&[LineFragment::text(" aaaaaaa")], px(72.))
.collect::<Vec<_>>(),
&[
Boundary::new(7, 5),
Boundary::new(9, 5),
Boundary::new(11, 5),
]
);
assert_eq!(
wrapper
.wrap_line(
&[LineFragment::text(" ")],
px(72.)
)
.collect::<Vec<_>>(),
&[
Boundary::new(7, 0),
Boundary::new(14, 0),
Boundary::new(21, 0)
]
);
assert_eq!(
wrapper
.wrap_line(&[LineFragment::text(" aaaaaaaaaaaaaa")], px(72.))
.collect::<Vec<_>>(),
&[
Boundary::new(7, 0),
Boundary::new(14, 3),
Boundary::new(18, 3),
Boundary::new(22, 3),
]
);
// Test wrapping multiple text fragments
assert_eq!(
wrapper
.wrap_line(
&[
LineFragment::text("aa bbb "),
LineFragment::text("cccc ddddd eeee")
],
px(72.)
)
.collect::<Vec<_>>(),
&[
Boundary::new(7, 0),
Boundary::new(12, 0),
Boundary::new(18, 0)
],
);
// Test wrapping with a mix of text and element fragments
assert_eq!(
wrapper
.wrap_line(
&[
LineFragment::text("aa "),
LineFragment::element(px(20.), 1),
LineFragment::text(" bbb "),
LineFragment::element(px(30.), 1),
LineFragment::text(" cccc")
],
px(72.)
)
.collect::<Vec<_>>(),
&[
Boundary::new(5, 0),
Boundary::new(9, 0),
Boundary::new(11, 0)
],
);
// Test with element at the beginning and text afterward
assert_eq!(
wrapper
.wrap_line(
&[
LineFragment::element(px(50.), 1),
LineFragment::text(" aaaa bbbb cccc dddd")
],
px(72.)
)
.collect::<Vec<_>>(),
&[
Boundary::new(2, 0),
Boundary::new(7, 0),
Boundary::new(12, 0),
Boundary::new(17, 0)
],
);
// Test with a large element that forces wrapping by itself
assert_eq!(
wrapper
.wrap_line(
&[
LineFragment::text("short text "),
LineFragment::element(px(100.), 1),
LineFragment::text(" more text")
],
px(72.)
)
.collect::<Vec<_>>(),
&[
Boundary::new(6, 0),
Boundary::new(11, 0),
Boundary::new(12, 0),
Boundary::new(18, 0)
],
);
}
#[test]
fn test_truncate_line() {
let mut wrapper = build_wrapper();
fn perform_test(
wrapper: &mut LineWrapper,
text: &'static str,
result: &'static str,
ellipsis: &str,
) {
let dummy_run_lens = vec![text.len()];
let mut dummy_runs = generate_test_runs(&dummy_run_lens);
assert_eq!(
wrapper.truncate_line(text.into(), px(220.), ellipsis, &mut dummy_runs),
result
);
assert_eq!(dummy_runs.first().unwrap().len, result.len());
}
perform_test(
&mut wrapper,
"aa bbb cccc ddddd eeee ffff gggg",
"aa bbb cccc ddddd eeee",
"",
);
perform_test(
&mut wrapper,
"aa bbb cccc ddddd eeee ffff gggg",
"aa bbb cccc ddddd eee…",
"",
);
perform_test(
&mut wrapper,
"aa bbb cccc ddddd eeee ffff gggg",
"aa bbb cccc dddd......",
"......",
);
}
#[test]
fn test_truncate_multiple_runs() {
let mut wrapper = build_wrapper();
fn perform_test(
wrapper: &mut LineWrapper,
text: &'static str,
result: &str,
run_lens: &[usize],
result_run_len: &[usize],
line_width: Pixels,
) {
let mut dummy_runs = generate_test_runs(run_lens);
assert_eq!(
wrapper.truncate_line(text.into(), line_width, "", &mut dummy_runs),
result
);
for (run, result_len) in dummy_runs.iter().zip(result_run_len) {
assert_eq!(run.len, *result_len);
}
}
// Case 0: Normal
// Text: abcdefghijkl
// Runs: Run0 { len: 12, ... }
//
// Truncate res: abcd… (truncate_at = 4)
// Run res: Run0 { string: abcd…, len: 7, ... }
perform_test(&mut wrapper, "abcdefghijkl", "abcd…", &[12], &[7], px(50.));
// Case 1: Drop some runs
// Text: abcdefghijkl
// Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
//
// Truncate res: abcdef… (truncate_at = 6)
// Runs res: Run0 { string: abcd, len: 4, ... }, Run1 { string: ef…, len:
// 5, ... }
perform_test(
&mut wrapper,
"abcdefghijkl",
"abcdef…",
&[4, 4, 4],
&[4, 5],
px(70.),
);
// Case 2: Truncate at start of some run
// Text: abcdefghijkl
// Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
//
// Truncate res: abcdefgh… (truncate_at = 8)
// Runs res: Run0 { string: abcd, len: 4, ... }, Run1 { string: efgh, len:
// 4, ... }, Run2 { string: …, len: 3, ... }
perform_test(
&mut wrapper,
"abcdefghijkl",
"abcdefgh…",
&[4, 4, 4],
&[4, 4, 3],
px(90.),
);
}
#[test]
fn test_update_run_after_truncation() {
fn perform_test(result: &str, run_lens: &[usize], result_run_lens: &[usize]) {
let mut dummy_runs = generate_test_runs(run_lens);
update_runs_after_truncation(result, "", &mut dummy_runs);
for (run, result_len) in dummy_runs.iter().zip(result_run_lens) {
assert_eq!(run.len, *result_len);
}
}
// Case 0: Normal
// Text: abcdefghijkl
// Runs: Run0 { len: 12, ... }
//
// Truncate res: abcd… (truncate_at = 4)
// Run res: Run0 { string: abcd…, len: 7, ... }
perform_test("abcd…", &[12], &[7]);
// Case 1: Drop some runs
// Text: abcdefghijkl
// Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
//
// Truncate res: abcdef… (truncate_at = 6)
// Runs res: Run0 { string: abcd, len: 4, ... }, Run1 { string: ef…, len:
// 5, ... }
perform_test("abcdef…", &[4, 4, 4], &[4, 5]);
// Case 2: Truncate at start of some run
// Text: abcdefghijkl
// Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
//
// Truncate res: abcdefgh… (truncate_at = 8)
// Runs res: Run0 { string: abcd, len: 4, ... }, Run1 { string: efgh, len:
// 4, ... }, Run2 { string: …, len: 3, ... }
perform_test("abcdefgh…", &[4, 4, 4], &[4, 4, 3]);
}
#[test]
fn test_is_word_char() {
#[track_caller]
fn assert_word(word: &str) {
for c in word.chars() {
assert!(LineWrapper::is_word_char(c), "assertion failed for '{}'", c);
}
}
#[track_caller]
fn assert_not_word(word: &str) {
let found = word.chars().any(|c| !LineWrapper::is_word_char(c));
assert!(found, "assertion failed for '{}'", word);
}
assert_word("Hello123");
assert_word("non-English");
assert_word("var_name");
assert_word("123456");
assert_word("3.1415");
assert_word("10^2");
assert_word("1~2");
assert_word("100%");
assert_word("@mention");
assert_word("#hashtag");
assert_word("$variable");
assert_word("a=1");
assert_word("Self::is_word_char");
assert_word("more⋯");
// Space
assert_not_word("foo bar");
// URL case
assert_word("github.com");
assert_not_word("zed-industries/zed");
assert_not_word("zed-industries\\zed");
assert_not_word("a=1&b=2");
assert_not_word("foo?b=2");
// Latin-1 Supplement
assert_word("ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏ");
// Latin Extended-A
assert_word("ĀāĂ㥹ĆćĈĉĊċČčĎď");
// Latin Extended-B
assert_word("ƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏ");
// Cyrillic
assert_word("АБВГДЕЖЗИЙКЛМНОП");
// non-word characters
assert_not_word("你好");
assert_not_word("안녕하세요");
assert_not_word("こんにちは");
assert_not_word("😀😁😂");
assert_not_word("()[]{}<>");
}
// For compatibility with the test macro
#[cfg(target_os = "macos")]
use crate as gpui;
// These seem to vary wildly based on the text system.
#[cfg(target_os = "macos")]
#[crate::test]
fn test_wrap_shaped_line(cx: &mut TestAppContext) {
cx.update(|cx| {
let text_system = WindowTextSystem::new(cx.text_system().clone());
let normal = TextRun {
len: 0,
font: font("Helvetica"),
color: Default::default(),
underline: Default::default(),
strikethrough: None,
background_color: None,
};
let bold = TextRun {
len: 0,
font: font("Helvetica").bold(),
color: Default::default(),
underline: Default::default(),
strikethrough: None,
background_color: None,
};
let text = "aa bbb cccc ddddd eeee".into();
let lines = text_system
.shape_text(
text,
px(16.),
&[
normal.with_len(4),
bold.with_len(5),
normal.with_len(6),
bold.with_len(1),
normal.with_len(7),
],
Some(px(72.)),
None,
)
.unwrap();
assert_eq!(
lines[0].layout.wrap_boundaries(),
&[
WrapBoundary {
run_ix: 0,
glyph_ix: 7
},
WrapBoundary {
run_ix: 0,
glyph_ix: 12
},
WrapBoundary {
run_ix: 0,
glyph_ix: 18
}
],
);
});
}
}