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