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