BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-pre / src / text_system / line.rs

line.rs

line.rs 73.6 KiB Download Raw
1use crate::{
2 App, Bounds, DevicePixels, Half, Hsla, LineLayout, Pixels, Point, RenderGlyphParams, Result,
3 SharedString, StrikethroughStyle, TextAlign, UnderlineStyle, Window, WrapBoundary,
4 WrappedLineLayout, black, fill, point, px, size, underline_y_offset,
5};
6use derive_more::{Deref, DerefMut};
7use smallvec::SmallVec;
8use std::{ops::Range, sync::Arc};
9
10/// Pre-computed glyph data for efficient painting without per-glyph cache lookups.
11///
12/// This is produced by `ShapedLine::compute_glyph_raster_data` during prepaint
13/// and consumed by `ShapedLine::paint_with_raster_data` during paint.
14#[derive(Clone, Debug)]
15pub struct GlyphRasterData {
16 /// The raster bounds for each glyph, in paint order.
17 pub bounds: Vec<Bounds<DevicePixels>>,
18 /// The render params for each glyph (needed for sprite atlas lookup).
19 pub params: Vec<RenderGlyphParams>,
20}
21
22/// Set the text decoration for a run of text.
23#[derive(Debug, Clone)]
24pub struct DecorationRun {
25 /// The length of the run in utf-8 bytes.
26 pub len: u32,
27
28 /// The color for this run
29 pub color: Hsla,
30
31 /// The background color for this run
32 pub background_color: Option<Hsla>,
33
34 /// The underline style for this run
35 pub underline: Option<UnderlineStyle>,
36
37 /// The strikethrough style for this run
38 pub strikethrough: Option<StrikethroughStyle>,
39}
40
41/// A line of text that has been shaped and decorated.
42#[derive(Clone, Default, Debug, Deref, DerefMut)]
43pub struct ShapedLine {
44 #[deref]
45 #[deref_mut]
46 pub(crate) layout: Arc<LineLayout>,
47 /// The text that was shaped for this line.
48 pub text: SharedString,
49 pub(crate) decoration_runs: SmallVec<[DecorationRun; 32]>,
50}
51
52impl ShapedLine {
53 /// Returns a forward-only cursor for this shaped line.
54 pub fn cursor(&self) -> ShapedLineCursor<'_> {
55 assert_eq!(
56 self.len(),
57 self.text.len(),
58 "cannot split a shaped line with an adjusted length"
59 );
60 let byte_ordered = self
61 .layout
62 .runs
63 .iter()
64 .flat_map(|run| run.glyphs.iter().map(|glyph| glyph.index))
65 .is_sorted();
66 ShapedLineCursor {
67 line: self,
68 unordered_remainder: (!byte_ordered).then(|| self.clone()),
69 byte_index: 0,
70 run_index: 0,
71 glyph_index: 0,
72 decoration_index: 0,
73 decoration_offset: 0,
74 x_offset: px(0.),
75 }
76 }
77
78 /// The length of the line in utf-8 bytes.
79 #[allow(clippy::len_without_is_empty)]
80 pub fn len(&self) -> usize {
81 self.layout.len
82 }
83
84 /// The width of the shaped line in pixels.
85 ///
86 /// This is the glyph advance width computed by the text shaping system and is useful for
87 /// incrementally advancing a "pen" when painting multiple fragments on the same row.
88 pub fn width(&self) -> Pixels {
89 self.layout.width
90 }
91
92 /// Override the len, useful if you're rendering text a
93 /// as text b (e.g. rendering invisibles).
94 pub fn with_len(mut self, len: usize) -> Self {
95 let layout = self.layout.as_ref();
96 self.layout = Arc::new(LineLayout {
97 font_size: layout.font_size,
98 width: layout.width,
99 ascent: layout.ascent,
100 descent: layout.descent,
101 runs: layout.runs.clone(),
102 len,
103 });
104 self
105 }
106
107 /// Paint the line of text to the window.
108 pub fn paint(
109 &self,
110 origin: Point<Pixels>,
111 line_height: Pixels,
112 align: TextAlign,
113 align_width: Option<Pixels>,
114 window: &mut Window,
115 cx: &mut App,
116 ) -> Result<()> {
117 self.paint_with_underline_handler(
118 origin,
119 line_height,
120 align,
121 align_width,
122 window,
123 cx,
124 |_, origin, width, style, window| window.paint_underline(origin, width, style),
125 )
126 }
127
128 /// Paint the line with a handler for each underline.
129 pub fn paint_with_underline_handler(
130 &self,
131 origin: Point<Pixels>,
132 line_height: Pixels,
133 align: TextAlign,
134 align_width: Option<Pixels>,
135 window: &mut Window,
136 cx: &mut App,
137 mut paint_underline: impl FnMut(
138 Range<usize>,
139 Point<Pixels>,
140 Pixels,
141 &UnderlineStyle,
142 &mut Window,
143 ),
144 ) -> Result<()> {
145 paint_line(
146 origin,
147 &self.layout,
148 line_height,
149 align,
150 align_width,
151 &self.decoration_runs,
152 &[],
153 window,
154 cx,
155 &mut paint_underline,
156 )
157 }
158
159 /// Paint the background of the line to the window.
160 pub fn paint_background(
161 &self,
162 origin: Point<Pixels>,
163 line_height: Pixels,
164 align: TextAlign,
165 align_width: Option<Pixels>,
166 window: &mut Window,
167 cx: &mut App,
168 ) -> Result<()> {
169 paint_line_background(
170 origin,
171 &self.layout,
172 line_height,
173 align,
174 align_width,
175 &self.decoration_runs,
176 &[],
177 window,
178 cx,
179 )?;
180
181 Ok(())
182 }
183
184 /// Split this shaped line at a byte index, returning `(prefix, suffix)`.
185 ///
186 /// - `prefix` contains glyphs for bytes `[0, byte_index)` with original positions.
187 /// Its width equals the x-advance up to the split point.
188 /// - `suffix` contains glyphs for bytes `[byte_index, len)` with positions
189 /// shifted left so the first glyph starts at x=0, and byte indices rebased to 0.
190 /// - Decoration runs are partitioned at the boundary; a run that straddles it is
191 /// split into two with adjusted lengths.
192 /// - `font_size`, `ascent`, and `descent` are copied to both halves.
193 pub fn split_at(&self, byte_index: usize) -> (ShapedLine, ShapedLine) {
194 let (left_layout, right_layout) = self.layout.split_at(byte_index);
195
196 // Partition decoration runs. A run straddling the boundary is split into two.
197 let mut left_decorations = SmallVec::new();
198 let mut right_decorations = SmallVec::new();
199 let mut decoration_offset = 0u32;
200 let split_point = byte_index as u32;
201
202 for decoration in &self.decoration_runs {
203 let run_end = decoration_offset + decoration.len;
204
205 if run_end <= split_point {
206 left_decorations.push(decoration.clone());
207 } else if decoration_offset >= split_point {
208 right_decorations.push(decoration.clone());
209 } else {
210 let left_len = split_point - decoration_offset;
211 let right_len = run_end - split_point;
212 left_decorations.push(DecorationRun {
213 len: left_len,
214 color: decoration.color,
215 background_color: decoration.background_color,
216 underline: decoration.underline,
217 strikethrough: decoration.strikethrough,
218 });
219 right_decorations.push(DecorationRun {
220 len: right_len,
221 color: decoration.color,
222 background_color: decoration.background_color,
223 underline: decoration.underline,
224 strikethrough: decoration.strikethrough,
225 });
226 }
227
228 decoration_offset = run_end;
229 }
230
231 // Split text
232 let left_text = if byte_index == self.text.len() {
233 self.text.clone()
234 } else {
235 SharedString::new(&self.text[..byte_index])
236 };
237 let right_text = if byte_index == 0 {
238 self.text.clone()
239 } else {
240 SharedString::new(&self.text[byte_index..])
241 };
242
243 let left = ShapedLine {
244 layout: Arc::new(left_layout),
245 text: left_text,
246 decoration_runs: left_decorations,
247 };
248
249 let right = ShapedLine {
250 layout: Arc::new(right_layout),
251 text: right_text,
252 decoration_runs: right_decorations,
253 };
254
255 (left, right)
256 }
257}
258
259/// Incrementally splits a [`ShapedLine`] at increasing UTF-8 byte boundaries.
260///
261/// Each piece preserves the original glyphs and decorations, rebased as in
262/// [`ShapedLine::split_at`]. Byte-ordered glyphs are advanced in linear time,
263/// copying each glyph and byte at most once; visually reordered glyphs fall
264/// back to the existing split operation.
265pub struct ShapedLineCursor<'a> {
266 line: &'a ShapedLine,
267 /// Bidirectional shaping can put glyphs out of byte order.
268 unordered_remainder: Option<ShapedLine>,
269 byte_index: usize,
270 run_index: usize,
271 glyph_index: usize,
272 decoration_index: usize,
273 decoration_offset: u32,
274 x_offset: Pixels,
275}
276
277impl<'a> ShapedLineCursor<'a> {
278 /// Takes the bytes since the previous boundary.
279 ///
280 /// Panics if the boundary precedes the previous one, exceeds the line's
281 /// length, or falls inside a UTF-8 character.
282 pub fn take_until(&mut self, byte_index: usize) -> ShapedLine {
283 assert!(
284 byte_index >= self.byte_index,
285 "split boundary moved backwards"
286 );
287 assert!(
288 byte_index <= self.line.len(),
289 "split boundary exceeds line length"
290 );
291 assert!(
292 self.line.text.is_char_boundary(byte_index),
293 "split boundary is not a UTF-8 character boundary"
294 );
295 let previous_index = self.byte_index;
296 let previous_x = self.x_offset;
297 if let Some(remainder) = &mut self.unordered_remainder {
298 let (piece, rest) = remainder.split_at(byte_index - previous_index);
299 *remainder = rest;
300 self.byte_index = byte_index;
301 self.x_offset = self.line.layout.x_for_index(byte_index);
302 return piece;
303 }
304 let mut runs = Vec::new();
305 let mut next_x = self.line.layout.width;
306 while let Some(run) = self.line.layout.runs.get(self.run_index) {
307 let start = self.glyph_index;
308 while let Some(glyph) = run.glyphs.get(self.glyph_index) {
309 if glyph.index >= byte_index {
310 break;
311 }
312 self.glyph_index += 1;
313 }
314 let end = self.glyph_index;
315 if start < end {
316 runs.push(crate::ShapedRun {
317 font_id: run.font_id,
318 glyphs: run.glyphs[start..end]
319 .iter()
320 .map(|glyph| crate::ShapedGlyph {
321 id: glyph.id,
322 position: point(glyph.position.x - previous_x, glyph.position.y),
323 index: glyph.index - previous_index,
324 is_emoji: glyph.is_emoji,
325 })
326 .collect(),
327 });
328 }
329 if let Some(glyph) = run.glyphs.get(self.glyph_index) {
330 next_x = glyph.position.x;
331 break;
332 }
333 self.run_index += 1;
334 self.glyph_index = 0;
335 }
336 let mut decorations = SmallVec::new();
337 while let Some(decoration) = self.line.decoration_runs.get(self.decoration_index)
338 && (self.decoration_offset < byte_index as u32
339 || (decoration.len == 0 && self.decoration_offset == byte_index as u32))
340 {
341 let end = self.decoration_offset + decoration.len;
342 let start = self.decoration_offset.max(previous_index as u32);
343 let len = end.min(byte_index as u32) - start;
344 if len > 0 || decoration.len == 0 {
345 decorations.push(DecorationRun {
346 len,
347 color: decoration.color,
348 background_color: decoration.background_color,
349 underline: decoration.underline,
350 strikethrough: decoration.strikethrough,
351 });
352 }
353 if end <= byte_index as u32 {
354 self.decoration_index += 1;
355 self.decoration_offset = end;
356 } else {
357 break;
358 }
359 }
360 self.byte_index = byte_index;
361 self.x_offset = next_x;
362 ShapedLine {
363 layout: Arc::new(LineLayout {
364 font_size: self.line.layout.font_size,
365 width: next_x - previous_x,
366 ascent: self.line.layout.ascent,
367 descent: self.line.layout.descent,
368 runs,
369 len: byte_index - previous_index,
370 }),
371 text: SharedString::new(&self.line.text[previous_index..byte_index]),
372 decoration_runs: decorations,
373 }
374 }
375
376 /// Returns the original line's x position at the current boundary.
377 pub fn x_offset(&self) -> Pixels {
378 self.x_offset
379 }
380}
381
382impl LineLayout {
383 /// Paint this layout to the window, using the given decoration runs to color
384 /// glyphs and draw underlines and strikethroughs.
385 ///
386 /// This is a lower-level alternative to [`ShapedLine::paint`] for callers that
387 /// hold a bare layout and track decorations themselves.
388 pub fn paint(
389 &self,
390 origin: Point<Pixels>,
391 line_height: Pixels,
392 align: TextAlign,
393 align_width: Option<Pixels>,
394 decoration_runs: &[DecorationRun],
395 window: &mut Window,
396 cx: &mut App,
397 ) -> Result<()> {
398 paint_line(
399 origin,
400 self,
401 line_height,
402 align,
403 align_width,
404 decoration_runs,
405 &[],
406 window,
407 cx,
408 &mut |_, origin, width, style, window| window.paint_underline(origin, width, style),
409 )
410 }
411
412 /// Paint the background of this layout to the window, using the given
413 /// decoration runs to determine background colors.
414 ///
415 /// This is a lower-level alternative to [`ShapedLine::paint_background`] for
416 /// callers that hold a bare layout and track decorations themselves.
417 pub fn paint_background(
418 &self,
419 origin: Point<Pixels>,
420 line_height: Pixels,
421 align: TextAlign,
422 align_width: Option<Pixels>,
423 decoration_runs: &[DecorationRun],
424 window: &mut Window,
425 cx: &mut App,
426 ) -> Result<()> {
427 paint_line_background(
428 origin,
429 self,
430 line_height,
431 align,
432 align_width,
433 decoration_runs,
434 &[],
435 window,
436 cx,
437 )
438 }
439}
440
441/// A line of text that has been shaped, decorated, and wrapped by the text layout system.
442#[derive(Default, Debug, Deref, DerefMut)]
443pub struct WrappedLine {
444 #[deref]
445 #[deref_mut]
446 pub(crate) layout: Arc<WrappedLineLayout>,
447 /// The text that was shaped for this line.
448 pub text: SharedString,
449 pub(crate) decoration_runs: Vec<DecorationRun>,
450}
451
452impl WrappedLine {
453 /// The length of the underlying, unwrapped layout, in utf-8 bytes.
454 #[allow(clippy::len_without_is_empty)]
455 pub fn len(&self) -> usize {
456 self.layout.len()
457 }
458
459 /// Paint this line of text to the window.
460 pub fn paint(
461 &self,
462 origin: Point<Pixels>,
463 line_height: Pixels,
464 align: TextAlign,
465 bounds: Option<Bounds<Pixels>>,
466 window: &mut Window,
467 cx: &mut App,
468 ) -> Result<()> {
469 let align_width = match bounds {
470 Some(bounds) => Some(bounds.size.width),
471 None => self.layout.wrap_width,
472 };
473
474 paint_line(
475 origin,
476 &self.layout.unwrapped_layout,
477 line_height,
478 align,
479 align_width,
480 &self.decoration_runs,
481 &self.wrap_boundaries,
482 window,
483 cx,
484 &mut |_, origin, width, style, window| window.paint_underline(origin, width, style),
485 )?;
486
487 Ok(())
488 }
489
490 /// Paint the background of line of text to the window.
491 pub fn paint_background(
492 &self,
493 origin: Point<Pixels>,
494 line_height: Pixels,
495 align: TextAlign,
496 bounds: Option<Bounds<Pixels>>,
497 window: &mut Window,
498 cx: &mut App,
499 ) -> Result<()> {
500 let align_width = match bounds {
501 Some(bounds) => Some(bounds.size.width),
502 None => self.layout.wrap_width,
503 };
504
505 paint_line_background(
506 origin,
507 &self.layout.unwrapped_layout,
508 line_height,
509 align,
510 align_width,
511 &self.decoration_runs,
512 &self.wrap_boundaries,
513 window,
514 cx,
515 )?;
516
517 Ok(())
518 }
519}
520
521fn paint_line(
522 origin: Point<Pixels>,
523 layout: &LineLayout,
524 line_height: Pixels,
525 align: TextAlign,
526 align_width: Option<Pixels>,
527 decoration_runs: &[DecorationRun],
528 wrap_boundaries: &[WrapBoundary],
529 window: &mut Window,
530 cx: &mut App,
531 paint_underline: &mut dyn FnMut(
532 Range<usize>,
533 Point<Pixels>,
534 Pixels,
535 &UnderlineStyle,
536 &mut Window,
537 ),
538) -> Result<()> {
539 let line_bounds = line_paint_bounds(
540 origin,
541 layout,
542 line_height,
543 align,
544 align_width,
545 wrap_boundaries,
546 );
547 window.paint_layer(line_bounds, |window| {
548 let padding_top = (line_height - layout.ascent - layout.descent) / 2.;
549 let baseline_offset = point(px(0.), padding_top + layout.ascent);
550 let underline_y_offset = underline_y_offset(line_height, layout.ascent, layout.descent);
551 let mut decoration_runs = decoration_runs.iter();
552 let mut wraps = wrap_boundaries.iter().peekable();
553 let mut run_end = 0;
554 let mut color = black();
555 let mut current_underline: Option<(Point<Pixels>, UnderlineStyle, Range<usize>)> = None;
556 let mut current_strikethrough: Option<(Point<Pixels>, StrikethroughStyle)> = None;
557 let text_system = cx.text_system().clone();
558 let segment_left_edges = segment_left_edges(layout, wrap_boundaries);
559 let mut segment = 0;
560 let mut glyph_origin = point(
561 aligned_origin_x(
562 origin,
563 align_width.unwrap_or(layout.width),
564 px(0.0),
565 &align,
566 layout,
567 wraps.peek(),
568 ) - segment_left_edges[0],
569 origin.y,
570 );
571 let mut prev_glyph_position = Point::default();
572 let mut max_glyph_size = size(px(0.), px(0.));
573 let mut first_glyph_x = origin.x;
574 for (run_ix, run) in layout.runs.iter().enumerate() {
575 max_glyph_size = text_system.bounding_box(run.font_id, layout.font_size).size;
576
577 for (glyph_ix, glyph) in run.glyphs.iter().enumerate() {
578 glyph_origin.x += glyph.position.x - prev_glyph_position.x;
579 if glyph_ix == 0 && run_ix == 0 {
580 first_glyph_x = glyph_origin.x;
581 }
582
583 if wraps.peek() == Some(&&WrapBoundary { run_ix, glyph_ix }) {
584 wraps.next();
585 if let Some((underline_origin, underline_style, underline_range)) =
586 current_underline.as_mut()
587 {
588 if glyph_origin.x == underline_origin.x {
589 underline_origin.x -= max_glyph_size.width.half();
590 };
591 paint_underline(
592 underline_range.clone(),
593 *underline_origin,
594 glyph_origin.x - underline_origin.x,
595 underline_style,
596 window,
597 );
598 if glyph.index < run_end {
599 underline_origin.x = origin.x;
600 underline_origin.y += line_height;
601 } else {
602 current_underline = None;
603 }
604 }
605 if let Some((strikethrough_origin, strikethrough_style)) =
606 current_strikethrough.as_mut()
607 {
608 if glyph_origin.x == strikethrough_origin.x {
609 strikethrough_origin.x -= max_glyph_size.width.half();
610 };
611 window.paint_strikethrough(
612 *strikethrough_origin,
613 glyph_origin.x - strikethrough_origin.x,
614 strikethrough_style,
615 );
616 if glyph.index < run_end {
617 strikethrough_origin.x = origin.x;
618 strikethrough_origin.y += line_height;
619 } else {
620 current_strikethrough = None;
621 }
622 }
623
624 segment += 1;
625 glyph_origin.x = aligned_origin_x(
626 origin,
627 align_width.unwrap_or(layout.width),
628 glyph.position.x,
629 &align,
630 layout,
631 wraps.peek(),
632 ) + glyph.position.x
633 - segment_left_edges[segment];
634 glyph_origin.y += line_height;
635 }
636 prev_glyph_position = glyph.position;
637
638 let mut finished_underline: Option<(Point<Pixels>, UnderlineStyle, Range<usize>)> =
639 None;
640 let mut finished_strikethrough: Option<(Point<Pixels>, StrikethroughStyle)> = None;
641 if glyph.index >= run_end {
642 let mut style_run = decoration_runs.next();
643
644 // ignore style runs that apply to a partial glyph
645 while let Some(run) = style_run {
646 if glyph.index < run_end + (run.len as usize) {
647 break;
648 }
649 run_end += run.len as usize;
650 style_run = decoration_runs.next();
651 }
652
653 if let Some(style_run) = style_run {
654 let style_run_start = run_end;
655 if let Some((_, underline_style, underline_range)) = &mut current_underline
656 {
657 if style_run.underline.as_ref() != Some(underline_style) {
658 finished_underline = current_underline.take();
659 } else {
660 underline_range.end = style_run_start + style_run.len as usize;
661 }
662 }
663 if let Some(run_underline) = style_run.underline.as_ref() {
664 current_underline.get_or_insert((
665 point(glyph_origin.x, glyph_origin.y + underline_y_offset),
666 UnderlineStyle {
667 color: Some(run_underline.color.unwrap_or(style_run.color)),
668 thickness: run_underline.thickness,
669 wavy: run_underline.wavy,
670 },
671 style_run_start..style_run_start + style_run.len as usize,
672 ));
673 }
674 if let Some((_, strikethrough_style)) = &mut current_strikethrough
675 && style_run.strikethrough.as_ref() != Some(strikethrough_style)
676 {
677 finished_strikethrough = current_strikethrough.take();
678 }
679 if let Some(run_strikethrough) = style_run.strikethrough.as_ref() {
680 current_strikethrough.get_or_insert((
681 point(
682 glyph_origin.x,
683 glyph_origin.y
684 + (((layout.ascent * 0.5) + baseline_offset.y) * 0.5),
685 ),
686 StrikethroughStyle {
687 color: Some(run_strikethrough.color.unwrap_or(style_run.color)),
688 thickness: run_strikethrough.thickness,
689 },
690 ));
691 }
692
693 run_end += style_run.len as usize;
694 color = style_run.color;
695 } else {
696 run_end = layout.len;
697 finished_underline = current_underline.take();
698 finished_strikethrough = current_strikethrough.take();
699 }
700 }
701
702 if let Some((mut underline_origin, underline_style, underline_range)) =
703 finished_underline
704 {
705 if underline_origin.x == glyph_origin.x {
706 underline_origin.x -= max_glyph_size.width.half();
707 };
708 paint_underline(
709 underline_range,
710 underline_origin,
711 glyph_origin.x - underline_origin.x,
712 &underline_style,
713 window,
714 );
715 }
716
717 if let Some((mut strikethrough_origin, strikethrough_style)) =
718 finished_strikethrough
719 {
720 if strikethrough_origin.x == glyph_origin.x {
721 strikethrough_origin.x -= max_glyph_size.width.half();
722 };
723 window.paint_strikethrough(
724 strikethrough_origin,
725 glyph_origin.x - strikethrough_origin.x,
726 &strikethrough_style,
727 );
728 }
729
730 let max_glyph_bounds = Bounds {
731 origin: glyph_origin,
732 size: max_glyph_size,
733 };
734
735 let content_mask = window.content_mask();
736 if max_glyph_bounds.intersects(&content_mask.bounds) {
737 let vertical_offset = point(px(0.0), glyph.position.y);
738 if glyph.is_emoji {
739 window.paint_emoji(
740 glyph_origin + baseline_offset + vertical_offset,
741 run.font_id,
742 glyph.id,
743 layout.font_size,
744 )?;
745 } else {
746 window.paint_glyph(
747 glyph_origin + baseline_offset + vertical_offset,
748 run.font_id,
749 glyph.id,
750 layout.font_size,
751 color,
752 )?;
753 }
754 }
755 }
756 }
757
758 let mut last_line_end_x = first_glyph_x + layout.width;
759 if let Some(boundary) = wrap_boundaries.last() {
760 let run = &layout.runs[boundary.run_ix];
761 let glyph = &run.glyphs[boundary.glyph_ix];
762 last_line_end_x -= glyph.position.x;
763 }
764
765 if let Some((mut underline_start, underline_style, underline_range)) =
766 current_underline.take()
767 {
768 if last_line_end_x == underline_start.x {
769 underline_start.x -= max_glyph_size.width.half()
770 };
771 paint_underline(
772 underline_range,
773 underline_start,
774 last_line_end_x - underline_start.x,
775 &underline_style,
776 window,
777 );
778 }
779
780 if let Some((mut strikethrough_start, strikethrough_style)) = current_strikethrough.take() {
781 if last_line_end_x == strikethrough_start.x {
782 strikethrough_start.x -= max_glyph_size.width.half()
783 };
784 window.paint_strikethrough(
785 strikethrough_start,
786 last_line_end_x - strikethrough_start.x,
787 &strikethrough_style,
788 );
789 }
790
791 Ok(())
792 })
793}
794
795fn paint_line_background(
796 origin: Point<Pixels>,
797 layout: &LineLayout,
798 line_height: Pixels,
799 align: TextAlign,
800 align_width: Option<Pixels>,
801 decoration_runs: &[DecorationRun],
802 wrap_boundaries: &[WrapBoundary],
803 window: &mut Window,
804 cx: &mut App,
805) -> Result<()> {
806 let line_bounds = line_paint_bounds(
807 origin,
808 layout,
809 line_height,
810 align,
811 align_width,
812 wrap_boundaries,
813 );
814 window.paint_layer(line_bounds, |window| {
815 let mut decoration_runs = decoration_runs.iter();
816 let mut wraps = wrap_boundaries.iter().peekable();
817 let mut run_end = 0;
818 let mut current_background: Option<(Point<Pixels>, Hsla)> = None;
819 let text_system = cx.text_system().clone();
820 let segment_left_edges = segment_left_edges(layout, wrap_boundaries);
821 let mut segment = 0;
822 let mut glyph_origin = point(
823 aligned_origin_x(
824 origin,
825 align_width.unwrap_or(layout.width),
826 px(0.0),
827 &align,
828 layout,
829 wraps.peek(),
830 ) - segment_left_edges[0],
831 origin.y,
832 );
833 let mut prev_glyph_position = Point::default();
834 let mut max_glyph_size = size(px(0.), px(0.));
835 for (run_ix, run) in layout.runs.iter().enumerate() {
836 max_glyph_size = text_system.bounding_box(run.font_id, layout.font_size).size;
837
838 for (glyph_ix, glyph) in run.glyphs.iter().enumerate() {
839 glyph_origin.x += glyph.position.x - prev_glyph_position.x;
840
841 if wraps.peek() == Some(&&WrapBoundary { run_ix, glyph_ix }) {
842 wraps.next();
843 if let Some((background_origin, background_color)) = current_background.as_mut()
844 {
845 if glyph_origin.x == background_origin.x {
846 background_origin.x -= max_glyph_size.width.half()
847 }
848 window.paint_quad(fill(
849 Bounds {
850 origin: *background_origin,
851 size: size(glyph_origin.x - background_origin.x, line_height),
852 },
853 *background_color,
854 ));
855 if glyph.index < run_end {
856 background_origin.x = origin.x;
857 background_origin.y += line_height;
858 } else {
859 current_background = None;
860 }
861 }
862
863 segment += 1;
864 glyph_origin.x = aligned_origin_x(
865 origin,
866 align_width.unwrap_or(layout.width),
867 glyph.position.x,
868 &align,
869 layout,
870 wraps.peek(),
871 ) + glyph.position.x
872 - segment_left_edges[segment];
873 glyph_origin.y += line_height;
874 }
875 prev_glyph_position = glyph.position;
876
877 let mut finished_background: Option<(Point<Pixels>, Hsla)> = None;
878 if glyph.index >= run_end {
879 let mut style_run = decoration_runs.next();
880
881 // ignore style runs that apply to a partial glyph
882 while let Some(run) = style_run {
883 if glyph.index < run_end + (run.len as usize) {
884 break;
885 }
886 run_end += run.len as usize;
887 style_run = decoration_runs.next();
888 }
889
890 if let Some(style_run) = style_run {
891 if let Some((_, background_color)) = &mut current_background
892 && style_run.background_color.as_ref() != Some(background_color)
893 {
894 finished_background = current_background.take();
895 }
896 if let Some(run_background) = style_run.background_color {
897 current_background.get_or_insert((
898 point(glyph_origin.x, glyph_origin.y),
899 run_background,
900 ));
901 }
902 run_end += style_run.len as usize;
903 } else {
904 run_end = layout.len;
905 finished_background = current_background.take();
906 }
907 }
908
909 if let Some((mut background_origin, background_color)) = finished_background {
910 let mut width = glyph_origin.x - background_origin.x;
911 if background_origin.x == glyph_origin.x {
912 background_origin.x -= max_glyph_size.width.half();
913 };
914 window.paint_quad(fill(
915 Bounds {
916 origin: background_origin,
917 size: size(width, line_height),
918 },
919 background_color,
920 ));
921 }
922 }
923 }
924
925 let mut last_line_end_x = origin.x + layout.width;
926 if let Some(boundary) = wrap_boundaries.last() {
927 let run = &layout.runs[boundary.run_ix];
928 let glyph = &run.glyphs[boundary.glyph_ix];
929 last_line_end_x -= glyph.position.x;
930 }
931
932 if let Some((mut background_origin, background_color)) = current_background.take() {
933 if last_line_end_x == background_origin.x {
934 background_origin.x -= max_glyph_size.width.half()
935 };
936 window.paint_quad(fill(
937 Bounds {
938 origin: background_origin,
939 size: size(last_line_end_x - background_origin.x, line_height),
940 },
941 background_color,
942 ));
943 }
944
945 Ok(())
946 })
947}
948
949fn line_paint_bounds(
950 origin: Point<Pixels>,
951 layout: &LineLayout,
952 line_height: Pixels,
953 align: TextAlign,
954 align_width: Option<Pixels>,
955 wrap_boundaries: &[WrapBoundary],
956) -> Bounds<Pixels> {
957 let mut bounds = Bounds::new(
958 origin,
959 size(
960 layout.width,
961 line_height * (wrap_boundaries.len() as f32 + 1.),
962 ),
963 );
964 if align == TextAlign::Left || layout.len == 0 {
965 return bounds;
966 }
967
968 let align_width = align_width.unwrap_or(layout.width);
969 let mut row_start = Pixels::ZERO;
970 let row_ends = wrap_boundaries
971 .iter()
972 .map(|boundary| {
973 layout.runs[boundary.run_ix].glyphs[boundary.glyph_ix]
974 .position
975 .x
976 })
977 .chain([layout.width]);
978 for (row, row_end) in row_ends.enumerate() {
979 let width = row_end - row_start;
980 let offset = match align {
981 TextAlign::Left => Pixels::ZERO,
982 TextAlign::Center => (align_width - width) / 2.,
983 TextAlign::Right => align_width - width,
984 };
985 bounds = bounds.union(&Bounds::new(
986 point(origin.x + offset, origin.y + line_height * row as f32),
987 size(width, line_height),
988 ));
989 row_start = row_end;
990 }
991 bounds
992}
993
994/// The leftmost glyph position of each wrapped line. Right-to-left runs are laid out
995/// unwrapped in visual order, so a wrapped line's first glyph is not its left edge.
996fn segment_left_edges(layout: &LineLayout, wrap_boundaries: &[WrapBoundary]) -> Vec<Pixels> {
997 let mut edges = vec![px(0.); wrap_boundaries.len() + 1];
998 let mut started = vec![false; wrap_boundaries.len() + 1];
999 let mut segment = 0;
1000 for (run_ix, run) in layout.runs.iter().enumerate() {
1001 for (glyph_ix, glyph) in run.glyphs.iter().enumerate() {
1002 if wrap_boundaries.get(segment) == Some(&WrapBoundary { run_ix, glyph_ix }) {
1003 segment += 1;
1004 }
1005 if !started[segment] || glyph.position.x < edges[segment] {
1006 edges[segment] = glyph.position.x;
1007 started[segment] = true;
1008 }
1009 }
1010 }
1011 edges
1012}
1013
1014fn aligned_origin_x(
1015 origin: Point<Pixels>,
1016 align_width: Pixels,
1017 last_glyph_x: Pixels,
1018 align: &TextAlign,
1019 layout: &LineLayout,
1020 wrap_boundary: Option<&&WrapBoundary>,
1021) -> Pixels {
1022 let end_of_line = if let Some(WrapBoundary { run_ix, glyph_ix }) = wrap_boundary {
1023 layout.runs[*run_ix].glyphs[*glyph_ix].position.x
1024 } else {
1025 layout.width
1026 };
1027
1028 let line_width = end_of_line - last_glyph_x;
1029
1030 match align {
1031 TextAlign::Left => origin.x,
1032 TextAlign::Center => (origin.x * 2.0 + align_width - line_width) / 2.0,
1033 TextAlign::Right => origin.x + align_width - line_width,
1034 }
1035}
1036
1037#[cfg(test)]
1038mod tests {
1039 use super::*;
1040 use crate::{
1041 AppContext as _, Context, FontId, GlyphId, IntoElement, Render, ShapedGlyph, ShapedRun,
1042 Styled, TestAppContext, TextRun, Underline, canvas, font, hsla,
1043 };
1044 use std::rc::Rc;
1045
1046 /// Helper: build a ShapedLine from glyph descriptors without the platform text system.
1047 /// Each glyph is described as (byte_index, x_position).
1048 fn make_shaped_line(
1049 text: &str,
1050 glyphs: &[(usize, f32)],
1051 width: f32,
1052 decorations: &[DecorationRun],
1053 ) -> ShapedLine {
1054 let shaped_glyphs: Vec<ShapedGlyph> = glyphs
1055 .iter()
1056 .map(|&(index, x)| ShapedGlyph {
1057 id: GlyphId(0),
1058 position: point(px(x), px(0.0)),
1059 index,
1060 is_emoji: false,
1061 })
1062 .collect();
1063
1064 ShapedLine {
1065 layout: Arc::new(LineLayout {
1066 font_size: px(16.0),
1067 width: px(width),
1068 ascent: px(12.0),
1069 descent: px(4.0),
1070 runs: vec![ShapedRun {
1071 font_id: FontId(0),
1072 glyphs: shaped_glyphs,
1073 }],
1074 len: text.len(),
1075 }),
1076 text: SharedString::new(text),
1077 decoration_runs: SmallVec::from(decorations.to_vec()),
1078 }
1079 }
1080
1081 #[test]
1082 fn test_aligned_line_paint_bounds() {
1083 let line = make_shaped_line("abcd", &[(0, 0.), (1, 10.), (2, 20.), (3, 30.)], 40., &[]);
1084 let origin = point(px(10.), px(20.));
1085 let line_height = px(16.);
1086 for (wrapped, align_width, expected_edges) in [
1087 (false, None, [(10., 50.), (10., 50.), (10., 50.)]),
1088 (true, None, [(10., 50.), (10., 50.), (10., 50.)]),
1089 (false, Some(40.), [(10., 50.), (10., 50.), (10., 50.)]),
1090 (true, Some(40.), [(10., 50.), (10., 50.), (10., 50.)]),
1091 (false, Some(100.), [(10., 50.), (10., 80.), (10., 110.)]),
1092 (true, Some(100.), [(10., 50.), (10., 70.), (10., 110.)]),
1093 (false, Some(10.), [(10., 50.), (-5., 50.), (-20., 50.)]),
1094 (true, Some(10.), [(10., 50.), (5., 50.), (0., 50.)]),
1095 (false, Some(0.), [(10., 50.), (-10., 50.), (-30., 50.)]),
1096 (true, Some(0.), [(10., 50.), (0., 50.), (-10., 50.)]),
1097 ] {
1098 let boundaries = if wrapped {
1099 vec![WrapBoundary {
1100 run_ix: 0,
1101 glyph_ix: 2,
1102 }]
1103 } else {
1104 Vec::new()
1105 };
1106 for (align, (left, right)) in [TextAlign::Left, TextAlign::Center, TextAlign::Right]
1107 .into_iter()
1108 .zip(expected_edges)
1109 {
1110 assert_eq!(
1111 line_paint_bounds(
1112 origin,
1113 &line.layout,
1114 line_height,
1115 align,
1116 align_width.map(px),
1117 &boundaries,
1118 ),
1119 Bounds::new(
1120 point(px(left), origin.y),
1121 size(px(right - left), px(if wrapped { 32. } else { 16. })),
1122 ),
1123 "wrapped={wrapped}, align={align:?}, align_width={align_width:?}",
1124 );
1125 }
1126 }
1127 let empty = make_shaped_line("", &[], 0., &[]);
1128 for align in [TextAlign::Left, TextAlign::Center, TextAlign::Right] {
1129 assert_eq!(
1130 line_paint_bounds(
1131 origin,
1132 &empty.layout,
1133 line_height,
1134 align,
1135 Some(px(100.)),
1136 &[]
1137 ),
1138 Bounds::new(origin, size(Pixels::ZERO, line_height)),
1139 );
1140 }
1141 }
1142
1143 #[gpui::test]
1144 fn test_underline_handler_matches_default_paint(cx: &mut TestAppContext) {
1145 test_underline_handler_at_scales(cx, |window, cx| {
1146 let first_style = UnderlineStyle {
1147 thickness: px(1.),
1148 color: Some(hsla(0., 1., 0.5, 1.)),
1149 wavy: true,
1150 };
1151 let last_style = UnderlineStyle {
1152 color: Some(hsla(0.5, 1., 0.5, 1.)),
1153 wavy: false,
1154 ..first_style
1155 };
1156 let fallback_style = UnderlineStyle {
1157 color: Some(black()),
1158 ..first_style
1159 };
1160 let decoration = DecorationRun {
1161 len: 1,
1162 color: black(),
1163 background_color: None,
1164 underline: Some(first_style),
1165 strikethrough: None,
1166 };
1167 let line = underline_test_line(
1168 "aébcde",
1169 &[
1170 decoration.clone(),
1171 DecorationRun {
1172 len: 2,
1173 ..decoration.clone()
1174 },
1175 DecorationRun {
1176 underline: None,
1177 ..decoration.clone()
1178 },
1179 DecorationRun {
1180 underline: Some(UnderlineStyle {
1181 color: None,
1182 ..first_style
1183 }),
1184 ..decoration.clone()
1185 },
1186 DecorationRun {
1187 underline: Some(last_style),
1188 ..decoration.clone()
1189 },
1190 DecorationRun {
1191 underline: Some(last_style),
1192 ..decoration
1193 },
1194 ],
1195 false,
1196 window,
1197 );
1198 assert_eq!(line.width(), px(48.));
1199 for origin_x in [-3.25, 0., 4.25] {
1200 for (align, align_width, offset) in [
1201 (TextAlign::Left, None, 0.),
1202 (TextAlign::Center, None, 0.),
1203 (TextAlign::Right, None, 0.),
1204 (TextAlign::Left, Some(px(96.)), 0.),
1205 (TextAlign::Center, Some(px(96.)), 24.),
1206 (TextAlign::Right, Some(px(96.)), 48.),
1207 ] {
1208 let origin = point(px(origin_x), px(12.25));
1209 let line_height = px(20.);
1210 window.next_frame.scene.clear();
1211 line.paint(origin, line_height, align, align_width, window, cx)
1212 .unwrap();
1213 let original = window.next_frame.scene.underlines.clone();
1214 window.next_frame.scene.clear();
1215 line.layout
1216 .paint(
1217 origin,
1218 line_height,
1219 align,
1220 align_width,
1221 &line.decoration_runs,
1222 window,
1223 cx,
1224 )
1225 .unwrap();
1226 assert_underline_primitives_eq(&window.next_frame.scene.underlines, &original);
1227
1228 window.next_frame.scene.clear();
1229 let mut strokes = Vec::new();
1230 line.paint_with_underline_handler(
1231 origin,
1232 line_height,
1233 align,
1234 align_width,
1235 window,
1236 cx,
1237 |range, origin, width, style, window| {
1238 strokes.push((range, origin, width, *style));
1239 window.paint_underline(origin, width, style);
1240 },
1241 )
1242 .unwrap();
1243 let start = px(origin_x + offset);
1244 let y = origin.y + underline_y_offset(line_height, line.ascent, line.descent);
1245 assert_eq!(
1246 strokes,
1247 [
1248 (0..3, point(start, y), px(16.), first_style),
1249 (4..5, point(start + px(24.), y), px(8.), fallback_style),
1250 (5..7, point(start + px(32.), y), px(16.), last_style),
1251 ]
1252 );
1253 assert_underline_primitives_eq(&window.next_frame.scene.underlines, &original);
1254
1255 window.next_frame.scene.clear();
1256 let mut captured = Vec::new();
1257 line.paint_with_underline_handler(
1258 origin,
1259 line_height,
1260 align,
1261 align_width,
1262 window,
1263 cx,
1264 |range, origin, width, style, _| {
1265 captured.push((range, origin, width, *style))
1266 },
1267 )
1268 .unwrap();
1269 assert_eq!(captured, strokes);
1270 assert_eq!(window.next_frame.scene.underlines.len(), 0);
1271 }
1272 }
1273 for text in ["", "abc"] {
1274 let line = underline_test_line(text, &[], false, window);
1275 let mut calls = 0;
1276 line.paint_with_underline_handler(
1277 point(px(4.), px(10.)),
1278 px(20.),
1279 TextAlign::Left,
1280 None,
1281 window,
1282 cx,
1283 |_, _, _, _, _| calls += 1,
1284 )
1285 .unwrap();
1286 assert_eq!(calls, 0);
1287 }
1288 });
1289 }
1290
1291 #[gpui::test]
1292 fn test_underline_handler_reports_zero_advance_geometry(cx: &mut TestAppContext) {
1293 test_underline_handler_at_scales(cx, |window, cx| {
1294 let first_style = UnderlineStyle {
1295 thickness: px(1.),
1296 color: Some(black()),
1297 wavy: true,
1298 };
1299 let last_style = UnderlineStyle {
1300 wavy: false,
1301 ..first_style
1302 };
1303 let decoration = DecorationRun {
1304 len: 1,
1305 color: black(),
1306 background_color: None,
1307 underline: Some(first_style),
1308 strikethrough: None,
1309 };
1310 let line = underline_test_line(
1311 "ab",
1312 &[
1313 decoration.clone(),
1314 DecorationRun {
1315 underline: Some(last_style),
1316 ..decoration
1317 },
1318 ],
1319 true,
1320 window,
1321 );
1322 let half_width = cx
1323 .text_system()
1324 .bounding_box(line.runs[0].font_id, line.font_size)
1325 .size
1326 .width
1327 / 2.;
1328 let origin = point(px(40.25), px(10.25));
1329 let line_height = px(20.);
1330 let y = origin.y + underline_y_offset(line_height, line.ascent, line.descent);
1331 for (align, offset) in [
1332 (TextAlign::Left, 0.),
1333 (TextAlign::Center, 16.),
1334 (TextAlign::Right, 32.),
1335 ] {
1336 window.next_frame.scene.clear();
1337 line.paint(origin, line_height, align, Some(px(32.)), window, cx)
1338 .unwrap();
1339 let original = window.next_frame.scene.underlines.clone();
1340 window.next_frame.scene.clear();
1341 let mut strokes = Vec::new();
1342 line.paint_with_underline_handler(
1343 origin,
1344 line_height,
1345 align,
1346 Some(px(32.)),
1347 window,
1348 cx,
1349 |range, origin, width, style, window| {
1350 strokes.push((range, origin, width, *style));
1351 window.paint_underline(origin, width, style);
1352 },
1353 )
1354 .unwrap();
1355 let end = origin.x + px(offset);
1356 let start = point(end - half_width, y);
1357 let width = end - start.x;
1358 assert_eq!(
1359 strokes,
1360 [
1361 (0..1, start, width, first_style),
1362 (1..2, start, width, last_style),
1363 ]
1364 );
1365 assert_underline_primitives_eq(&window.next_frame.scene.underlines, &original);
1366 }
1367 });
1368 }
1369
1370 #[gpui::test]
1371 fn test_underline_handler_matches_wrapped_paint(cx: &mut TestAppContext) {
1372 test_underline_handler_at_scales(cx, |window, cx| {
1373 let style = UnderlineStyle {
1374 thickness: px(1.),
1375 color: Some(black()),
1376 wavy: true,
1377 };
1378 for zero_advance in [false, true] {
1379 let line = underline_test_line(
1380 "abcd",
1381 &[DecorationRun {
1382 len: 4,
1383 color: black(),
1384 background_color: None,
1385 underline: Some(style),
1386 strikethrough: None,
1387 }],
1388 zero_advance,
1389 window,
1390 );
1391 let half_width = cx
1392 .text_system()
1393 .bounding_box(line.runs[0].font_id, line.font_size)
1394 .size
1395 .width
1396 / 2.;
1397 let origin = point(px(40.25), px(10.25));
1398 let line_height = px(20.);
1399 let y = origin.y + underline_y_offset(line_height, line.ascent, line.descent);
1400 let wrapped = WrappedLine {
1401 layout: Arc::new(WrappedLineLayout {
1402 unwrapped_layout: line.layout,
1403 wrap_boundaries: SmallVec::from_buf([WrapBoundary {
1404 run_ix: 0,
1405 glyph_ix: 2,
1406 }]),
1407 wrap_width: Some(px(16.)),
1408 }),
1409 text: line.text,
1410 decoration_runs: line.decoration_runs.into_vec(),
1411 };
1412 window.next_frame.scene.clear();
1413 wrapped
1414 .paint(origin, line_height, TextAlign::Left, None, window, cx)
1415 .unwrap();
1416 let original = window.next_frame.scene.underlines.clone();
1417 window.next_frame.scene.clear();
1418 let mut strokes = Vec::new();
1419 paint_line(
1420 origin,
1421 &wrapped.unwrapped_layout,
1422 line_height,
1423 TextAlign::Left,
1424 Some(px(16.)),
1425 &wrapped.decoration_runs,
1426 &wrapped.wrap_boundaries,
1427 window,
1428 cx,
1429 &mut |range, origin, width, style, window| {
1430 strokes.push((range, origin, width, *style));
1431 window.paint_underline(origin, width, style);
1432 },
1433 )
1434 .unwrap();
1435 let (start, width) = if zero_advance {
1436 let start = origin.x - half_width;
1437 (start, origin.x - start)
1438 } else {
1439 (origin.x, px(16.))
1440 };
1441 assert_eq!(
1442 strokes,
1443 [
1444 (0..4, point(start, y), width, style),
1445 (0..4, point(start, y + line_height), width, style),
1446 ]
1447 );
1448 assert_underline_primitives_eq(&window.next_frame.scene.underlines, &original);
1449 }
1450 });
1451 }
1452
1453 #[test]
1454 fn test_split_at_invariants() {
1455 // Split "abcdef" at every possible byte index and verify structural invariants.
1456 let line = make_shaped_line(
1457 "abcdef",
1458 &[
1459 (0, 0.0),
1460 (1, 10.0),
1461 (2, 20.0),
1462 (3, 30.0),
1463 (4, 40.0),
1464 (5, 50.0),
1465 ],
1466 60.0,
1467 &[],
1468 );
1469
1470 for i in 0..=6 {
1471 let (left, right) = line.split_at(i);
1472
1473 assert_eq!(
1474 left.width() + right.width(),
1475 line.width(),
1476 "widths must sum at split={i}"
1477 );
1478 assert_eq!(
1479 left.len() + right.len(),
1480 line.len(),
1481 "lengths must sum at split={i}"
1482 );
1483 assert_eq!(
1484 format!("{}{}", left.text.as_ref(), right.text.as_ref()),
1485 "abcdef",
1486 "text must concatenate at split={i}"
1487 );
1488 assert_eq!(left.font_size, line.font_size, "font_size at split={i}");
1489 assert_eq!(right.ascent, line.ascent, "ascent at split={i}");
1490 assert_eq!(right.descent, line.descent, "descent at split={i}");
1491 }
1492
1493 // Edge: split at 0 produces no left runs, full content on right
1494 let (left, right) = line.split_at(0);
1495 assert_eq!(left.runs.len(), 0);
1496 assert_eq!(right.runs[0].glyphs.len(), 6);
1497
1498 // Edge: split at end produces full content on left, no right runs
1499 let (left, right) = line.split_at(6);
1500 assert_eq!(left.runs[0].glyphs.len(), 6);
1501 assert_eq!(right.runs.len(), 0);
1502 }
1503
1504 #[test]
1505 fn test_split_at_glyph_rebasing() {
1506 // Two font runs (simulating a font fallback boundary at byte 3):
1507 // run A (FontId 0): glyphs at bytes 0,1,2 positions 0,10,20
1508 // run B (FontId 1): glyphs at bytes 3,4,5 positions 30,40,50
1509 // Successive splits simulate the incremental splitting done during wrap.
1510 let line = ShapedLine {
1511 layout: Arc::new(LineLayout {
1512 font_size: px(16.0),
1513 width: px(60.0),
1514 ascent: px(12.0),
1515 descent: px(4.0),
1516 runs: vec![
1517 ShapedRun {
1518 font_id: FontId(0),
1519 glyphs: vec![
1520 ShapedGlyph {
1521 id: GlyphId(0),
1522 position: point(px(0.0), px(0.0)),
1523 index: 0,
1524 is_emoji: false,
1525 },
1526 ShapedGlyph {
1527 id: GlyphId(0),
1528 position: point(px(10.0), px(0.0)),
1529 index: 1,
1530 is_emoji: false,
1531 },
1532 ShapedGlyph {
1533 id: GlyphId(0),
1534 position: point(px(20.0), px(0.0)),
1535 index: 2,
1536 is_emoji: false,
1537 },
1538 ],
1539 },
1540 ShapedRun {
1541 font_id: FontId(1),
1542 glyphs: vec![
1543 ShapedGlyph {
1544 id: GlyphId(0),
1545 position: point(px(30.0), px(0.0)),
1546 index: 3,
1547 is_emoji: false,
1548 },
1549 ShapedGlyph {
1550 id: GlyphId(0),
1551 position: point(px(40.0), px(0.0)),
1552 index: 4,
1553 is_emoji: false,
1554 },
1555 ShapedGlyph {
1556 id: GlyphId(0),
1557 position: point(px(50.0), px(0.0)),
1558 index: 5,
1559 is_emoji: false,
1560 },
1561 ],
1562 },
1563 ],
1564 len: 6,
1565 }),
1566 text: "abcdef".into(),
1567 decoration_runs: SmallVec::new(),
1568 };
1569
1570 // First split at byte 2 — mid-run in run A
1571 let (first, remainder) = line.split_at(2);
1572 assert_eq!(first.text.as_ref(), "ab");
1573 assert_eq!(first.runs.len(), 1);
1574 assert_eq!(first.runs[0].font_id, FontId(0));
1575
1576 // Remainder "cdef" should have two runs: tail of A (1 glyph) + all of B (3 glyphs)
1577 assert_eq!(remainder.text.as_ref(), "cdef");
1578 assert_eq!(remainder.runs.len(), 2);
1579 assert_eq!(remainder.runs[0].font_id, FontId(0));
1580 assert_eq!(remainder.runs[0].glyphs.len(), 1);
1581 assert_eq!(remainder.runs[0].glyphs[0].index, 0);
1582 assert_eq!(remainder.runs[0].glyphs[0].position.x, px(0.0));
1583 assert_eq!(remainder.runs[1].font_id, FontId(1));
1584 assert_eq!(remainder.runs[1].glyphs[0].index, 1);
1585 assert_eq!(remainder.runs[1].glyphs[0].position.x, px(10.0));
1586
1587 // Second split at byte 2 within remainder — crosses the run boundary
1588 let (second, final_part) = remainder.split_at(2);
1589 assert_eq!(second.text.as_ref(), "cd");
1590 assert_eq!(final_part.text.as_ref(), "ef");
1591 assert_eq!(final_part.runs[0].glyphs[0].index, 0);
1592 assert_eq!(final_part.runs[0].glyphs[0].position.x, px(0.0));
1593
1594 // Widths must sum across all three pieces
1595 assert_eq!(
1596 first.width() + second.width() + final_part.width(),
1597 line.width()
1598 );
1599 }
1600
1601 #[test]
1602 fn test_split_at_decorations() {
1603 // Three decoration runs: red [0..2), green [2..5), blue [5..6).
1604 // Split at byte 3 — red goes entirely left, green straddles, blue goes entirely right.
1605 let red = Hsla {
1606 h: 0.0,
1607 s: 1.0,
1608 l: 0.5,
1609 a: 1.0,
1610 };
1611 let green = Hsla {
1612 h: 0.3,
1613 s: 1.0,
1614 l: 0.5,
1615 a: 1.0,
1616 };
1617 let blue = Hsla {
1618 h: 0.6,
1619 s: 1.0,
1620 l: 0.5,
1621 a: 1.0,
1622 };
1623
1624 let line = make_shaped_line(
1625 "abcdef",
1626 &[
1627 (0, 0.0),
1628 (1, 10.0),
1629 (2, 20.0),
1630 (3, 30.0),
1631 (4, 40.0),
1632 (5, 50.0),
1633 ],
1634 60.0,
1635 &[
1636 DecorationRun {
1637 len: 2,
1638 color: red,
1639 background_color: None,
1640 underline: None,
1641 strikethrough: None,
1642 },
1643 DecorationRun {
1644 len: 3,
1645 color: green,
1646 background_color: None,
1647 underline: None,
1648 strikethrough: None,
1649 },
1650 DecorationRun {
1651 len: 1,
1652 color: blue,
1653 background_color: None,
1654 underline: None,
1655 strikethrough: None,
1656 },
1657 ],
1658 );
1659
1660 let (left, right) = line.split_at(3);
1661
1662 // Left: red(2) + green(1) — green straddled, left portion has len 1
1663 assert_eq!(left.decoration_runs.len(), 2);
1664 assert_eq!(left.decoration_runs[0].len, 2);
1665 assert_eq!(left.decoration_runs[0].color, red);
1666 assert_eq!(left.decoration_runs[1].len, 1);
1667 assert_eq!(left.decoration_runs[1].color, green);
1668
1669 // Right: green(2) + blue(1) — green straddled, right portion has len 2
1670 assert_eq!(right.decoration_runs.len(), 2);
1671 assert_eq!(right.decoration_runs[0].len, 2);
1672 assert_eq!(right.decoration_runs[0].color, green);
1673 assert_eq!(right.decoration_runs[1].len, 1);
1674 assert_eq!(right.decoration_runs[1].color, blue);
1675 }
1676
1677 struct UnderlineHandlerTestView(Rc<dyn Fn(&mut Window, &mut App)>);
1678
1679 impl Render for UnderlineHandlerTestView {
1680 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1681 let paint = self.0.clone();
1682 canvas(
1683 |_, _, _| {},
1684 move |_, _, window, cx| {
1685 window.with_element_opacity(Some(0.5), |window| paint(window, cx));
1686 },
1687 )
1688 .size_full()
1689 }
1690 }
1691
1692 fn test_underline_handler_at_scales(
1693 cx: &mut TestAppContext,
1694 paint: impl Fn(&mut Window, &mut App) + 'static,
1695 ) {
1696 let window = cx.add_window(move |_, _| UnderlineHandlerTestView(Rc::new(paint)));
1697 for scale in [1., 1.25, 1.5, 2., 3.] {
1698 cx.simulate_window_scale_factor_change(window.into(), scale);
1699 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
1700 .unwrap();
1701 }
1702 }
1703
1704 fn underline_test_line(
1705 text: &str,
1706 decorations: &[DecorationRun],
1707 zero_advance: bool,
1708 window: &Window,
1709 ) -> ShapedLine {
1710 let mut line = window.text_system().shape_line(
1711 SharedString::new(text),
1712 px(16.),
1713 &[TextRun {
1714 len: text.len(),
1715 font: font(".ZedMono"),
1716 color: black(),
1717 ..TextRun::default()
1718 }],
1719 None,
1720 );
1721 line.decoration_runs = SmallVec::from(decorations.to_vec());
1722 let layout = &line.layout;
1723 let mut runs = layout.runs.clone();
1724 let advance = if zero_advance { px(0.) } else { px(8.) };
1725 let mut width = px(0.);
1726 for glyph in runs.iter_mut().flat_map(|run| &mut run.glyphs) {
1727 glyph.position.x = width;
1728 width += advance;
1729 }
1730 line.layout = Arc::new(LineLayout {
1731 font_size: layout.font_size,
1732 width,
1733 ascent: layout.ascent,
1734 descent: layout.descent,
1735 runs,
1736 len: layout.len,
1737 });
1738 line
1739 }
1740
1741 fn assert_underline_primitives_eq(actual: &[Underline], expected: &[Underline]) {
1742 assert_eq!(actual.len(), expected.len());
1743 for (actual, expected) in actual.iter().zip(expected) {
1744 assert_eq!(actual.bounds, expected.bounds);
1745 assert_eq!(actual.content_mask, expected.content_mask);
1746 assert_eq!(actual.color, expected.color);
1747 assert_eq!(actual.thickness, expected.thickness);
1748 assert_eq!(actual.wavy, expected.wavy);
1749 assert_eq!(actual.order, expected.order);
1750 assert_eq!(actual.pad, expected.pad);
1751 }
1752 }
1753
1754 #[test]
1755 fn test_cursor_preserves_shaping_metadata_across_runs() {
1756 let line = ShapedLine {
1757 layout: Arc::new(LineLayout {
1758 font_size: px(16.0),
1759 width: px(50.0),
1760 ascent: px(12.0),
1761 descent: px(4.0),
1762 runs: vec![
1763 ShapedRun {
1764 font_id: FontId(3),
1765 glyphs: vec![
1766 ShapedGlyph {
1767 id: GlyphId(11),
1768 position: point(px(0.0), px(1.0)),
1769 index: 0,
1770 is_emoji: true,
1771 },
1772 ShapedGlyph {
1773 id: GlyphId(12),
1774 position: point(px(17.0), px(1.0)),
1775 index: 1,
1776 is_emoji: false,
1777 },
1778 ShapedGlyph {
1779 id: GlyphId(13),
1780 position: point(px(19.0), px(-1.0)),
1781 index: 1,
1782 is_emoji: false,
1783 },
1784 ],
1785 },
1786 ShapedRun {
1787 font_id: FontId(8),
1788 glyphs: vec![
1789 ShapedGlyph {
1790 id: GlyphId(21),
1791 position: point(px(25.0), px(1.0)),
1792 index: 5,
1793 is_emoji: true,
1794 },
1795 ShapedGlyph {
1796 id: GlyphId(22),
1797 position: point(px(41.0), px(1.0)),
1798 index: 7,
1799 is_emoji: false,
1800 },
1801 ],
1802 },
1803 ],
1804 len: 10,
1805 }),
1806 text: "a😀bcdef".into(),
1807 decoration_runs: SmallVec::new(),
1808 };
1809 let mut cursor = line.cursor();
1810 let first = cursor.take_until(5);
1811 assert_eq!(first.text.as_ref(), "a😀");
1812 assert_eq!(first.runs[0].font_id, FontId(3));
1813 assert_eq!(first.runs[0].glyphs[0].id, GlyphId(11));
1814 assert!(first.runs[0].glyphs[0].is_emoji);
1815 assert_eq!(first.runs[0].glyphs[1].index, 1);
1816 assert_eq!(first.runs[0].glyphs[1].position, point(px(17.0), px(1.0)));
1817 assert_eq!(first.runs[0].glyphs.len(), 3);
1818 assert_eq!(first.runs[0].glyphs[2].index, 1);
1819 assert_eq!(first.runs[0].glyphs[2].position, point(px(19.0), px(-1.0)));
1820 assert_eq!(cursor.x_offset(), px(25.0));
1821
1822 let second = cursor.take_until(7);
1823 assert_eq!(second.text.as_ref(), "bc");
1824 assert_eq!(second.runs[0].font_id, FontId(8));
1825 assert_eq!(second.runs[0].glyphs[0].id, GlyphId(21));
1826 assert_eq!(second.runs[0].glyphs[0].index, 0);
1827 assert_eq!(second.runs[0].glyphs[0].position, point(px(0.0), px(1.0)));
1828 assert_eq!(cursor.x_offset(), px(41.0));
1829
1830 let final_part = cursor.take_until(10);
1831 assert_eq!(final_part.text.as_ref(), "def");
1832 assert_eq!(final_part.runs[0].font_id, FontId(8));
1833 assert_eq!(final_part.runs[0].glyphs[0].id, GlyphId(22));
1834 assert_eq!(final_part.runs[0].glyphs[0].index, 0);
1835 assert_eq!(
1836 final_part.runs[0].glyphs[0].position,
1837 point(px(0.0), px(1.0))
1838 );
1839 }
1840
1841 #[test]
1842 fn test_cursor_preserves_existing_visual_order_splitting() {
1843 let line = make_shaped_line("abc", &[(0, 0.0), (2, 10.0), (1, 20.0)], 30.0, &[]);
1844 let mut cursor = line.cursor();
1845 let mut remainder = line.clone();
1846 let mut previous_boundary = 0;
1847 for boundary in [0, 1, 2, 3] {
1848 let (expected, rest) = remainder.split_at(boundary - previous_boundary);
1849 let actual = cursor.take_until(boundary);
1850 assert_eq!(actual.text, expected.text);
1851 assert_eq!(actual.width(), expected.width());
1852 assert_eq!(actual.runs.len(), expected.runs.len());
1853 for (actual, expected) in actual.runs.iter().zip(&expected.runs) {
1854 assert_eq!(actual.font_id, expected.font_id);
1855 assert_eq!(actual.glyphs.len(), expected.glyphs.len());
1856 for (actual, expected) in actual.glyphs.iter().zip(&expected.glyphs) {
1857 assert_eq!(actual.id, expected.id);
1858 assert_eq!(actual.index, expected.index);
1859 assert_eq!(actual.position, expected.position);
1860 }
1861 }
1862 assert_eq!(cursor.x_offset(), line.x_for_index(boundary));
1863 remainder = rest;
1864 previous_boundary = boundary;
1865 }
1866 }
1867
1868 #[test]
1869 fn test_cursor_partitions_one_decoration_across_three_chunks() {
1870 let line = make_shaped_line(
1871 "abcdef",
1872 &[
1873 (0, 0.0),
1874 (1, 10.0),
1875 (2, 20.0),
1876 (3, 30.0),
1877 (4, 40.0),
1878 (5, 50.0),
1879 ],
1880 60.0,
1881 &[DecorationRun {
1882 len: 6,
1883 color: Hsla {
1884 h: 0.2,
1885 s: 0.4,
1886 l: 0.6,
1887 a: 1.0,
1888 },
1889 background_color: None,
1890 underline: None,
1891 strikethrough: None,
1892 }],
1893 );
1894 let mut cursor = line.cursor();
1895 assert_eq!(cursor.take_until(2).decoration_runs[0].len, 2);
1896 assert_eq!(cursor.take_until(4).decoration_runs[0].len, 2);
1897 assert_eq!(cursor.take_until(6).decoration_runs[0].len, 2);
1898 }
1899
1900 #[test]
1901 fn test_cursor_matches_successive_splits_at_ordered_boundaries() {
1902 let decorations: Vec<_> = [2, 0, 3, 1]
1903 .into_iter()
1904 .map(|len| DecorationRun {
1905 len,
1906 color: Hsla {
1907 h: len as f32 / 10.0,
1908 s: 0.5,
1909 l: 0.5,
1910 a: 1.0,
1911 },
1912 background_color: Some(black()),
1913 underline: None,
1914 strikethrough: None,
1915 })
1916 .collect();
1917 let line = make_shaped_line(
1918 "abcdef",
1919 &[(0, 5.0), (0, 5.0), (2, 15.0), (4, 25.0), (5, 35.0)],
1920 45.0,
1921 &decorations,
1922 );
1923 for first in 0..=line.len() {
1924 for second in first..=line.len() {
1925 let mut cursor = line.cursor();
1926 let mut remainder = line.clone();
1927 let mut previous_boundary = 0;
1928 let mut total_width = px(0.0);
1929 let mut text = String::new();
1930 for boundary in [first, second, line.len(), line.len()] {
1931 let (expected, rest) = remainder.split_at(boundary - previous_boundary);
1932 let actual = cursor.take_until(boundary);
1933 assert_eq!(actual.text, expected.text);
1934 assert_eq!(actual.len(), expected.len());
1935 assert_eq!(actual.width(), expected.width());
1936 assert_eq!(actual.runs.len(), expected.runs.len());
1937 for (actual, expected) in actual.runs.iter().zip(&expected.runs) {
1938 assert_eq!(actual.font_id, expected.font_id);
1939 assert_eq!(actual.glyphs.len(), expected.glyphs.len());
1940 for (actual, expected) in actual.glyphs.iter().zip(&expected.glyphs) {
1941 assert_eq!(actual.id, expected.id);
1942 assert_eq!(actual.index, expected.index);
1943 assert_eq!(actual.position, expected.position);
1944 }
1945 }
1946 assert_eq!(actual.decoration_runs.len(), expected.decoration_runs.len());
1947 for (actual, expected) in
1948 actual.decoration_runs.iter().zip(&expected.decoration_runs)
1949 {
1950 assert_eq!(actual.len, expected.len);
1951 assert_eq!(actual.color, expected.color);
1952 assert_eq!(actual.background_color, expected.background_color);
1953 }
1954 total_width += actual.width();
1955 text.push_str(&actual.text);
1956 remainder = rest;
1957 previous_boundary = boundary;
1958 }
1959 assert_eq!(total_width, line.width());
1960 assert_eq!(text, line.text.as_ref());
1961 }
1962 }
1963 }
1964
1965 #[test]
1966 fn test_cursor_empty_chunks_and_repeated_boundaries() {
1967 let line = make_shaped_line("ab", &[(0, 5.0), (1, 15.0)], 20.0, &[]);
1968 let mut cursor = line.cursor();
1969 assert_eq!(cursor.take_until(0).text.as_ref(), "");
1970 assert_eq!(cursor.take_until(0).text.as_ref(), "");
1971 assert_eq!(cursor.take_until(1).text.as_ref(), "a");
1972 assert_eq!(cursor.take_until(2).text.as_ref(), "b");
1973 assert_eq!(cursor.take_until(2).text.as_ref(), "");
1974 let empty = make_shaped_line("", &[], 0.0, &[]);
1975 let piece = empty.cursor().take_until(0);
1976 assert!(piece.text.is_empty());
1977 assert!(piece.runs.is_empty());
1978 assert_eq!(piece.width(), px(0.0));
1979 }
1980
1981 #[test]
1982 fn test_cursor_rejects_invalid_boundaries() {
1983 let line = make_shaped_line("é", &[(0, 0.0)], 10.0, &[]);
1984 let mut cursor = line.cursor();
1985 assert!(
1986 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1987 cursor.take_until(1);
1988 }))
1989 .is_err()
1990 );
1991 let mut cursor = line.cursor();
1992 cursor.take_until(2);
1993 assert!(
1994 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1995 cursor.take_until(0);
1996 }))
1997 .is_err()
1998 );
1999 let mut cursor = line.cursor();
2000 assert!(
2001 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2002 cursor.take_until(3);
2003 }))
2004 .is_err()
2005 );
2006 }
2007}