Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

gpui: Add `ShapedLineCursor` API (#64185)

Bennet Bo Fennerf792c2d72d14
diff --git a/crates/gpui/src/text_system/line.rs b/crates/gpui/src/text_system/line.rs
index 15101e6a2f3..a96cec3c99e 100644
--- a/crates/gpui/src/text_system/line.rs
+++ b/crates/gpui/src/text_system/line.rs
@@ -50,6 +50,31 @@ pub struct ShapedLine {
}
impl ShapedLine {
+ /// Returns a forward-only cursor for this shaped line.
+ pub fn cursor(&self) -> ShapedLineCursor<'_> {
+ assert_eq!(
+ self.len(),
+ self.text.len(),
+ "cannot split a shaped line with an adjusted length"
+ );
+ let byte_ordered = self
+ .layout
+ .runs
+ .iter()
+ .flat_map(|run| run.glyphs.iter().map(|glyph| glyph.index))
+ .is_sorted();
+ ShapedLineCursor {
+ line: self,
+ unordered_remainder: (!byte_ordered).then(|| self.clone()),
+ byte_index: 0,
+ run_index: 0,
+ glyph_index: 0,
+ decoration_index: 0,
+ decoration_offset: 0,
+ x_offset: px(0.),
+ }
+ }
+
/// The length of the line in utf-8 bytes.
#[allow(clippy::len_without_is_empty)]
pub fn len(&self) -> usize {
@@ -204,6 +229,129 @@ impl ShapedLine {
}
}
+/// Incrementally splits a [`ShapedLine`] at increasing UTF-8 byte boundaries.
+///
+/// Each piece preserves the original glyphs and decorations, rebased as in
+/// [`ShapedLine::split_at`]. Byte-ordered glyphs are advanced in linear time,
+/// copying each glyph and byte at most once; visually reordered glyphs fall
+/// back to the existing split operation.
+pub struct ShapedLineCursor<'a> {
+ line: &'a ShapedLine,
+ /// Bidirectional shaping can put glyphs out of byte order.
+ unordered_remainder: Option<ShapedLine>,
+ byte_index: usize,
+ run_index: usize,
+ glyph_index: usize,
+ decoration_index: usize,
+ decoration_offset: u32,
+ x_offset: Pixels,
+}
+
+impl<'a> ShapedLineCursor<'a> {
+ /// Takes the bytes since the previous boundary.
+ ///
+ /// Panics if the boundary precedes the previous one, exceeds the line's
+ /// length, or falls inside a UTF-8 character.
+ pub fn take_until(&mut self, byte_index: usize) -> ShapedLine {
+ assert!(
+ byte_index >= self.byte_index,
+ "split boundary moved backwards"
+ );
+ assert!(
+ byte_index <= self.line.len(),
+ "split boundary exceeds line length"
+ );
+ assert!(
+ self.line.text.is_char_boundary(byte_index),
+ "split boundary is not a UTF-8 character boundary"
+ );
+ let previous_index = self.byte_index;
+ let previous_x = self.x_offset;
+ if let Some(remainder) = &mut self.unordered_remainder {
+ let (piece, rest) = remainder.split_at(byte_index - previous_index);
+ *remainder = rest;
+ self.byte_index = byte_index;
+ self.x_offset = self.line.layout.x_for_index(byte_index);
+ return piece;
+ }
+ let mut runs = Vec::new();
+ let mut next_x = self.line.layout.width;
+ while let Some(run) = self.line.layout.runs.get(self.run_index) {
+ let start = self.glyph_index;
+ while let Some(glyph) = run.glyphs.get(self.glyph_index) {
+ if glyph.index >= byte_index {
+ break;
+ }
+ self.glyph_index += 1;
+ }
+ let end = self.glyph_index;
+ if start < end {
+ runs.push(crate::ShapedRun {
+ font_id: run.font_id,
+ glyphs: run.glyphs[start..end]
+ .iter()
+ .map(|glyph| crate::ShapedGlyph {
+ id: glyph.id,
+ position: point(glyph.position.x - previous_x, glyph.position.y),
+ index: glyph.index - previous_index,
+ is_emoji: glyph.is_emoji,
+ })
+ .collect(),
+ });
+ }
+ if let Some(glyph) = run.glyphs.get(self.glyph_index) {
+ next_x = glyph.position.x;
+ break;
+ }
+ self.run_index += 1;
+ self.glyph_index = 0;
+ }
+ let mut decorations = SmallVec::new();
+ while let Some(decoration) = self.line.decoration_runs.get(self.decoration_index)
+ && (self.decoration_offset < byte_index as u32
+ || (decoration.len == 0 && self.decoration_offset == byte_index as u32))
+ {
+ let end = self.decoration_offset + decoration.len;
+ let start = self.decoration_offset.max(previous_index as u32);
+ let len = end.min(byte_index as u32) - start;
+ if len > 0 || decoration.len == 0 {
+ decorations.push(DecorationRun {
+ len,
+ color: decoration.color,
+ background_color: decoration.background_color,
+ underline: decoration.underline,
+ strikethrough: decoration.strikethrough,
+ });
+ }
+ if end <= byte_index as u32 {
+ self.decoration_index += 1;
+ self.decoration_offset = end;
+ } else {
+ break;
+ }
+ }
+ self.byte_index = byte_index;
+ self.x_offset = next_x;
+ ShapedLine {
+ layout: Arc::new(LineLayout {
+ font_size: self.line.layout.font_size,
+ width: next_x - previous_x,
+ ascent: self.line.layout.ascent,
+ descent: self.line.layout.descent,
+ runs,
+ len: byte_index - previous_index,
+ }),
+ text: SharedString::new(&self.line.text[previous_index..byte_index]),
+ decoration_runs: decorations,
+ }
+ }
+
+ /// Returns the original line's x position at the current boundary.
+ pub fn x_offset(&self) -> Pixels {
+ self.x_offset
+ }
+}
+
impl LineLayout {
/// Paint this layout to the window, using the given decoration runs to color
/// glyphs and draw underlines and strikethroughs.
@@ -1022,4 +1170,258 @@ mod tests {
assert_eq!(right.decoration_runs[1].len, 1);
assert_eq!(right.decoration_runs[1].color, blue);
}
+
+ #[test]
+ fn test_cursor_preserves_shaping_metadata_across_runs() {
+ let line = ShapedLine {
+ layout: Arc::new(LineLayout {
+ font_size: px(16.0),
+ width: px(50.0),
+ ascent: px(12.0),
+ descent: px(4.0),
+ runs: vec![
+ ShapedRun {
+ font_id: FontId(3),
+ glyphs: vec![
+ ShapedGlyph {
+ id: GlyphId(11),
+ position: point(px(0.0), px(1.0)),
+ index: 0,
+ is_emoji: true,
+ },
+ ShapedGlyph {
+ id: GlyphId(12),
+ position: point(px(17.0), px(1.0)),
+ index: 1,
+ is_emoji: false,
+ },
+ ShapedGlyph {
+ id: GlyphId(13),
+ position: point(px(19.0), px(-1.0)),
+ index: 1,
+ is_emoji: false,
+ },
+ ],
+ },
+ ShapedRun {
+ font_id: FontId(8),
+ glyphs: vec![
+ ShapedGlyph {
+ id: GlyphId(21),
+ position: point(px(25.0), px(1.0)),
+ index: 5,
+ is_emoji: true,
+ },
+ ShapedGlyph {
+ id: GlyphId(22),
+ position: point(px(41.0), px(1.0)),
+ index: 7,
+ is_emoji: false,
+ },
+ ],
+ },
+ ],
+ len: 10,
+ }),
+ text: "a😀bcdef".into(),
+ decoration_runs: SmallVec::new(),
+ };
+ let mut cursor = line.cursor();
+ let first = cursor.take_until(5);
+ assert_eq!(first.text.as_ref(), "a😀");
+ assert_eq!(first.runs[0].font_id, FontId(3));
+ assert_eq!(first.runs[0].glyphs[0].id, GlyphId(11));
+ assert!(first.runs[0].glyphs[0].is_emoji);
+ assert_eq!(first.runs[0].glyphs[1].index, 1);
+ assert_eq!(first.runs[0].glyphs[1].position, point(px(17.0), px(1.0)));
+ assert_eq!(first.runs[0].glyphs.len(), 3);
+ assert_eq!(first.runs[0].glyphs[2].index, 1);
+ assert_eq!(first.runs[0].glyphs[2].position, point(px(19.0), px(-1.0)));
+ assert_eq!(cursor.x_offset(), px(25.0));
+
+ let second = cursor.take_until(7);
+ assert_eq!(second.text.as_ref(), "bc");
+ assert_eq!(second.runs[0].font_id, FontId(8));
+ assert_eq!(second.runs[0].glyphs[0].id, GlyphId(21));
+ assert_eq!(second.runs[0].glyphs[0].index, 0);
+ assert_eq!(second.runs[0].glyphs[0].position, point(px(0.0), px(1.0)));
+ assert_eq!(cursor.x_offset(), px(41.0));
+
+ let final_part = cursor.take_until(10);
+ assert_eq!(final_part.text.as_ref(), "def");
+ assert_eq!(final_part.runs[0].font_id, FontId(8));
+ assert_eq!(final_part.runs[0].glyphs[0].id, GlyphId(22));
+ assert_eq!(final_part.runs[0].glyphs[0].index, 0);
+ assert_eq!(
+ final_part.runs[0].glyphs[0].position,
+ point(px(0.0), px(1.0))
+ );
+ }
+
+ #[test]
+ fn test_cursor_preserves_existing_visual_order_splitting() {
+ let line = make_shaped_line("abc", &[(0, 0.0), (2, 10.0), (1, 20.0)], 30.0, &[]);
+ let mut cursor = line.cursor();
+ let mut remainder = line.clone();
+ let mut previous_boundary = 0;
+ for boundary in [0, 1, 2, 3] {
+ let (expected, rest) = remainder.split_at(boundary - previous_boundary);
+ let actual = cursor.take_until(boundary);
+ assert_eq!(actual.text, expected.text);
+ assert_eq!(actual.width(), expected.width());
+ assert_eq!(actual.runs.len(), expected.runs.len());
+ for (actual, expected) in actual.runs.iter().zip(&expected.runs) {
+ assert_eq!(actual.font_id, expected.font_id);
+ assert_eq!(actual.glyphs.len(), expected.glyphs.len());
+ for (actual, expected) in actual.glyphs.iter().zip(&expected.glyphs) {
+ assert_eq!(actual.id, expected.id);
+ assert_eq!(actual.index, expected.index);
+ assert_eq!(actual.position, expected.position);
+ }
+ }
+ assert_eq!(cursor.x_offset(), line.x_for_index(boundary));
+ remainder = rest;
+ previous_boundary = boundary;
+ }
+ }
+
+ #[test]
+ fn test_cursor_partitions_one_decoration_across_three_chunks() {
+ let line = make_shaped_line(
+ "abcdef",
+ &[
+ (0, 0.0),
+ (1, 10.0),
+ (2, 20.0),
+ (3, 30.0),
+ (4, 40.0),
+ (5, 50.0),
+ ],
+ 60.0,
+ &[DecorationRun {
+ len: 6,
+ color: Hsla {
+ h: 0.2,
+ s: 0.4,
+ l: 0.6,
+ a: 1.0,
+ },
+ background_color: None,
+ underline: None,
+ strikethrough: None,
+ }],
+ );
+ let mut cursor = line.cursor();
+ assert_eq!(cursor.take_until(2).decoration_runs[0].len, 2);
+ assert_eq!(cursor.take_until(4).decoration_runs[0].len, 2);
+ assert_eq!(cursor.take_until(6).decoration_runs[0].len, 2);
+ }
+
+ #[test]
+ fn test_cursor_matches_successive_splits_at_ordered_boundaries() {
+ let decorations: Vec<_> = [2, 0, 3, 1]
+ .into_iter()
+ .map(|len| DecorationRun {
+ len,
+ color: Hsla {
+ h: len as f32 / 10.0,
+ s: 0.5,
+ l: 0.5,
+ a: 1.0,
+ },
+ background_color: Some(black()),
+ underline: None,
+ strikethrough: None,
+ })
+ .collect();
+ let line = make_shaped_line(
+ "abcdef",
+ &[(0, 5.0), (0, 5.0), (2, 15.0), (4, 25.0), (5, 35.0)],
+ 45.0,
+ &decorations,
+ );
+ for first in 0..=line.len() {
+ for second in first..=line.len() {
+ let mut cursor = line.cursor();
+ let mut remainder = line.clone();
+ let mut previous_boundary = 0;
+ let mut total_width = px(0.0);
+ let mut text = String::new();
+ for boundary in [first, second, line.len(), line.len()] {
+ let (expected, rest) = remainder.split_at(boundary - previous_boundary);
+ let actual = cursor.take_until(boundary);
+ assert_eq!(actual.text, expected.text);
+ assert_eq!(actual.len(), expected.len());
+ assert_eq!(actual.width(), expected.width());
+ assert_eq!(actual.runs.len(), expected.runs.len());
+ for (actual, expected) in actual.runs.iter().zip(&expected.runs) {
+ assert_eq!(actual.font_id, expected.font_id);
+ assert_eq!(actual.glyphs.len(), expected.glyphs.len());
+ for (actual, expected) in actual.glyphs.iter().zip(&expected.glyphs) {
+ assert_eq!(actual.id, expected.id);
+ assert_eq!(actual.index, expected.index);
+ assert_eq!(actual.position, expected.position);
+ }
+ }
+ assert_eq!(actual.decoration_runs.len(), expected.decoration_runs.len());
+ for (actual, expected) in
+ actual.decoration_runs.iter().zip(&expected.decoration_runs)
+ {
+ assert_eq!(actual.len, expected.len);
+ assert_eq!(actual.color, expected.color);
+ assert_eq!(actual.background_color, expected.background_color);
+ }
+ total_width += actual.width();
+ text.push_str(&actual.text);
+ remainder = rest;
+ previous_boundary = boundary;
+ }
+ assert_eq!(total_width, line.width());
+ assert_eq!(text, line.text.as_ref());
+ }
+ }
+ }
+
+ #[test]
+ fn test_cursor_empty_chunks_and_repeated_boundaries() {
+ let line = make_shaped_line("ab", &[(0, 5.0), (1, 15.0)], 20.0, &[]);
+ let mut cursor = line.cursor();
+ assert_eq!(cursor.take_until(0).text.as_ref(), "");
+ assert_eq!(cursor.take_until(0).text.as_ref(), "");
+ assert_eq!(cursor.take_until(1).text.as_ref(), "a");
+ assert_eq!(cursor.take_until(2).text.as_ref(), "b");
+ assert_eq!(cursor.take_until(2).text.as_ref(), "");
+ let empty = make_shaped_line("", &[], 0.0, &[]);
+ let piece = empty.cursor().take_until(0);
+ assert!(piece.text.is_empty());
+ assert!(piece.runs.is_empty());
+ assert_eq!(piece.width(), px(0.0));
+ }
+
+ #[test]
+ fn test_cursor_rejects_invalid_boundaries() {
+ let line = make_shaped_line("é", &[(0, 0.0)], 10.0, &[]);
+ let mut cursor = line.cursor();
+ assert!(
+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ cursor.take_until(1);
+ }))
+ .is_err()
+ );
+ let mut cursor = line.cursor();
+ cursor.take_until(2);
+ assert!(
+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ cursor.take_until(0);
+ }))
+ .is_err()
+ );
+ let mut cursor = line.cursor();
+ assert!(
+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ cursor.take_until(3);
+ }))
+ .is_err()
+ );
+ }
}