1use std::{
2 any::Any,
3 fmt,
4 hash::{Hash, Hasher},
5 ops::Range,
6 sync::Arc,
7};
8
9use rustc_hash::FxHashMap;
10
11use crate::{
12 geometry::{Bounds, Point, Points, Size, point, px, size},
13 ops::{EventMask, NodeId},
14 style::{
15 Color, DecorationStyle, EllipsizeMode, FontFamily, FontVariant, TextAlign, TextDecoration,
16 TextShadow, TextStyle, TextTransform, VerticalAlign,
17 },
18};
19
20#[derive(Debug, Clone, Copy, PartialEq)]
22pub struct ResolvedTextStyle {
23 pub color: Color,
25 pub font_size: Points,
27 pub font_weight: u16,
29 pub line_height: Points,
31 pub font_family: Option<FontFamily>,
33 pub italic: bool,
35 pub letter_spacing: Points,
37 pub line_height_multiple: f32,
40 pub decoration: TextDecoration,
42 pub decoration_color: Option<Color>,
44 pub decoration_style: DecorationStyle,
46 pub decoration_thickness: Option<Points>,
48 pub underline_offset: Option<Points>,
50 pub transform: TextTransform,
52 pub font_variant: FontVariant,
54 pub background: Option<TextBackground>,
56 pub hidden: bool,
62}
63
64#[derive(Debug, Clone, Copy, PartialEq)]
70pub struct TextBackground {
71 pub color: Color,
73 pub radius: Points,
75 pub node: NodeId,
78 pub top: Points,
81 pub bottom: Points,
83}
84
85#[derive(Debug, Clone, Copy, PartialEq)]
88pub struct LinePiece {
89 pub x: Points,
91 pub width: Points,
93 pub background: Option<TextBackground>,
96 pub ascent: Points,
98 pub descent: Points,
100}
101
102#[derive(Debug, Clone, Copy, PartialEq)]
105pub struct BackgroundBox {
106 pub x: Points,
108 pub width: Points,
110 pub ascent: Points,
112 pub descent: Points,
114 pub background: TextBackground,
116}
117
118impl BackgroundBox {
119 pub fn join(
124 pieces: impl IntoIterator<Item = LinePiece>,
125 (left, right): (Points, Points),
126 mut f: impl FnMut(BackgroundBox),
127 ) {
128 let mut current: Option<BackgroundBox> = None;
129 let mut emit = |b: Option<BackgroundBox>| {
130 if let Some(mut b) = b {
131 b.ascent += b.background.top;
132 b.descent += b.background.bottom;
133 let x1 = (b.x + b.width).min(right);
134 b.x = b.x.max(left);
135 b.width = x1 - b.x;
136 if b.width > Points::ZERO && b.ascent + b.descent > Points::ZERO {
137 f(b);
138 }
139 }
140 };
141 for p in pieces {
142 let Some(background) = p.background else {
143 emit(current.take());
144 continue;
145 };
146 match &mut current {
147 Some(b) if b.background == background => {
148 b.width = (p.x + p.width).max(b.x + b.width) - b.x;
149 b.ascent = b.ascent.max(p.ascent);
150 b.descent = b.descent.max(p.descent);
151 }
152 _ => {
153 emit(current.take());
154 current = Some(BackgroundBox {
155 x: p.x,
156 width: p.width,
157 ascent: p.ascent,
158 descent: p.descent,
159 background,
160 });
161 }
162 }
163 }
164 emit(current);
165 }
166
167 pub fn radius(&self) -> Points {
170 self.background
171 .radius
172 .min(self.width / 2.0)
173 .min((self.ascent + self.descent) / 2.0)
174 .max(Points::ZERO)
175 }
176}
177
178impl Default for ResolvedTextStyle {
179 fn default() -> Self {
181 Self {
182 color: Color::BLACK,
183 font_size: px(14.0),
184 font_weight: 400,
185 line_height: Points::ZERO,
186 font_family: None,
187 italic: false,
188 letter_spacing: Points::ZERO,
189 decoration: TextDecoration {
190 underline: false,
191 line_through: false,
192 },
193 decoration_color: None,
194 decoration_style: DecorationStyle::Solid,
195 decoration_thickness: None,
196 underline_offset: None,
197 line_height_multiple: 0.0,
198 transform: TextTransform::None,
199 font_variant: FontVariant(0),
200 background: None,
201 hidden: false,
202 }
203 }
204}
205
206impl ResolvedTextStyle {
207 #[inline]
209 pub(crate) fn inherit(self, style: &TextStyle) -> Self {
210 let font_size = match style.font_size_em {
212 Some(em) => px(em * self.font_size.0),
213 None => style.font_size.unwrap_or(self.font_size),
214 };
215 let (line_height, line_height_multiple) = match (
218 style.line_height_multiple,
219 style.line_height,
220 style.line_height_em,
221 ) {
222 (_, _, Some(em)) => (em * font_size, 0.0),
223 (Some(m), _, _) => (m * font_size, m),
224 (None, Some(points), _) => (points, 0.0),
225 (None, None, _) if self.line_height_multiple > 0.0 => (
226 self.line_height_multiple * font_size,
227 self.line_height_multiple,
228 ),
229 (None, None, _) => (self.line_height, 0.0),
230 };
231 Self {
232 color: style.color.unwrap_or(self.color),
233 font_size,
234 font_weight: style.font_weight.unwrap_or(self.font_weight),
235 line_height,
236 line_height_multiple,
237 font_family: style.font_family.or(self.font_family),
238 italic: style.italic.unwrap_or(self.italic),
239 letter_spacing: match style.letter_spacing_em {
241 Some(em) => em * font_size,
242 None => style.letter_spacing.unwrap_or(self.letter_spacing),
243 },
244 decoration: style.decoration.unwrap_or(self.decoration),
245 decoration_color: style.decoration_color.or(self.decoration_color),
246 decoration_style: style.decoration_style.unwrap_or(self.decoration_style),
247 decoration_thickness: style.decoration_thickness.or(self.decoration_thickness),
248 underline_offset: style.underline_offset.or(self.underline_offset),
249 transform: style.transform.unwrap_or(self.transform),
250 font_variant: style.font_variant.unwrap_or(self.font_variant),
251 background: self.background,
252 hidden: self.hidden,
253 }
254 }
255
256 #[must_use]
259 pub(crate) fn hide(self) -> Self {
260 Self {
261 color: Color::TRANSPARENT,
262 decoration_color: None,
263 background: None,
264 hidden: true,
265 ..self
266 }
267 }
268
269 #[doc(hidden)]
273 #[inline]
274 pub fn approx_line_height(&self) -> Points {
275 let font = self.font_size.max(px(1.0));
276 if self.line_height > Points::ZERO {
277 self.line_height
278 } else if self.line_height_multiple > 0.0 {
279 font * self.line_height_multiple
280 } else {
281 font * 1.2
282 }
283 }
284
285 #[inline]
288 fn layout_eq(&self, other: &Self) -> bool {
289 self.font_size == other.font_size
290 && self.font_weight == other.font_weight
291 && self.line_height == other.line_height
292 && self.font_family == other.font_family
293 && self.italic == other.italic
294 && self.letter_spacing == other.letter_spacing
295 && self.font_variant == other.font_variant
296 }
297}
298
299fn spans_same_but_colors(a: &[TextSpan], b: &[TextSpan]) -> bool {
302 let colorless = |s: &ResolvedTextStyle| ResolvedTextStyle {
303 color: Color::TRANSPARENT,
304 decoration_color: None,
305 background: s.background.map(|b| TextBackground {
306 color: Color::TRANSPARENT,
307 ..b
308 }),
309 hidden: false,
312 ..*s
313 };
314 let (mut a, mut b) = (a.iter().peekable(), b.iter().peekable());
316 loop {
317 match (a.peek(), b.peek()) {
318 (None, None) => return true,
319 (Some(x), Some(y)) => {
320 let overlap = x.start < y.end && y.start < x.end;
321 if !overlap || colorless(&x.style) != colorless(&y.style) {
322 return false;
323 }
324 match x.end.cmp(&y.end) {
325 std::cmp::Ordering::Less => {
326 a.next();
327 }
328 std::cmp::Ordering::Greater => {
329 b.next();
330 }
331 std::cmp::Ordering::Equal => {
332 a.next();
333 b.next();
334 }
335 }
336 }
337 _ => return false,
338 }
339 }
340}
341
342#[derive(Debug, Clone, Copy, PartialEq)]
347pub struct TextSpan {
348 pub start: u32,
350 pub end: u32,
352 pub style: ResolvedTextStyle,
354}
355
356#[derive(Debug, Clone, PartialEq, Default)]
359pub struct AttributedText {
360 pub text: String,
362 pub spans: Vec<TextSpan>,
364 #[doc(hidden)]
370 pub paragraph_strut: Option<ResolvedTextStyle>,
371 pub align: TextAlign,
373 pub max_lines: u32,
375 pub ellipsize: EllipsizeMode,
377 pub no_wrap: bool,
380 pub shadow: Option<TextShadow>,
382 pub links: Vec<TextLink>,
384 #[doc(hidden)]
391 pub link_hrefs: Vec<LinkHref>,
392 pub test_ids: Vec<SpanTestId>,
395 pub copy_texts: Vec<AttachmentCopyText>,
400 pub writing_direction: Option<bool>,
403 pub rtl: bool,
406 pub selectable: Option<bool>,
411 pub selection_color: Option<Color>,
414 pub attachments: Vec<TextAttachment>,
419}
420
421#[derive(Debug, Clone, Copy, PartialEq)]
431pub struct TextAttachment {
432 pub index: u32,
434 pub width: Points,
436 pub height: Points,
438}
439
440#[derive(Debug, Clone, Copy, PartialEq, Default)]
443#[non_exhaustive]
444pub struct FontExtent {
445 pub ascent: Points,
447 pub descent: Points,
449 pub x_height: Points,
451}
452
453impl FontExtent {
454 pub fn new(ascent: Points, descent: Points, x_height: Points) -> Self {
456 Self {
457 ascent,
458 descent,
459 x_height,
460 }
461 }
462}
463
464impl TextAttachment {
465 pub fn ascent(&self, font: FontExtent, align: VerticalAlign) -> Points {
469 let h = self.height;
470 match align {
471 VerticalAlign::Baseline => h,
472 VerticalAlign::TextTop => font.ascent,
473 VerticalAlign::TextBottom => h - font.descent,
474 VerticalAlign::Middle => (h + font.x_height) / 2.0,
475 }
476 }
477
478 pub fn extent(&self, font: FontExtent, align: VerticalAlign) -> (Points, Points) {
485 let ascent = self.ascent(font, align);
486 (
487 ascent.max(Points::ZERO),
488 (self.height - ascent).max(Points::ZERO),
489 )
490 }
491}
492
493#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
497#[non_exhaustive]
498pub struct AttachmentAlignments {
499 values: Vec<(u32, VerticalAlign)>,
500 baselines: Vec<(u32, u32)>,
504}
505
506impl AttachmentAlignments {
507 pub fn get(&self, index: u32) -> VerticalAlign {
509 self.values
510 .binary_search_by_key(&index, |v| v.0)
511 .map_or(VerticalAlign::Baseline, |i| self.values[i].1)
512 }
513
514 pub fn set(&mut self, index: u32, align: VerticalAlign) {
516 match self.values.binary_search_by_key(&index, |v| v.0) {
517 Ok(i) if align == VerticalAlign::Baseline => {
518 self.values.remove(i);
519 }
520 Ok(i) => self.values[i].1 = align,
521 Err(i) if align != VerticalAlign::Baseline => self.values.insert(i, (index, align)),
522 Err(_) => {}
523 }
524 }
525
526 pub fn baseline(&self, index: u32) -> Option<Points> {
532 self.baselines
533 .binary_search_by_key(&index, |v| v.0)
534 .ok()
535 .map(|i| Points(f32::from_bits(self.baselines[i].1)))
536 }
537
538 pub fn set_baseline(&mut self, index: u32, baseline: Option<Points>) {
541 match (
542 self.baselines.binary_search_by_key(&index, |v| v.0),
543 baseline,
544 ) {
545 (Ok(i), Some(b)) => self.baselines[i].1 = b.0.to_bits(),
546 (Ok(i), None) => {
547 self.baselines.remove(i);
548 }
549 (Err(i), Some(b)) => self.baselines.insert(i, (index, b.0.to_bits())),
550 (Err(_), None) => {}
551 }
552 }
553
554 pub fn ascent(&self, a: &TextAttachment, font: FontExtent) -> Points {
560 match (self.get(a.index), self.baseline(a.index)) {
561 (VerticalAlign::Baseline, Some(baseline)) => baseline.max(Points::ZERO).min(a.height),
562 (align, _) => a.ascent(font, align),
563 }
564 }
565
566 pub fn extent(&self, a: &TextAttachment, font: FontExtent) -> (Points, Points) {
569 let ascent = self.ascent(a, font);
570 (
571 ascent.max(Points::ZERO),
572 (a.height - ascent).max(Points::ZERO),
573 )
574 }
575
576 pub fn push(
578 &mut self,
579 text: &mut AttributedText,
580 size: Size<Points>,
581 align: VerticalAlign,
582 style: ResolvedTextStyle,
583 ) {
584 self.set(text.len_utf16(), align);
585 text.push_attachment(size, style);
586 }
587
588 pub fn is_empty(&self) -> bool {
590 self.values.is_empty() && self.baselines.is_empty()
591 }
592
593 pub fn layout_hash(&self, text: &AttributedText) -> u64 {
595 if self.is_empty() {
596 return text.layout_hash();
597 }
598 use std::hash::{Hash, Hasher};
599 let mut h = std::collections::hash_map::DefaultHasher::new();
600 text.layout_hash().hash(&mut h);
601 self.hash(&mut h);
602 h.finish()
603 }
604}
605
606fn is_emoji_presentation(c: &str) -> bool {
610 use unicode_properties::{EmojiStatus, UnicodeEmoji};
611 !c.contains('\u{FE0E}')
612 && c.chars().any(|ch| {
613 ch == '\u{FE0F}'
614 || matches!(
615 ch.emoji_status(),
616 EmojiStatus::EmojiPresentation
617 | EmojiStatus::EmojiPresentationAndModifierBase
618 | EmojiStatus::EmojiPresentationAndEmojiComponent
619 | EmojiStatus::EmojiPresentationAndModifierAndEmojiComponent
620 )
621 })
622}
623
624fn utf16_len(s: &str) -> u32 {
626 s.chars().map(|c| c.len_utf16() as u32).sum()
627}
628
629pub(crate) fn escape_html(out: &mut String, s: &str) {
632 for c in s.chars() {
633 match c {
634 '&' => out.push_str("&"),
635 '<' => out.push_str("<"),
636 '>' => out.push_str(">"),
637 '"' => out.push_str("""),
638 c => out.push(c),
639 }
640 }
641}
642
643fn seek(s: &str, mut byte: usize, mut at: u32, to: u32) -> (usize, u32) {
648 for c in s[byte..].chars() {
649 let next = at + c.len_utf16() as u32;
650 if next > to {
651 break;
652 }
653 (at, byte) = (next, byte + c.len_utf8());
654 }
655 (byte, at)
656}
657
658pub const ATTACHMENT_CHAR: char = '\u{FFFC}';
660
661#[derive(Debug, Clone, Copy, PartialEq)]
672pub struct TextLink {
673 pub start: u32,
675 pub end: u32,
677 pub node: NodeId,
679 pub events: EventMask,
681 pub focus_stop: bool,
684}
685
686#[derive(Debug, Clone, PartialEq, Default)]
688#[non_exhaustive]
689pub struct SpanTestId {
690 pub start: u32,
692 pub end: u32,
694 pub test_id: Arc<str>,
696}
697
698#[doc(hidden)]
701#[derive(Debug, Clone, PartialEq, Default)]
702#[non_exhaustive]
703pub struct LinkHref {
704 pub link: u32,
706 pub href: Arc<str>,
708}
709
710impl LinkHref {
711 pub fn new(link: u32, href: impl Into<Arc<str>>) -> Self {
713 Self {
714 link,
715 href: href.into(),
716 }
717 }
718}
719
720#[derive(Debug, Clone, PartialEq, Default)]
724#[non_exhaustive]
725pub struct AttachmentCopyText {
726 pub index: u32,
729 pub text: Arc<str>,
731}
732
733impl AttachmentCopyText {
734 pub fn new(index: u32, text: impl Into<Arc<str>>) -> Self {
736 Self {
737 index,
738 text: text.into(),
739 }
740 }
741}
742
743impl AttributedText {
744 pub fn is_selectable(&self) -> bool {
746 self.selectable == Some(true)
747 }
748
749 pub fn has_backgrounds(&self) -> bool {
751 self.spans.iter().any(|s| s.style.background.is_some())
752 }
753
754 #[doc(hidden)]
757 pub fn paragraph_strut_or_first(&self) -> ResolvedTextStyle {
758 self.paragraph_strut.unwrap_or_else(|| {
759 self.spans
760 .first()
761 .map_or_else(ResolvedTextStyle::default, |s| s.style)
762 })
763 }
764
765 #[inline]
769 fn paragraph_strut_layout_eq(&self, other: &Self) -> bool {
770 let (a, b) = (
771 self.paragraph_strut_or_first(),
772 other.paragraph_strut_or_first(),
773 );
774 a.font_size == b.font_size
775 && a.font_weight == b.font_weight
776 && a.line_height == b.line_height
777 && a.font_family == b.font_family
778 && a.italic == b.italic
779 && a.font_variant == b.font_variant
780 }
781
782 pub(crate) fn approx_metrics(&self) -> (Points, Points) {
786 if self.spans.is_empty() {
787 let font = px(14.0);
788 return (font, font * 1.2);
789 }
790 self.spans.iter().fold(
791 (Points::ZERO, self.paragraph_strut_or_first().line_height),
792 |(font, line), span| {
793 let s = &span.style;
794 (
795 font.max(s.font_size.max(px(1.0))),
796 line.max(s.approx_line_height()),
797 )
798 },
799 )
800 }
801
802 pub fn uniform_color(&self) -> Option<Color> {
806 let color = self.spans.first()?.style.color;
807 self.spans
808 .iter()
809 .all(|s| {
810 !s.style.hidden
812 && s.style.color == color
813 && (s.style.decoration.is_none()
814 || s.style.decoration_color.is_none_or(|c| c == color))
815 })
816 .then_some(color)
817 }
818
819 pub fn has_hidden(&self) -> bool {
821 self.spans.iter().any(|s| s.style.hidden)
822 }
823
824 pub fn visible_text(&self) -> std::borrow::Cow<'_, str> {
830 let spacers = self.attachments.iter().any(|a| a.height <= Points::ZERO);
831 if !self.has_hidden() && !spacers {
832 return std::borrow::Cow::Borrowed(&self.text);
833 }
834 let mut out = String::with_capacity(self.text.len());
835 self.each_shown(0..self.len_utf16(), |s, _| out.push_str(s));
836 if spacers {
837 let shown: Vec<bool> = self
840 .attachments
841 .iter()
842 .filter(|a| !self.hidden_at(a.index))
843 .map(|a| a.height > Points::ZERO)
844 .collect();
845 let mut nth = 0;
846 out.retain(|c| {
847 if c != ATTACHMENT_CHAR {
848 return true;
849 }
850 nth += 1;
851 shown.get(nth - 1).copied().unwrap_or(true)
852 });
853 }
854 std::borrow::Cow::Owned(out)
855 }
856
857 pub fn copied_text(&self, range: Range<u32>) -> String {
863 if self.copy_texts.is_empty() {
864 return self.text_without_attachments(range);
865 }
866 let mut out = String::new();
867 let mut copies = self.copy_texts.iter().peekable();
868 self.each_shown(range, |s, mut at| {
869 for c in s.chars() {
870 if c == ATTACHMENT_CHAR {
871 while copies.next_if(|t| t.index < at).is_some() {}
872 if let Some(copy) = copies.next_if(|t| t.index == at) {
873 out.push_str(©.text);
874 }
875 } else {
876 out.push(c);
877 }
878 at += c.len_utf16() as u32;
879 }
880 });
881 out
882 }
883
884 #[doc(hidden)]
893 pub fn copied_html(&self, range: Range<u32>) -> (String, bool) {
894 #[derive(Clone, Copy, PartialEq)]
895 struct Format<'a> {
896 href: Option<&'a str>,
897 bold: bool,
898 italic: bool,
899 }
900 fn close(out: &mut String, f: Format<'_>) {
901 if f.italic {
902 out.push_str("</i>");
903 }
904 if f.bold {
905 out.push_str("</b>");
906 }
907 if f.href.is_some() {
908 out.push_str("</a>");
909 }
910 }
911 fn open(out: &mut String, f: Format<'_>) {
912 if let Some(href) = f.href {
913 out.push_str("<a href=\"");
914 escape_html(out, href);
915 out.push_str("\">");
916 }
917 if f.bold {
918 out.push_str("<b>");
919 }
920 if f.italic {
921 out.push_str("<i>");
922 }
923 }
924 let plain = Format {
925 href: None,
926 bold: false,
927 italic: false,
928 };
929 let mut out = String::new();
930 let mut formatted = false;
931 let mut current = plain;
932 let mut copies = self.copy_texts.iter().peekable();
933 let mut piece = String::new();
934 self.each_shown(range, |s, mut at| {
935 for c in s.chars() {
936 let format = match self.span_at(at) {
937 Some(span) => Format {
938 href: self
939 .links
940 .iter()
941 .enumerate()
942 .filter(|(_, l)| at >= l.start && at < l.end)
943 .filter_map(|(n, l)| Some((l.end - l.start, self.link_href(n)?)))
944 .min_by_key(|&(len, _)| len)
945 .map(|(_, href)| href),
946 bold: span.style.font_weight >= 600,
947 italic: span.style.italic,
948 },
949 None => plain,
950 };
951 piece.clear();
952 if c == ATTACHMENT_CHAR {
953 while copies.next_if(|t| t.index < at).is_some() {}
954 if let Some(copy) = copies.next_if(|t| t.index == at) {
955 piece.push_str(©.text);
956 }
957 } else {
958 piece.push(c);
959 }
960 at += c.len_utf16() as u32;
961 if piece.is_empty() {
962 continue;
963 }
964 if format != current {
965 close(&mut out, current);
966 open(&mut out, format);
967 current = format;
968 formatted |= format != plain;
969 }
970 for line in piece.split_inclusive('\n') {
971 match line.strip_suffix('\n') {
972 Some(line) => {
973 escape_html(&mut out, line);
974 out.push_str("<br>");
975 }
976 None => escape_html(&mut out, line),
977 }
978 }
979 }
980 });
981 close(&mut out, current);
982 (out, formatted)
983 }
984
985 pub fn text_without_attachments(&self, range: Range<u32>) -> String {
991 let mut out = String::new();
992 self.each_shown(range, |s, _| {
993 out.extend(s.chars().filter(|&c| c != ATTACHMENT_CHAR));
994 });
995 out
996 }
997
998 fn each_shown(&self, range: Range<u32>, mut f: impl FnMut(&str, u32)) {
1002 let end = range.end.min(self.len_utf16().max(utf16_len(&self.text)));
1003 let (mut byte, mut at) = seek(&self.text, 0, 0, range.start.min(end));
1004 let mut spans = self.spans[self.spans.partition_point(|s| s.end <= at)..].iter();
1006 while at < end {
1007 let (to, hidden) = match spans.next() {
1008 Some(s) => (s.end.min(end), s.style.hidden),
1009 None => (end, false),
1010 };
1011 let (next, reached) = seek(&self.text, byte, at, to);
1012 if !hidden {
1013 f(&self.text[byte..next], at);
1014 }
1015 if reached == at {
1016 break;
1017 }
1018 (byte, at) = (next, reached);
1019 }
1020 }
1021
1022 pub fn span_at(&self, index: u32) -> Option<&TextSpan> {
1025 let i = self.spans.partition_point(|s| s.end <= index);
1026 self.spans.get(i.min(self.spans.len().saturating_sub(1)))
1027 }
1028
1029 pub fn visible_ranges(&self, range: Range<u32>) -> Vec<Range<u32>> {
1033 if !self.has_hidden() {
1034 return vec![range];
1035 }
1036 let mut out: Vec<Range<u32>> = Vec::new();
1037 let mut at = range.start;
1038 let first = self.spans.partition_point(|s| s.end <= at);
1039 for s in &self.spans[first..] {
1040 if at >= range.end {
1041 break;
1042 }
1043 let to = s.end.min(range.end);
1044 if !s.style.hidden && to > at {
1045 match out.last_mut() {
1046 Some(last) if last.end == at => last.end = to,
1047 _ => out.push(at..to),
1048 }
1049 }
1050 at = at.max(to);
1051 }
1052 if at < range.end {
1054 match out.last_mut() {
1055 Some(last) if last.end == at => last.end = range.end,
1056 _ => out.push(at..range.end),
1057 }
1058 }
1059 out
1060 }
1061
1062 pub fn hidden_at(&self, index: u32) -> bool {
1065 self.span_at(index).is_some_and(|s| s.style.hidden)
1066 }
1067
1068 pub fn background_at(&self, index: u32) -> Option<TextBackground> {
1070 self.span_at(index)?.style.background
1071 }
1072
1073 pub fn len_utf16(&self) -> u32 {
1075 self.spans.last().map_or(0, |s| s.end)
1076 }
1077
1078 pub fn link_at(&self, index: u32) -> Option<&TextLink> {
1080 self.links
1081 .iter()
1082 .filter(|l| index >= l.start && index < l.end)
1083 .min_by_key(|l| l.end - l.start)
1084 }
1085
1086 #[doc(hidden)]
1089 pub fn link_href(&self, link: usize) -> Option<&str> {
1090 self.link_hrefs
1091 .iter()
1092 .find(|h| h.link as usize == link)
1093 .map(|h| &*h.href)
1094 }
1095
1096 pub fn push_attachment(&mut self, size: Size<Points>, style: ResolvedTextStyle) {
1098 let index = self.len_utf16();
1099 self.push(ATTACHMENT_CHAR.encode_utf8(&mut [0; 3]), style);
1100 self.attachments.push(TextAttachment {
1101 index,
1102 width: size.width,
1103 height: size.height,
1104 });
1105 }
1106
1107 pub fn push(&mut self, s: &str, style: ResolvedTextStyle) {
1111 if s.is_empty() {
1112 return;
1113 }
1114 let s = &*style.transform.apply(s);
1115 if !style.italic || s.is_ascii() {
1116 self.push_run(s, style);
1117 return;
1118 }
1119 let upright = ResolvedTextStyle {
1122 italic: false,
1123 ..style
1124 };
1125 let (mut run, mut at) = (0, 0);
1126 while at < s.len() {
1127 let end = crate::text_edit::next_cluster(s, at);
1128 if is_emoji_presentation(&s[at..end]) {
1129 self.push_run(&s[run..at], style);
1130 self.push_run(&s[at..end], upright);
1131 run = end;
1132 }
1133 at = end;
1134 }
1135 self.push_run(&s[run..], style);
1136 }
1137
1138 fn push_run(&mut self, s: &str, style: ResolvedTextStyle) {
1139 if s.is_empty() {
1140 return;
1141 }
1142 let len = s.encode_utf16().count() as u32;
1143 self.text.push_str(s);
1144 match self.spans.last_mut() {
1145 Some(last) if last.style == style => last.end += len,
1146 last => {
1147 let start = last.map_or(0, |l| l.end);
1148 self.spans.push(TextSpan {
1149 start,
1150 end: start + len,
1151 style,
1152 });
1153 }
1154 }
1155 }
1156
1157 pub(crate) fn same_but_colors(&self, other: &Self) -> bool {
1164 let Self {
1166 text,
1167 spans,
1168 paragraph_strut: _,
1169 align,
1170 max_lines,
1171 ellipsize,
1172 no_wrap,
1173 shadow,
1174 links,
1175 writing_direction,
1176 rtl,
1177 selectable,
1178 selection_color,
1179 attachments,
1180 test_ids: _,
1181 copy_texts: _,
1182 link_hrefs: _,
1183 } = self;
1184 text == &other.text
1185 && self.paragraph_strut_layout_eq(other)
1186 && align == &other.align
1187 && max_lines == &other.max_lines
1188 && ellipsize == &other.ellipsize
1189 && no_wrap == &other.no_wrap
1190 && shadow == &other.shadow
1191 && links == &other.links
1192 && writing_direction == &other.writing_direction
1193 && rtl == &other.rtl
1194 && selectable == &other.selectable
1195 && selection_color == &other.selection_color
1196 && attachments == &other.attachments
1197 && spans_same_but_colors(spans, &other.spans)
1198 }
1199
1200 pub fn recolored_ranges(&self, other: &Self) -> Option<Vec<std::ops::Range<u32>>> {
1206 if !self.same_but_colors(other) {
1207 return None;
1208 }
1209 let mut out: Vec<std::ops::Range<u32>> = Vec::new();
1210 let (mut a, mut b) = (self.spans.iter().peekable(), other.spans.iter().peekable());
1213 while let (Some(x), Some(y)) = (a.peek(), b.peek()) {
1214 let (start, end) = (x.start.max(y.start), x.end.min(y.end));
1215 if start < end && x.style != y.style {
1216 match out.last_mut() {
1217 Some(last) if last.end >= start => last.end = last.end.max(end),
1218 _ => out.push(start..end),
1219 }
1220 }
1221 match x.end.cmp(&y.end) {
1222 std::cmp::Ordering::Less => {
1223 a.next();
1224 }
1225 std::cmp::Ordering::Greater => {
1226 b.next();
1227 }
1228 std::cmp::Ordering::Equal => {
1229 a.next();
1230 b.next();
1231 }
1232 }
1233 }
1234 Some(out)
1235 }
1236
1237 pub(crate) fn metadata_eq(&self, other: &Self) -> bool {
1241 self.test_ids == other.test_ids
1242 && self.copy_texts == other.copy_texts
1243 && self.link_hrefs == other.link_hrefs
1244 }
1245
1246 pub(crate) fn set_metadata(&mut self, other: &Self) {
1249 self.test_ids = other.test_ids.clone();
1250 self.copy_texts = other.copy_texts.clone();
1251 self.link_hrefs = other.link_hrefs.clone();
1252 }
1253
1254 pub(crate) fn rendering_eq(&self, other: &Self) -> bool {
1257 let Self {
1259 text,
1260 spans,
1261 paragraph_strut: _,
1262 align,
1263 max_lines,
1264 ellipsize,
1265 no_wrap,
1266 shadow,
1267 links,
1268 writing_direction,
1269 rtl,
1270 selectable,
1271 selection_color,
1272 attachments,
1273 test_ids: _,
1275 copy_texts: _,
1276 link_hrefs: _,
1277 } = self;
1278 text == &other.text
1279 && spans == &other.spans
1280 && self.paragraph_strut_layout_eq(other)
1281 && align == &other.align
1282 && max_lines == &other.max_lines
1283 && ellipsize == &other.ellipsize
1284 && no_wrap == &other.no_wrap
1285 && shadow == &other.shadow
1286 && links == &other.links
1287 && writing_direction == &other.writing_direction
1288 && rtl == &other.rtl
1289 && selectable == &other.selectable
1290 && selection_color == &other.selection_color
1291 && attachments == &other.attachments
1292 }
1293
1294 pub fn layout_eq(&self, other: &Self) -> bool {
1297 self.align == other.align
1298 && self.paragraph_strut_layout_eq(other)
1299 && self.writing_direction == other.writing_direction
1300 && self.rtl == other.rtl
1301 && self.max_lines == other.max_lines
1302 && self.ellipsize == other.ellipsize
1303 && self.no_wrap == other.no_wrap
1304 && self.text == other.text
1305 && self.attachments == other.attachments
1306 && self.spans.len() == other.spans.len()
1307 && self
1308 .spans
1309 .iter()
1310 .zip(&other.spans)
1311 .all(|(a, b)| a.start == b.start && a.end == b.end && a.style.layout_eq(&b.style))
1312 }
1313
1314 pub fn layout_hash(&self) -> u64 {
1317 let mut h = std::hash::DefaultHasher::new();
1318 self.text.hash(&mut h);
1319 let strut = self.paragraph_strut_or_first();
1320 strut.line_height.0.to_bits().hash(&mut h);
1321 (
1322 strut.font_size.0.to_bits(),
1323 strut.font_weight,
1324 strut.font_family,
1325 strut.italic,
1326 strut.font_variant,
1327 )
1328 .hash(&mut h);
1329 (self.align as u8, self.writing_direction, self.rtl).hash(&mut h);
1330 (self.max_lines, self.ellipsize, self.no_wrap).hash(&mut h);
1331 for s in &self.spans {
1332 (s.start, s.end, s.style.font_weight).hash(&mut h);
1333 (s.style.font_family, s.style.italic, s.style.font_variant).hash(&mut h);
1334 s.style.font_size.0.to_bits().hash(&mut h);
1335 s.style.line_height.0.to_bits().hash(&mut h);
1336 s.style.letter_spacing.0.to_bits().hash(&mut h);
1337 }
1338 for a in &self.attachments {
1339 (a.index, a.width.0.to_bits(), a.height.0.to_bits()).hash(&mut h);
1340 }
1341 h.finish()
1342 }
1343}
1344
1345#[derive(Clone)]
1349pub struct TextLayout(pub Arc<dyn Any + Send + Sync>);
1350
1351impl TextLayout {
1352 pub fn downcast<T: Any>(&self) -> Option<&T> {
1354 self.0.downcast_ref()
1355 }
1356}
1357
1358impl fmt::Debug for TextLayout {
1359 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1360 f.write_str("TextLayout")
1361 }
1362}
1363
1364#[derive(Debug, Clone, Copy, PartialEq, Default)]
1370#[non_exhaustive]
1371pub struct TextOptions {
1372 pub indent: Option<Points>,
1382}
1383
1384impl TextOptions {
1385 #[must_use]
1389 pub fn indent(mut self, indent: impl Into<Option<Points>>) -> Self {
1390 self.indent = indent
1391 .into()
1392 .filter(|indent| indent.0.is_finite() && indent.0 > 0.0);
1393 self
1394 }
1395}
1396
1397pub trait TextEngine {
1404 type Prepared;
1407
1408 fn prepare(&self, text: &AttributedText) -> Self::Prepared;
1410
1411 fn prepare_aligned(
1414 &self,
1415 text: &AttributedText,
1416 alignments: &AttachmentAlignments,
1417 ) -> Self::Prepared {
1418 let _ = alignments;
1419 self.prepare(text)
1420 }
1421
1422 fn prepare_with(
1425 &self,
1426 text: &AttributedText,
1427 alignments: &AttachmentAlignments,
1428 options: &TextOptions,
1429 ) -> Self::Prepared {
1430 let _ = options;
1431 self.prepare_aligned(text, alignments)
1432 }
1433
1434 fn measure(&self, prepared: &Self::Prepared, max_width: Option<Points>) -> Size<Points>;
1436
1437 fn first_baseline(&self, prepared: &Self::Prepared, width: Points) -> Option<Points> {
1443 let _ = (prepared, width);
1444 None
1445 }
1446
1447 fn uniform_input_line_height(&self) -> bool {
1450 false
1451 }
1452
1453 fn breaks_lines_greedily(&self) -> bool {
1459 false
1460 }
1461
1462 fn draws_colors_from_text(&self) -> bool {
1472 false
1473 }
1474
1475 fn layout(&self, prepared: &Self::Prepared, size: Size<Points>) -> TextLayout;
1477
1478 fn lines(&self, layout: &TextLayout) -> Vec<TextLine> {
1481 let _ = layout;
1482 Vec::new()
1483 }
1484
1485 fn attachments(&self, layout: &TextLayout) -> Vec<Option<Point<Points>>> {
1489 let _ = layout;
1490 Vec::new()
1491 }
1492
1493 fn hit_test(&self, layout: &TextLayout, point: Point<Points>) -> TextPosition {
1503 estimate::hit_test(&self.lines(layout), point)
1504 }
1505
1506 fn caret_rect(&self, layout: &TextLayout, position: TextPosition) -> Option<Bounds<Points>> {
1513 estimate::caret_rect(&self.lines(layout), position)
1514 }
1515
1516 fn range_rects(&self, layout: &TextLayout, range: Range<u32>, out: &mut Vec<Bounds<Points>>) {
1526 estimate::range_rects(&self.lines(layout), range, out);
1527 }
1528
1529 fn register_font(&self, data: &[u8]) -> Result<(), String> {
1533 let _ = data;
1534 Err("this text engine does not support custom fonts".to_owned())
1535 }
1536}
1537
1538impl<T: TextEngine> TextEngine for std::rc::Rc<T> {
1541 type Prepared = T::Prepared;
1542
1543 fn prepare(&self, text: &AttributedText) -> Self::Prepared {
1544 (**self).prepare(text)
1545 }
1546
1547 fn prepare_aligned(
1548 &self,
1549 text: &AttributedText,
1550 alignments: &AttachmentAlignments,
1551 ) -> Self::Prepared {
1552 (**self).prepare_aligned(text, alignments)
1553 }
1554
1555 fn prepare_with(
1556 &self,
1557 text: &AttributedText,
1558 alignments: &AttachmentAlignments,
1559 options: &TextOptions,
1560 ) -> Self::Prepared {
1561 (**self).prepare_with(text, alignments, options)
1562 }
1563
1564 fn breaks_lines_greedily(&self) -> bool {
1565 (**self).breaks_lines_greedily()
1566 }
1567
1568 fn draws_colors_from_text(&self) -> bool {
1569 (**self).draws_colors_from_text()
1570 }
1571
1572 fn uniform_input_line_height(&self) -> bool {
1573 (**self).uniform_input_line_height()
1574 }
1575
1576 fn measure(&self, prepared: &Self::Prepared, max_width: Option<Points>) -> Size<Points> {
1577 (**self).measure(prepared, max_width)
1578 }
1579
1580 fn first_baseline(&self, prepared: &Self::Prepared, width: Points) -> Option<Points> {
1581 (**self).first_baseline(prepared, width)
1582 }
1583
1584 fn layout(&self, prepared: &Self::Prepared, size: Size<Points>) -> TextLayout {
1585 (**self).layout(prepared, size)
1586 }
1587
1588 fn lines(&self, layout: &TextLayout) -> Vec<TextLine> {
1589 (**self).lines(layout)
1590 }
1591
1592 fn attachments(&self, layout: &TextLayout) -> Vec<Option<Point<Points>>> {
1593 (**self).attachments(layout)
1594 }
1595
1596 fn hit_test(&self, layout: &TextLayout, point: Point<Points>) -> TextPosition {
1597 (**self).hit_test(layout, point)
1598 }
1599
1600 fn caret_rect(&self, layout: &TextLayout, position: TextPosition) -> Option<Bounds<Points>> {
1601 (**self).caret_rect(layout, position)
1602 }
1603
1604 fn range_rects(&self, layout: &TextLayout, range: Range<u32>, out: &mut Vec<Bounds<Points>>) {
1605 (**self).range_rects(layout, range, out);
1606 }
1607
1608 fn register_font(&self, data: &[u8]) -> Result<(), String> {
1609 (**self).register_font(data)
1610 }
1611}
1612
1613#[derive(Debug, Clone, PartialEq, Default)]
1616pub struct TextLine {
1617 pub text: String,
1619 pub start: u32,
1621 pub end: u32,
1623 pub x: Points,
1625 pub y: Points,
1627 pub width: Points,
1629 pub height: Points,
1631 pub ascender: Points,
1633 pub descender: Points,
1635 pub cap_height: Points,
1637 pub x_height: Points,
1639}
1640
1641#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1644pub enum Affinity {
1645 Upstream,
1648 #[default]
1651 Downstream,
1652}
1653
1654#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1656#[non_exhaustive]
1657pub struct TextPosition {
1658 pub offset: u32,
1660 pub affinity: Affinity,
1662}
1663
1664impl TextPosition {
1665 pub const fn new(offset: u32, affinity: Affinity) -> Self {
1667 Self { offset, affinity }
1668 }
1669
1670 pub fn line(self, lines: &[TextLine]) -> Option<usize> {
1676 self.line_in(lines.iter().map(|l| l.start..l.end))
1677 }
1678
1679 pub fn line_in<I>(self, ranges: I) -> Option<usize>
1682 where
1683 I: IntoIterator<Item = Range<u32>>,
1684 I::IntoIter: Clone,
1685 {
1686 let ranges = ranges.into_iter();
1687 let o = self.offset;
1688 let holds = |r: &Range<u32>| match self.affinity {
1689 Affinity::Upstream => r.start < o && o <= r.end,
1690 Affinity::Downstream => r.start <= o && o < r.end,
1691 };
1692 ranges
1693 .clone()
1694 .position(|r| holds(&r))
1695 .or_else(|| {
1696 let starts = ranges.clone().enumerate();
1697 starts.filter(|(_, r)| r.start <= o).last().map(|(i, _)| i)
1698 })
1699 .or_else(|| ranges.clone().next().map(|_| 0))
1700 }
1701}
1702
1703mod estimate {
1706 use super::*;
1707
1708 pub(super) fn line_at(lines: &[TextLine], y: Points) -> Option<&TextLine> {
1711 lines.iter().find(|l| y < l.y + l.height).or(lines.last())
1712 }
1713
1714 fn x_of(l: &TextLine, o: u32) -> Points {
1716 let count = l.end.saturating_sub(l.start);
1717 if count == 0 {
1718 return l.x;
1719 }
1720 let done = o.clamp(l.start, l.end) - l.start;
1721 l.x + l.width * (done as f32 / count as f32)
1722 }
1723
1724 pub(super) fn hit_test(lines: &[TextLine], p: Point<Points>) -> TextPosition {
1725 let Some(l) = line_at(lines, p.y) else {
1726 return TextPosition::default();
1727 };
1728 let count = l.end.saturating_sub(l.start);
1729 let fraction = if l.width > Points::ZERO {
1730 ((p.x - l.x) / l.width).clamp(0.0, 1.0)
1731 } else {
1732 0.0
1733 };
1734 let offset = l.start + (fraction * count as f32).round() as u32;
1736 let affinity = if offset == l.end && count > 0 {
1737 Affinity::Upstream
1738 } else {
1739 Affinity::Downstream
1740 };
1741 TextPosition::new(offset, affinity)
1742 }
1743
1744 pub(super) fn caret_rect(lines: &[TextLine], position: TextPosition) -> Option<Bounds<Points>> {
1745 let l = lines.get(position.line(lines)?)?;
1746 Some(Bounds::new(
1747 point(x_of(l, position.offset), l.y),
1748 size(Points::ZERO, l.height),
1749 ))
1750 }
1751
1752 pub(super) fn range_rects(lines: &[TextLine], r: Range<u32>, out: &mut Vec<Bounds<Points>>) {
1753 if r.start >= r.end {
1754 return;
1755 }
1756 for l in lines.iter().filter(|l| l.start < r.end && r.start < l.end) {
1757 let x1 = x_of(l, r.start);
1758 let x2 = if r.end > l.end {
1759 l.x + l.width
1760 } else {
1761 x_of(l, r.end)
1762 };
1763 out.push(Bounds::new(point(x1, l.y), size(x2 - x1, l.height)));
1764 }
1765 }
1766}
1767
1768#[doc(hidden)]
1770#[derive(Debug, Clone)]
1771#[non_exhaustive]
1772pub struct ApproxPrepared {
1773 chars: usize,
1774 font: Points,
1775 strut_font: Points,
1778 line: Points,
1779 max_lines: u32,
1780 indent: Points,
1783 attachments: Vec<TextAttachment>,
1784 astral: Vec<u32>,
1785 breaks: Vec<usize>,
1786}
1787
1788impl ApproxPrepared {
1789 #[doc(hidden)]
1791 pub fn chars(&self) -> usize {
1792 self.chars
1793 }
1794}
1795
1796impl Default for ApproxPrepared {
1797 fn default() -> Self {
1798 let font = px(14.0);
1799 Self {
1800 chars: 0,
1801 font,
1802 strut_font: font,
1803 line: font * 1.2,
1804 max_lines: 0,
1805 indent: Points::ZERO,
1806 attachments: Vec::new(),
1807 astral: Vec::new(),
1808 breaks: Vec::new(),
1809 }
1810 }
1811}
1812
1813#[derive(Debug, Default, Clone, Copy)]
1824pub struct ApproxTextEngine;
1825
1826impl TextEngine for ApproxTextEngine {
1827 type Prepared = ApproxPrepared;
1828
1829 fn prepare(&self, text: &AttributedText) -> Self::Prepared {
1830 self.prepare_aligned(text, &AttachmentAlignments::default())
1831 }
1832
1833 fn prepare_aligned(
1834 &self,
1835 text: &AttributedText,
1836 alignments: &AttachmentAlignments,
1837 ) -> Self::Prepared {
1838 let (font, line) = text.approx_metrics();
1839 let astral = text
1841 .text
1842 .chars()
1843 .enumerate()
1844 .filter(|(_, c)| c.len_utf16() == 2)
1845 .filter_map(|(i, _)| u32::try_from(i).ok())
1846 .collect();
1847 let breaks = match text.text.contains('\n') {
1849 true => text.text.split('\n').map(|l| l.chars().count()).collect(),
1850 false => Vec::new(),
1851 };
1852 let metrics = FontExtent::new(font * 1.2, Points::ZERO, font * 0.5);
1853 ApproxPrepared {
1854 chars: text.text.chars().count(),
1855 font,
1856 strut_font: match text.paragraph_strut {
1857 Some(strut) if strut.line_height.0 > 0.0 => strut.font_size,
1858 _ => font,
1861 },
1862 line,
1863 max_lines: text.max_lines,
1864 indent: Points::ZERO,
1865 attachments: text
1866 .attachments
1867 .iter()
1868 .map(|a| TextAttachment {
1869 height: alignments.ascent(a, metrics),
1870 ..*a
1871 })
1872 .collect(),
1873 astral,
1874 breaks,
1875 }
1876 }
1877
1878 fn prepare_with(
1879 &self,
1880 text: &AttributedText,
1881 alignments: &AttachmentAlignments,
1882 options: &TextOptions,
1883 ) -> Self::Prepared {
1884 let mut prepared = self.prepare_aligned(text, alignments);
1885 prepared.indent = options.indent.unwrap_or(Points::ZERO);
1887 prepared
1888 }
1889
1890 fn first_baseline(&self, prepared: &Self::Prepared, _: Points) -> Option<Points> {
1893 let natural = prepared.strut_font * 1.2;
1894 Some(natural + (prepared.line - natural) * 0.5)
1895 }
1896
1897 fn measure(&self, prepared: &Self::Prepared, max_width: Option<Points>) -> Size<Points> {
1898 let wrap = |chars: usize| {
1900 let width = Points(chars as f32 * prepared.font.0 * 0.55);
1901 match max_width {
1902 Some(max) if max > Points::ZERO && prepared.indent == Points::ZERO => {
1905 match width > max {
1906 true => (max, (width / max).ceil()),
1907 false => (width, 1.0),
1908 }
1909 }
1910 Some(max) if max > Points::ZERO => {
1911 let first = (max - prepared.indent).max(Points::ZERO);
1914 if width <= first {
1915 (width + prepared.indent, 1.0)
1916 } else {
1917 (
1918 first + prepared.indent,
1919 1.0 + ((width - first) / max).ceil(),
1920 )
1921 }
1922 }
1923 _ => (width + prepared.indent, 1.0),
1924 }
1925 };
1926 let (width, mut lines) = match prepared.breaks.is_empty() {
1927 true => wrap(prepared.chars),
1928 false => prepared
1929 .breaks
1930 .iter()
1931 .fold((Points::ZERO, 0.0), |(w, n), &c| {
1932 let (lw, ln) = wrap(c);
1933 (w.max(lw), n + ln)
1934 }),
1935 };
1936 if prepared.max_lines > 0 {
1937 lines = lines.min(prepared.max_lines as f32);
1938 }
1939 size(width, prepared.line * lines)
1940 }
1941
1942 fn layout(&self, prepared: &Self::Prepared, size: Size<Points>) -> TextLayout {
1943 let line = prepared.line;
1945 let font = prepared.font;
1946 let natural = prepared.strut_font * 1.2;
1947 let baseline = natural + (line - natural) * 0.5;
1948 let advance = font * 0.55;
1949 let units = prepared.chars.saturating_add(prepared.astral.len());
1950 let mut layout = ApproxLayout {
1951 attachments: Vec::new(),
1952 attachment_widths: Vec::new(),
1953 line: TextLine {
1954 end: u32::try_from(units).unwrap_or(u32::MAX),
1955 width: size.width,
1956 height: line,
1957 ascender: baseline,
1958 descender: (line - baseline).max(Points::ZERO),
1959 x_height: font * 0.5,
1960 ..TextLine::default()
1961 },
1962 advance,
1963 chars: u32::try_from(prepared.chars).unwrap_or(u32::MAX),
1964 astral: prepared.astral.clone(),
1965 };
1966 layout.attachment_widths = prepared
1967 .attachments
1968 .iter()
1969 .map(|a| (layout.char_at(a.index), a.width))
1970 .collect();
1971 layout.attachment_widths.sort_unstable_by_key(|&(k, _)| k);
1972 layout.attachments = prepared
1975 .attachments
1976 .iter()
1977 .map(|a| {
1978 let (row, x) = approx_place(
1979 layout.char_at(a.index) as usize,
1980 prepared.chars,
1981 font,
1982 &prepared.breaks,
1983 size.width,
1984 );
1985 if prepared.max_lines > 0 && row >= prepared.max_lines as f32 {
1986 return None;
1987 }
1988 Some(point(
1989 x,
1990 line * row + (baseline - a.height).max(Points::ZERO),
1991 ))
1992 })
1993 .collect();
1994 TextLayout(Arc::new(layout))
1995 }
1996
1997 fn lines(&self, layout: &TextLayout) -> Vec<TextLine> {
1998 layout
1999 .downcast::<ApproxLayout>()
2000 .map_or_else(Vec::new, |l| vec![l.line.clone()])
2001 }
2002
2003 fn attachments(&self, layout: &TextLayout) -> Vec<Option<Point<Points>>> {
2004 layout
2005 .downcast::<ApproxLayout>()
2006 .map_or_else(Vec::new, |l| l.attachments.clone())
2007 }
2008
2009 fn hit_test(&self, layout: &TextLayout, p: Point<Points>) -> TextPosition {
2010 let Some(l) = layout.downcast::<ApproxLayout>() else {
2011 return TextPosition::default();
2012 };
2013 TextPosition::new(l.unit_of(l.hit_x(p.x)), Affinity::Downstream)
2014 }
2015
2016 fn caret_rect(&self, layout: &TextLayout, position: TextPosition) -> Option<Bounds<Points>> {
2017 let l = layout.downcast::<ApproxLayout>()?;
2018 Some(Bounds::new(
2019 point(l.x_of(position.offset), l.line.y),
2020 size(Points::ZERO, l.line.height),
2021 ))
2022 }
2023
2024 fn range_rects(&self, layout: &TextLayout, range: Range<u32>, out: &mut Vec<Bounds<Points>>) {
2025 let Some(l) = layout.downcast::<ApproxLayout>() else {
2026 return;
2027 };
2028 if range.start >= range.end || range.start >= l.line.end {
2029 return;
2030 }
2031 let (x1, x2) = (l.x_of(range.start), l.x_of(range.end));
2032 out.push(Bounds::new(
2033 point(x1, l.line.y),
2034 size(x2 - x1, l.line.height),
2035 ));
2036 }
2037
2038 fn register_font(&self, _: &[u8]) -> Result<(), String> {
2039 Ok(())
2040 }
2041}
2042
2043fn approx_place(
2049 k: usize,
2050 chars: usize,
2051 font: Points,
2052 breaks: &[usize],
2053 width: Points,
2054) -> (f32, Points) {
2055 let whole = [chars];
2056 let lines: &[usize] = if breaks.is_empty() { &whole } else { breaks };
2057 let wraps = |chars: usize| {
2059 let w = Points(chars as f32 * font.0 * 0.55);
2060 match w > width && width > Points::ZERO {
2061 true => (w / width).ceil(),
2062 false => 1.0,
2063 }
2064 };
2065 let (mut row, mut start) = (0.0, 0);
2066 for (i, &n) in lines.iter().enumerate() {
2067 if k <= start + n || i + 1 == lines.len() {
2068 let x = Points(k.saturating_sub(start) as f32 * font.0 * 0.55);
2069 let n_wraps = wraps(n);
2070 if n_wraps <= 1.0 {
2071 return (row, x);
2072 }
2073 let wrapped = (x / width).floor().min(n_wraps - 1.0);
2074 return (row + wrapped, x - width * wrapped);
2075 }
2076 row += wraps(n);
2077 start += n + 1;
2078 }
2079 (row, Points::ZERO)
2080}
2081
2082struct ApproxLayout {
2084 attachments: Vec<Option<Point<Points>>>,
2085 attachment_widths: Vec<(u32, Points)>,
2087 line: TextLine,
2088 advance: Points,
2090 chars: u32,
2091 astral: Vec<u32>,
2093}
2094
2095impl ApproxLayout {
2096 fn unit_of(&self, k: u32) -> u32 {
2098 let before = self.astral.partition_point(|&i| i < k);
2099 k.saturating_add(u32::try_from(before).unwrap_or(u32::MAX))
2100 }
2101
2102 fn char_at(&self, o: u32) -> u32 {
2105 let mut k = o;
2106 for (j, &i) in self.astral.iter().enumerate() {
2107 let start = i.saturating_add(u32::try_from(j).unwrap_or(u32::MAX));
2108 if start >= o {
2109 break;
2110 }
2111 k = if start.saturating_add(1) == o {
2112 i
2113 } else {
2114 k.saturating_sub(1)
2115 };
2116 }
2117 k.min(self.chars)
2118 }
2119
2120 fn x_of(&self, o: u32) -> Points {
2122 let k = self.char_at(o);
2123 let mut x = self.advance * k as f32;
2124 for &(at, width) in &self.attachment_widths {
2125 if at >= k {
2126 break;
2127 }
2128 x += width - self.advance;
2129 }
2130 x
2131 }
2132
2133 fn hit_x(&self, x: Points) -> u32 {
2135 if x <= Points::ZERO {
2136 return 0;
2137 }
2138 if self.attachment_widths.is_empty() {
2139 return if self.advance > Points::ZERO {
2140 (x / self.advance).round().clamp(0.0, self.chars as f32) as u32
2142 } else {
2143 0
2144 };
2145 }
2146 let mut seg_start = 0u32;
2147 let mut cur_x = Points::ZERO;
2148 for &(at, width) in &self.attachment_widths {
2149 let at = at.min(self.chars);
2150 if at > seg_start {
2151 let n = at - seg_start;
2152 let run_end = cur_x + self.advance * n as f32;
2153 if x < run_end {
2154 let step = if self.advance > Points::ZERO {
2155 ((x - cur_x) / self.advance).round().clamp(0.0, n as f32) as u32
2156 } else {
2157 0
2158 };
2159 return seg_start + step;
2160 }
2161 cur_x = run_end;
2162 }
2163 let att_end = cur_x + width;
2164 if x < att_end {
2165 return if x < cur_x + width * 0.5 {
2166 at
2167 } else {
2168 (at + 1).min(self.chars)
2169 };
2170 }
2171 cur_x = att_end;
2172 seg_start = (at + 1).min(self.chars);
2173 }
2174 if seg_start < self.chars {
2175 let n = self.chars - seg_start;
2176 let step = if self.advance > Points::ZERO {
2177 ((x - cur_x) / self.advance).round().clamp(0.0, n as f32) as u32
2178 } else {
2179 0
2180 };
2181 return seg_start + step;
2182 }
2183 self.chars
2184 }
2185}
2186
2187pub(crate) struct MeasureCache {
2201 current: FxHashMap<(u64, u32), Size<Points>>,
2202 previous: FxHashMap<(u64, u32), Size<Points>>,
2203 pixel_ratio: f32,
2204 cell: Option<Size<Points>>,
2205 pub(crate) resizing: Option<u32>,
2208}
2209
2210impl Default for MeasureCache {
2211 fn default() -> Self {
2212 Self {
2213 current: FxHashMap::default(),
2214 previous: FxHashMap::default(),
2215 pixel_ratio: 1.0,
2216 cell: None,
2217 resizing: None,
2218 }
2219 }
2220}
2221
2222impl MeasureCache {
2223 const GENERATION: usize = 512;
2224
2225 pub(crate) fn pixel_ratio(&self) -> f32 {
2227 self.pixel_ratio
2228 }
2229
2230 pub(crate) fn set_pixel_ratio(&mut self, ratio: f32) -> bool {
2233 let ratio = if ratio.is_finite() && ratio > 0.0 {
2234 ratio
2235 } else {
2236 1.0
2237 };
2238 if ratio == self.pixel_ratio {
2239 return false;
2240 }
2241 self.pixel_ratio = ratio;
2242 self.clear();
2243 true
2244 }
2245
2246 pub(crate) fn set_cell(&mut self, cell: Option<Size<Points>>) -> bool {
2250 if cell == self.cell {
2251 return false;
2252 }
2253 self.cell = cell;
2254 self.clear();
2255 true
2256 }
2257
2258 pub(crate) fn on_cells(&self, size: Size<Points>) -> Option<Size<Points>> {
2262 let cell = self.cell?;
2263 let up = |v: Points, c: Points| Points(((v.0 / c.0) - 1.0e-3).ceil().max(0.0) * c.0);
2264 Some(Size::new(
2265 up(size.width, cell.width),
2266 up(size.height, cell.height),
2267 ))
2268 }
2269
2270 pub(crate) fn clear(&mut self) {
2272 self.current.clear();
2273 self.previous.clear();
2274 }
2275
2276 #[inline]
2277 fn key(layout_hash: u64, max_width: Option<Points>) -> (u64, u32) {
2278 (layout_hash, max_width.map_or(f32::NAN, |w| w.0).to_bits())
2280 }
2281
2282 pub(crate) fn get(
2283 &mut self,
2284 layout_hash: u64,
2285 max_width: Option<Points>,
2286 ) -> Option<Size<Points>> {
2287 let key = Self::key(layout_hash, max_width);
2288 if let Some(&size) = self.current.get(&key) {
2289 return Some(size);
2290 }
2291 let size = self.previous.remove(&key)?;
2292 self.insert_key(key, size);
2293 Some(size)
2294 }
2295
2296 pub(crate) fn insert(
2297 &mut self,
2298 layout_hash: u64,
2299 max_width: Option<Points>,
2300 size: Size<Points>,
2301 ) {
2302 self.insert_key(Self::key(layout_hash, max_width), size);
2303 }
2304
2305 fn insert_key(&mut self, key: (u64, u32), size: Size<Points>) {
2306 if self.current.len() >= Self::GENERATION {
2307 self.previous = std::mem::take(&mut self.current);
2308 self.current.reserve(Self::GENERATION);
2309 }
2310 self.current.insert(key, size);
2311 }
2312
2313 #[cfg(test)]
2314 fn len(&self) -> usize {
2315 self.current.len() + self.previous.len()
2316 }
2317}
2318
2319const MAX_WOFF_TABLES: u64 = 128 * 1024 * 1024;
2322
2323pub fn font_data(data: &[u8]) -> Result<std::borrow::Cow<'_, [u8]>, String> {
2327 let unwrapped = match data.get(..4) {
2328 Some(b"wOFF") => {
2329 if let Some(size) = woff_tables_size(data)?.filter(|&size| size > MAX_WOFF_TABLES) {
2335 return Err(format!(
2336 "the WOFF font's tables declare {size} bytes, more than a font may hold \
2337 ({MAX_WOFF_TABLES})"
2338 ));
2339 }
2340 wuff::decompress_woff1(data)
2341 }
2342 Some(b"wOF2") => wuff::decompress_woff2(data),
2343 _ => return Ok(std::borrow::Cow::Borrowed(data)),
2344 };
2345 unwrapped
2346 .map(std::borrow::Cow::Owned)
2347 .map_err(|e| format!("the WOFF font does not decompress: {e:?}"))
2348}
2349
2350pub fn keep_font(fonts: &mut Vec<Vec<u8>>, data: &[u8]) -> bool {
2353 if fonts.iter().any(|font| font == data) {
2354 return false;
2355 }
2356 fonts.push(data.to_vec());
2357 true
2358}
2359
2360fn woff_tables_size(data: &[u8]) -> Result<Option<u64>, String> {
2366 let field = |at: usize| Some(u32::from_be_bytes(data.get(at..at + 4)?.try_into().ok()?));
2367 let Some(tables) = data.get(12..14) else {
2368 return Ok(None);
2369 };
2370 let mut size = 0;
2371 for table in 0..usize::from(u16::from_be_bytes([tables[0], tables[1]])) {
2372 let at = 44 + table * 20;
2373 let (Some(compressed), Some(length)) = (field(at + 8), field(at + 12)) else {
2374 return Ok(None);
2375 };
2376 if compressed > length {
2377 return Err(format!(
2378 "the WOFF font's table {table} is larger compressed ({compressed} bytes) than it is \
2379 ({length})"
2380 ));
2381 }
2382 size += u64::from(length);
2383 }
2384 Ok(Some(size))
2385}
2386
2387pub fn font_family(data: &[u8]) -> Result<String, String> {
2391 let data = font_data(data)?;
2392 let font = parse_font(&data).map_err(|e| format!("not a font: {e}"))?;
2393 font_name(&font, skrifa::raw::types::NameId::TYPOGRAPHIC_FAMILY_NAME)
2394 .or_else(|| font_name(&font, skrifa::raw::types::NameId::FAMILY_NAME))
2395 .ok_or_else(|| "the font has no family name".to_owned())
2396}
2397
2398fn parse_font(data: &[u8]) -> Result<skrifa::FontRef<'_>, String> {
2400 use skrifa::raw::TableProvider as _;
2401 let font = skrifa::FontRef::from_index(data, 0).map_err(|e| e.to_string())?;
2402 font.head().map_err(|e| e.to_string())?;
2403 Ok(font)
2404}
2405
2406fn font_name(font: &skrifa::FontRef<'_>, id: skrifa::raw::types::NameId) -> Option<String> {
2409 use skrifa::raw::TableProvider as _;
2410 let name = font.name().ok()?;
2411 name.name_record()
2412 .iter()
2413 .filter(|r| {
2414 r.name_id() == id && matches!((r.platform_id(), r.encoding_id()), (0, _) | (3, 0 | 1))
2415 })
2416 .find_map(|r| r.string(name.string_data()).ok())
2417 .map(|s| s.chars().collect())
2418}
2419
2420#[cfg(test)]
2421mod tests {
2422 use super::*;
2423
2424 #[test]
2425 fn push_merges_and_counts_utf16() {
2426 let mut t = AttributedText::default();
2427 let a = ResolvedTextStyle::default();
2428 let b = ResolvedTextStyle {
2429 font_weight: 700,
2430 ..a
2431 };
2432 t.push("ab", a);
2433 t.push("", b);
2434 t.push("😀", a);
2435 t.push("c", b);
2436 assert_eq!(t.text, "ab😀c");
2437 assert_eq!(t.spans.len(), 2);
2438 assert_eq!((t.spans[0].start, t.spans[0].end), (0, 4));
2439 assert_eq!((t.spans[1].start, t.spans[1].end), (4, 5));
2440 }
2441
2442 #[test]
2443 fn a_direct_text_falls_back_to_its_first_span_until_the_root_strut_is_set() {
2444 let small = ResolvedTextStyle {
2445 font_size: px(12.6),
2446 line_height: px(20.475),
2447 ..Default::default()
2448 };
2449 let root = ResolvedTextStyle {
2450 font_size: px(14.0),
2451 line_height: px(22.75),
2452 ..Default::default()
2453 };
2454 let mut text = AttributedText::default();
2455 text.push("`code`", small);
2456 text.push(" body", root);
2457
2458 let fallback = text.paragraph_strut_or_first();
2459 assert_eq!(fallback.font_size, small.font_size);
2460 assert_eq!(fallback.line_height, small.line_height);
2461
2462 text.paragraph_strut = Some(root);
2463 let explicit = text.paragraph_strut_or_first();
2464 assert_eq!(explicit.font_size, root.font_size);
2465 assert_eq!(explicit.line_height, root.line_height);
2466
2467 text.paragraph_strut = Some(ResolvedTextStyle {
2470 line_height: Points::ZERO,
2471 ..root
2472 });
2473 assert_eq!(text.paragraph_strut_or_first().line_height, Points::ZERO);
2474 }
2475
2476 #[test]
2477 fn only_the_root_struts_layout_metrics_compare() {
2478 let root = ResolvedTextStyle {
2479 color: Color(0xff00_00ff),
2480 font_size: px(14.0),
2481 line_height: px(22.75),
2482 letter_spacing: px(2.0),
2483 decoration: TextDecoration {
2484 underline: true,
2485 line_through: false,
2486 },
2487 ..Default::default()
2488 };
2489 let mut a = AttributedText::default();
2490 a.push("hello", root);
2491 a.paragraph_strut = Some(root);
2492 let mut b = a.clone();
2493 b.paragraph_strut = Some(ResolvedTextStyle {
2494 color: Color(0x0000_ffff),
2495 letter_spacing: Points::ZERO,
2496 decoration: TextDecoration::default(),
2497 transform: TextTransform::Uppercase,
2498 hidden: true,
2499 ..root
2500 });
2501
2502 assert!(a.layout_eq(&b));
2503 assert_eq!(a.layout_hash(), b.layout_hash());
2504 assert!(a.rendering_eq(&b));
2505 assert!(a.same_but_colors(&b));
2506
2507 let mut c = b.clone();
2508 c.paragraph_strut.as_mut().unwrap().font_weight = 700;
2509 assert!(!a.layout_eq(&c));
2510 assert_ne!(a.layout_hash(), c.layout_hash());
2511 assert!(!a.rendering_eq(&c));
2512 assert!(!a.same_but_colors(&c));
2513 }
2514
2515 #[test]
2516 fn italic_text_keeps_color_emoji_upright() {
2517 let italic = ResolvedTextStyle {
2518 italic: true,
2519 ..Default::default()
2520 };
2521 let runs = |s: &str| {
2522 let mut t = AttributedText::default();
2523 t.push(s, italic);
2524 let units: Vec<u16> = t.text.encode_utf16().collect();
2525 t.spans
2526 .iter()
2527 .map(|s| {
2528 let text = String::from_utf16(&units[s.start as usize..s.end as usize]);
2529 (text.unwrap(), s.style.italic)
2530 })
2531 .collect::<Vec<_>>()
2532 };
2533 let run = |s: &str, italic: bool| (s.to_owned(), italic);
2534 assert_eq!(
2535 runs("斜体 abc 😀😀 end"),
2536 [
2537 run("斜体 abc ", true),
2538 run("😀😀", false),
2539 run(" end", true)
2540 ]
2541 );
2542 assert_eq!(runs("👩💻👍🏽🇨🇳#️⃣❤️"), [run("👩💻👍🏽🇨🇳#️⃣❤️", false)]);
2544 assert_eq!(runs("© ❤ ☺ 😀\u{FE0E}"), [run("© ❤ ☺ 😀\u{FE0E}", true)]);
2546
2547 let mut t = AttributedText::default();
2549 t.push("a😀", ResolvedTextStyle::default());
2550 assert_eq!(t.spans.len(), 1);
2551 t.push("😀", italic);
2552 t.push("b", italic);
2553 assert_eq!(t.spans.len(), 2);
2554 assert_eq!((t.spans[0].end, t.spans[1].start), (5, 5));
2555 }
2556
2557 #[test]
2558 fn color_does_not_affect_layout_identity() {
2559 let mut a = AttributedText::default();
2560 a.push("hello", ResolvedTextStyle::default());
2561 let mut b = AttributedText::default();
2562 b.push(
2563 "hello",
2564 ResolvedTextStyle {
2565 color: Color(0xff00_00ff),
2566 ..Default::default()
2567 },
2568 );
2569 assert_ne!(a, b);
2570 assert!(a.layout_eq(&b));
2571 assert_eq!(a.layout_hash(), b.layout_hash());
2572 let mut c = b.clone();
2573 c.spans[0].style.font_size = px(15.0);
2574 assert!(!a.layout_eq(&c));
2575 assert_ne!(a.layout_hash(), c.layout_hash());
2576 }
2577
2578 #[test]
2579 fn measure_cache_is_bounded_and_promotes() {
2580 let mut cache = MeasureCache::default();
2581 cache.insert(1, Some(px(100.0)), size(px(1.0), px(1.0)));
2582 for i in 0..10_000u64 {
2583 cache.insert(1000 + i, None, Size::default());
2584 assert!(cache.get(1, Some(px(100.0))).is_some());
2586 assert!(cache.len() <= 2 * MeasureCache::GENERATION);
2587 }
2588 assert!(cache.get(1, Some(px(99.0))).is_none());
2589 assert!(cache.get(1000, None).is_none(), "cold entries are evicted");
2590 }
2591
2592 #[test]
2596 fn an_attachments_own_baseline_stands_on_the_lines() {
2597 let font = FontExtent::new(px(10.0), px(3.0), px(5.0));
2598 let a = TextAttachment {
2599 index: 4,
2600 width: px(30.0),
2601 height: px(20.0),
2602 };
2603 let mut alignments = AttachmentAlignments::default();
2604 assert_eq!(alignments.ascent(&a, font), px(20.0));
2605 alignments.set_baseline(4, Some(px(14.0)));
2606 assert!(!alignments.is_empty());
2607 assert_eq!(alignments.baseline(4), Some(px(14.0)));
2608 assert_eq!(alignments.baseline(5), None);
2609 assert_eq!(alignments.ascent(&a, font), px(14.0));
2610 assert_eq!(alignments.extent(&a, font), (px(14.0), px(6.0)));
2611 alignments.set_baseline(4, Some(px(25.0)));
2613 assert_eq!(alignments.extent(&a, font), (px(20.0), px(0.0)));
2614 alignments.set_baseline(4, Some(px(14.0)));
2615 alignments.set(4, VerticalAlign::TextTop);
2616 assert_eq!(alignments.ascent(&a, font), px(10.0));
2617 alignments.set(4, VerticalAlign::Baseline);
2618 alignments.set_baseline(4, None);
2619 assert!(alignments.is_empty());
2620 let text = AttributedText::default();
2622 let plain = alignments.layout_hash(&text);
2623 alignments.set_baseline(4, Some(px(14.0)));
2624 assert_ne!(alignments.layout_hash(&text), plain);
2625 }
2626
2627 #[test]
2628 fn attachments_sit_in_their_line_by_vertical_align() {
2629 let font = FontExtent::new(px(10.0), px(3.0), px(5.0));
2632 let at = || TextAttachment {
2633 index: 0,
2634 width: px(8.0),
2635 height: px(20.0),
2636 };
2637 let place = |align| {
2638 let a = at();
2639 (a.ascent(font, align), a.extent(font, align))
2640 };
2641 assert_eq!(
2643 place(VerticalAlign::Baseline),
2644 (px(20.0), (px(20.0), px(0.0)))
2645 );
2646 assert_eq!(
2648 place(VerticalAlign::TextTop),
2649 (px(10.0), (px(10.0), px(10.0)))
2650 );
2651 assert_eq!(
2653 place(VerticalAlign::TextBottom),
2654 (px(17.0), (px(17.0), px(3.0)))
2655 );
2656 assert_eq!(
2658 place(VerticalAlign::Middle),
2659 (px(12.5), (px(12.5), px(7.5)))
2660 );
2661 let small = TextAttachment {
2663 height: px(4.0),
2664 ..at()
2665 };
2666 assert_eq!(small.ascent(font, VerticalAlign::TextTop), px(10.0));
2667 assert_eq!(
2668 small.extent(font, VerticalAlign::TextTop),
2669 (px(10.0), px(0.0))
2670 );
2671 let small = TextAttachment {
2672 height: px(2.0),
2673 ..at()
2674 };
2675 assert_eq!(small.ascent(font, VerticalAlign::TextBottom), px(-1.0));
2676 assert_eq!(
2677 small.extent(font, VerticalAlign::TextBottom),
2678 (px(0.0), px(3.0))
2679 );
2680 }
2681
2682 #[test]
2685 fn approx_engine_has_its_first_baseline_at_its_first_lines_bottom() {
2686 let engine = ApproxTextEngine;
2687 let mut t = AttributedText::default();
2688 t.push(
2689 "a long line\nand another",
2690 ResolvedTextStyle {
2691 font_size: px(10.0),
2692 ..ResolvedTextStyle::default()
2693 },
2694 );
2695 let prepared = engine.prepare(&t);
2696 let layout = engine.layout(&prepared, engine.measure(&prepared, None));
2697 let line = engine.lines(&layout).remove(0);
2698 for width in [px(20.0), px(1000.0)] {
2699 assert_eq!(
2700 engine.first_baseline(&prepared, width),
2701 Some(line.y + line.ascender)
2702 );
2703 }
2704 assert_eq!(engine.first_baseline(&prepared, px(20.0)), Some(px(12.0)));
2705 }
2706
2707 #[test]
2708 fn approx_engine_honors_line_height_and_multiple() {
2709 let engine = ApproxTextEngine;
2710 let mut explicit = AttributedText::default();
2711 explicit.push(
2712 "ab\ncd",
2713 ResolvedTextStyle {
2714 font_size: px(10.0),
2715 line_height: px(24.0),
2716 ..ResolvedTextStyle::default()
2717 },
2718 );
2719 let prepared = engine.prepare(&explicit);
2720 let measured = engine.measure(&prepared, None);
2721 assert_eq!(measured, size(px(11.0), px(48.0)));
2722 let laid = engine.layout(&prepared, measured);
2723 let line = engine.lines(&laid).remove(0);
2724 assert_eq!(line.height, px(24.0));
2726 assert_eq!(line.ascender, px(18.0));
2727 assert_eq!(line.descender, px(6.0));
2728 assert_eq!(engine.first_baseline(&prepared, px(50.0)), Some(px(18.0)));
2729 assert_eq!(
2730 engine.first_baseline(&prepared, px(50.0)),
2731 Some(line.y + line.ascender)
2732 );
2733
2734 let mut multiple = AttributedText::default();
2735 multiple.push(
2736 "ab",
2737 ResolvedTextStyle {
2738 font_size: px(10.0),
2739 line_height_multiple: 2.0,
2740 ..ResolvedTextStyle::default()
2741 },
2742 );
2743 let mp = engine.prepare(&multiple);
2744 assert_eq!(engine.measure(&mp, None), size(px(11.0), px(20.0)));
2745
2746 let mut mixed = AttributedText::default();
2748 mixed.push(
2749 "a",
2750 ResolvedTextStyle {
2751 font_size: px(10.0),
2752 line_height: px(16.0),
2753 ..ResolvedTextStyle::default()
2754 },
2755 );
2756 mixed.push(
2757 "b",
2758 ResolvedTextStyle {
2759 font_size: px(12.0),
2760 line_height: px(30.0),
2761 ..ResolvedTextStyle::default()
2762 },
2763 );
2764 let mp_mixed = engine.prepare(&mixed);
2765 assert_eq!(engine.measure(&mp_mixed, None).height, px(30.0));
2766
2767 let mut mixed_fonts = AttributedText::default();
2770 mixed_fonts.push(
2771 "a",
2772 ResolvedTextStyle {
2773 font_size: px(10.0),
2774 ..ResolvedTextStyle::default()
2775 },
2776 );
2777 mixed_fonts.push(
2778 "b",
2779 ResolvedTextStyle {
2780 font_size: px(20.0),
2781 ..ResolvedTextStyle::default()
2782 },
2783 );
2784 let mp_fonts = engine.prepare(&mixed_fonts);
2785 assert_eq!(engine.measure(&mp_fonts, None), size(px(22.0), px(24.0)));
2786 assert_eq!(engine.first_baseline(&mp_fonts, px(50.0)), Some(px(24.0)));
2787
2788 assert_eq!(
2791 engine.measure(&ApproxPrepared::default(), None),
2792 engine.measure(&engine.prepare(&AttributedText::default()), None)
2793 );
2794 assert_eq!(
2795 ResolvedTextStyle {
2796 font_size: Points::ZERO,
2797 ..ResolvedTextStyle::default()
2798 }
2799 .approx_line_height(),
2800 px(1.2)
2801 );
2802 }
2803
2804 #[test]
2805 fn approx_engine_places_aligned_attachments() {
2806 let engine = ApproxTextEngine;
2807 let style = ResolvedTextStyle {
2808 font_size: px(10.0),
2809 ..ResolvedTextStyle::default()
2810 };
2811 let y = |align| {
2812 let mut t = AttributedText::default();
2813 t.push("ab", style);
2814 let mut alignments = AttachmentAlignments::default();
2815 alignments.push(&mut t, size(px(8.0), px(6.0)), align, style);
2816 let prepared = engine.prepare_aligned(&t, &alignments);
2817 let layout = engine.layout(&prepared, size(px(100.0), px(12.0)));
2818 engine.attachments(&layout)[0].map(|p| (p.x, p.y))
2819 };
2820 assert_eq!(y(VerticalAlign::Baseline), Some((px(11.0), px(6.0))));
2822 assert_eq!(y(VerticalAlign::TextTop), Some((px(11.0), px(0.0))));
2823 assert_eq!(y(VerticalAlign::TextBottom), Some((px(11.0), px(6.0))));
2824 assert_eq!(y(VerticalAlign::Middle), Some((px(11.0), px(6.5))));
2825 }
2826
2827 #[test]
2828 fn approx_engine_places_attachments_on_the_lines_they_wrap_to() {
2829 let engine = ApproxTextEngine;
2830 let style = ResolvedTextStyle {
2831 font_size: px(10.0),
2832 ..ResolvedTextStyle::default()
2833 };
2834 let place = |text: &str, width: f32, max_lines: u32| {
2837 let mut t = AttributedText::default();
2838 t.push(text, style);
2839 t.push_attachment(size(px(8.0), px(6.0)), style);
2840 t.push("z", style);
2841 t.max_lines = max_lines;
2842 let prepared = engine.prepare(&t);
2843 let measured = engine.measure(&prepared, Some(px(width)));
2844 let layout = engine.layout(&prepared, size(px(width), measured.height));
2845 engine.attachments(&layout)[0].map(|p| (p.x, p.y))
2846 };
2847 assert_eq!(place("abcd", 100.0, 0), Some((px(22.0), px(6.0))));
2849 assert_eq!(place("abcdefghij", 22.0, 0), Some((px(11.0), px(30.0))));
2852 assert_eq!(place("abcdefghij\nab", 22.0, 0), Some((px(11.0), px(42.0))));
2854 assert_eq!(place("abcdefghij", 22.0, 2), None);
2856 assert_eq!(place("a😀b", 100.0, 0), Some((px(16.5), px(6.0))));
2858 }
2859
2860 fn line(start: u32, end: u32, y: f32) -> TextLine {
2861 TextLine {
2862 start,
2863 end,
2864 x: px(0.0),
2865 y: px(y),
2866 width: px((end - start) as f32 * 10.0),
2867 height: px(20.0),
2868 ..TextLine::default()
2869 }
2870 }
2871
2872 #[test]
2873 fn caret_positions_take_their_line_by_affinity() {
2874 let lines = [line(0, 4, 0.0), line(4, 9, 20.0), line(9, 9, 40.0)];
2877 let at = |o, a| TextPosition::new(o, a).line(&lines);
2878 assert_eq!(at(4, Affinity::Upstream), Some(0));
2879 assert_eq!(at(4, Affinity::Downstream), Some(1));
2880 assert_eq!(at(0, Affinity::Upstream), Some(0));
2881 assert_eq!(at(9, Affinity::Upstream), Some(1));
2882 assert_eq!(at(9, Affinity::Downstream), Some(2));
2883 assert_eq!(at(50, Affinity::Downstream), Some(2));
2884 assert_eq!(TextPosition::default().line(&[]), None);
2885 }
2886
2887 struct LinesOnly(Vec<TextLine>);
2889
2890 impl TextEngine for LinesOnly {
2891 type Prepared = ();
2892
2893 fn prepare(&self, _: &AttributedText) {}
2894
2895 fn measure(&self, (): &(), _: Option<Points>) -> Size<Points> {
2896 Size::default()
2897 }
2898
2899 fn layout(&self, (): &(), _: Size<Points>) -> TextLayout {
2900 TextLayout(Arc::new(()))
2901 }
2902
2903 fn lines(&self, _: &TextLayout) -> Vec<TextLine> {
2904 self.0.clone()
2905 }
2906 }
2907
2908 #[test]
2909 fn line_only_engines_estimate_hits_carets_and_ranges() {
2910 let engine = LinesOnly(vec![line(0, 4, 0.0), line(4, 8, 20.0)]);
2911 let layout = engine.layout(&(), Size::default());
2912 let end = engine.hit_test(&layout, point(px(70.0), px(5.0)));
2914 assert_eq!(end, TextPosition::new(4, Affinity::Upstream));
2915 assert_eq!(
2916 engine.caret_rect(&layout, end),
2917 Some(Bounds::new(
2918 point(px(40.0), px(0.0)),
2919 size(px(0.0), px(20.0))
2920 ))
2921 );
2922 assert_eq!(
2923 engine.caret_rect(&layout, TextPosition::new(4, Affinity::Downstream)),
2924 Some(Bounds::new(
2925 point(px(0.0), px(20.0)),
2926 size(px(0.0), px(20.0))
2927 ))
2928 );
2929 let below = engine.hit_test(&layout, point(px(16.0), px(90.0)));
2931 assert_eq!(below, TextPosition::new(6, Affinity::Downstream));
2932 let mut rects = Vec::new();
2933 engine.range_rects(&layout, 2..6, &mut rects);
2934 assert_eq!(
2935 rects,
2936 [
2937 Bounds::new(point(px(20.0), px(0.0)), size(px(20.0), px(20.0))),
2938 Bounds::new(point(px(0.0), px(20.0)), size(px(20.0), px(20.0))),
2939 ]
2940 );
2941 rects.clear();
2942 engine.range_rects(&layout, 3..3, &mut rects);
2943 assert!(rects.is_empty());
2944 }
2945
2946 #[test]
2947 fn approx_engine_hit_tests_whole_characters() {
2948 let engine = ApproxTextEngine;
2949 let mut t = AttributedText::default();
2950 t.push(
2952 "a😀b",
2953 ResolvedTextStyle {
2954 font_size: px(10.0),
2955 ..ResolvedTextStyle::default()
2956 },
2957 );
2958 let layout = engine.layout(&engine.prepare(&t), size(px(100.0), px(12.0)));
2959 assert_eq!(engine.lines(&layout)[0].end, 4);
2960 let hit = |x| engine.hit_test(&layout, point(px(x), px(6.0))).offset;
2961 assert_eq!([hit(-3.0), hit(5.0), hit(11.5), hit(99.0)], [0, 1, 3, 4]);
2962 let caret_x = |o| {
2963 engine
2964 .caret_rect(&layout, TextPosition::new(o, Affinity::Downstream))
2965 .map(|b| b.origin.x)
2966 };
2967 assert_eq!(caret_x(2), Some(px(5.5)));
2969 assert_eq!(caret_x(3), Some(px(11.0)));
2970 assert_eq!(caret_x(9), Some(px(16.5)));
2971 let mut rects = Vec::new();
2972 engine.range_rects(&layout, 1..3, &mut rects);
2973 assert_eq!(
2974 rects,
2975 [Bounds::new(
2976 point(px(5.5), px(0.0)),
2977 size(px(5.5), px(12.0))
2978 )]
2979 );
2980 }
2981
2982 #[test]
2983 fn woff_and_woff2_fonts_decompress_to_the_font_they_hold() {
2984 let ttf: &[u8] =
2985 include_bytes!("../../../tests/compat/cases/layout/fonts/Pacifico-Regular.ttf");
2986 let face = |data: &[u8]| {
2987 use skrifa::{MetadataProvider as _, raw::TableProvider as _};
2988 let font = parse_font(data).expect("a font");
2989 let family = font_name(&font, skrifa::raw::types::NameId::FAMILY_NAME);
2990 (
2991 family,
2992 font.maxp().expect("maxp").num_glyphs(),
2993 font.charmap().map('P'),
2994 )
2995 };
2996 let original = face(ttf);
2997 assert_eq!(original.0.as_deref(), Some("Pacifico"));
2998 assert!(matches!(font_data(ttf), Ok(std::borrow::Cow::Borrowed(_))));
3000 for wrapped in [
3001 &include_bytes!("../../../tests/compat/cases/layout/fonts/Pacifico-Regular.woff")[..],
3002 &include_bytes!("../../../tests/compat/cases/layout/fonts/Pacifico-Regular.woff2")[..],
3003 ] {
3004 let data = font_data(wrapped).expect("decompressed");
3005 assert_eq!(face(&data), original);
3006 }
3007 assert!(font_data(b"wOF2 and nothing else").is_err());
3008 assert_eq!(font_family(ttf).as_deref(), Ok("Pacifico"));
3009 assert_eq!(
3010 font_family(include_bytes!(
3011 "../../../tests/compat/cases/layout/fonts/Pacifico-Regular.woff2"
3012 ))
3013 .as_deref(),
3014 Ok("Pacifico")
3015 );
3016 assert!(font_family(b"not a font").is_err());
3017 }
3018
3019 #[test]
3020 fn keep_font_keeps_each_file_once() {
3021 let mut fonts = Vec::new();
3022 assert!(keep_font(&mut fonts, b"a"));
3023 assert!(!keep_font(&mut fonts, b"a"));
3024 assert!(keep_font(&mut fonts, b"b"));
3025 assert_eq!(fonts, [b"a".to_vec(), b"b".to_vec()]);
3026 }
3027
3028 fn forged_woff(length: u32) -> Vec<u8> {
3030 let mut data = Vec::new();
3031 data.extend(b"wOFF\0\x01\0\0");
3032 data.extend(68u32.to_be_bytes()); data.extend(1u16.to_be_bytes()); data.extend([0; 2]); data.extend(length.saturating_add(28).to_be_bytes()); data.extend([0; 24]); data.extend(b"glyf");
3038 data.extend(64u32.to_be_bytes()); data.extend(4u32.to_be_bytes()); data.extend(length.to_be_bytes()); data.extend([0; 4]); data.extend([0x78, 0x9c, 0x03, 0x00]); data
3044 }
3045
3046 #[test]
3047 fn a_woff_font_declaring_more_than_a_font_holds_is_refused_before_it_decompresses() {
3048 let forged = forged_woff(u32::MAX);
3049 let error = font_data(&forged).expect_err("refused");
3050 assert!(error.contains("declare"), "{error}");
3051 let error = font_data(&forged_woff(1024)).expect_err("refused");
3054 assert!(error.contains("does not decompress"), "{error}");
3055 assert!(matches!(woff_tables_size(&forged[..56]), Ok(None)));
3057 assert!(font_data(&forged[..56]).is_err());
3058 }
3059
3060 #[test]
3061 fn a_woff_font_whose_tables_share_data_larger_than_they_are_is_refused() {
3062 let mut forged = Vec::new();
3066 forged.extend(b"wOFF\0\x01\0\0");
3067 forged.extend(92u32.to_be_bytes()); forged.extend(2u16.to_be_bytes()); forged.extend([0; 2]); forged.extend(44u32.to_be_bytes()); forged.extend([0; 24]); for tag in [b"cmap", b"glyf"] {
3073 forged.extend(tag);
3074 forged.extend(84u32.to_be_bytes()); forged.extend(8u32.to_be_bytes()); forged.extend(4u32.to_be_bytes()); forged.extend([0; 4]); }
3079 forged.extend([0; 8]);
3080 assert_eq!(forged.len(), 92);
3081 let error = font_data(&forged).expect_err("refused");
3082 assert!(error.contains("larger compressed"), "{error}");
3083 }
3084
3085 #[test]
3086 fn a_woff2_font_declaring_more_than_its_size_allows_is_refused() {
3087 let mut forged = Vec::new();
3091 forged.extend(b"wOF2\0\x01\0\0");
3092 forged.extend(60u32.to_be_bytes()); forged.extend(1u16.to_be_bytes()); forged.extend([0; 2]); forged.extend(u32::MAX.to_be_bytes()); forged.extend(4u32.to_be_bytes()); forged.extend([0; 24]); forged.push(0); forged.extend([0x8f, 0xff, 0xff, 0xff, 0x7f]); forged.extend([0; 6]); assert_eq!(forged.len(), 60);
3102 assert!(font_data(&forged).is_err());
3103 }
3104
3105 #[test]
3106 fn em_font_size_is_of_the_inherited_size() {
3107 let parent = ResolvedTextStyle {
3108 font_size: px(16.0),
3109 ..ResolvedTextStyle::default()
3110 };
3111 let span = TextStyle {
3112 font_size_em: Some(0.875),
3113 letter_spacing_em: Some(0.1),
3114 ..TextStyle::default()
3115 };
3116 let r = parent.inherit(&span);
3117 assert_eq!(r.font_size, px(14.0));
3118 assert!((r.letter_spacing.0 - 1.4).abs() < 1e-4);
3120 }
3121}
3122
3123pub(crate) trait GeometryEngine {
3125 fn geometry_lines(&self, layout: &TextLayout) -> Vec<TextLine>;
3126 fn geometry_hit_test(&self, layout: &TextLayout, point: Point<Points>) -> TextPosition;
3127 fn geometry_caret_rect(
3128 &self,
3129 layout: &TextLayout,
3130 position: TextPosition,
3131 ) -> Option<Bounds<Points>>;
3132 fn geometry_range_rects(
3133 &self,
3134 layout: &TextLayout,
3135 range: Range<u32>,
3136 out: &mut Vec<Bounds<Points>>,
3137 );
3138}
3139
3140impl<M: TextEngine> GeometryEngine for M {
3141 fn geometry_lines(&self, layout: &TextLayout) -> Vec<TextLine> {
3142 self.lines(layout)
3143 }
3144 fn geometry_hit_test(&self, layout: &TextLayout, point: Point<Points>) -> TextPosition {
3145 self.hit_test(layout, point)
3146 }
3147 fn geometry_caret_rect(
3148 &self,
3149 layout: &TextLayout,
3150 position: TextPosition,
3151 ) -> Option<Bounds<Points>> {
3152 self.caret_rect(layout, position)
3153 }
3154 fn geometry_range_rects(
3155 &self,
3156 layout: &TextLayout,
3157 range: Range<u32>,
3158 out: &mut Vec<Bounds<Points>>,
3159 ) {
3160 self.range_rects(layout, range, out);
3161 }
3162}
3163
3164#[derive(Clone)]
3174pub struct TextGeometry {
3175 engine: std::rc::Rc<dyn GeometryEngine>,
3176 layout: TextLayout,
3177 text: Arc<AttributedText>,
3178 spacers: Arc<[u32]>,
3180}
3181
3182impl TextGeometry {
3183 pub(crate) fn new(
3184 engine: std::rc::Rc<dyn GeometryEngine>,
3185 layout: TextLayout,
3186 text: Arc<AttributedText>,
3187 spacers: &[u32],
3188 ) -> Self {
3189 let mut spacers = spacers.to_vec();
3190 spacers.sort_unstable();
3191 spacers.dedup();
3192 Self {
3193 engine,
3194 layout,
3195 text,
3196 spacers: spacers.into(),
3197 }
3198 }
3199
3200 fn to_source(&self, t: u32) -> u32 {
3202 t - self.spacers.partition_point(|&s| s < t) as u32
3203 }
3204
3205 fn to_laid(&self, s: u32, upstream: bool) -> u32 {
3209 let mut t = s;
3210 for &at in self.spacers.iter() {
3211 if at < t || (at == t && !upstream) {
3212 t += 1;
3213 } else {
3214 break;
3215 }
3216 }
3217 t
3218 }
3219
3220 pub fn lines(&self) -> Vec<TextLine> {
3222 let units: Vec<u16> = self.text.text.encode_utf16().collect();
3223 let mut lines = self.engine.geometry_lines(&self.layout);
3224 for line in &mut lines {
3225 let (start, end) = (line.start as usize, (line.end as usize).min(units.len()));
3226 if start < end {
3227 let mut text = String::from_utf16_lossy(&units[start..end]);
3228 if self
3229 .spacers
3230 .iter()
3231 .any(|&s| s >= line.start && s < line.end)
3232 {
3233 let mut k = line.start;
3236 text = text
3237 .chars()
3238 .filter(|c| {
3239 let at = k;
3240 k += c.len_utf16() as u32;
3241 !(*c == ATTACHMENT_CHAR && self.spacers.binary_search(&at).is_ok())
3242 })
3243 .collect();
3244 }
3245 line.text = text;
3246 }
3247 line.start = self.to_source(line.start);
3248 line.end = self.to_source(line.end);
3249 }
3250 lines
3251 }
3252
3253 pub fn hit_test(&self, point: Point<Points>) -> TextPosition {
3255 let p = self.engine.geometry_hit_test(&self.layout, point);
3256 TextPosition::new(self.to_source(p.offset), p.affinity)
3257 }
3258
3259 pub fn caret_rect(&self, position: TextPosition) -> Option<Bounds<Points>> {
3261 let upstream = position.affinity == Affinity::Upstream;
3262 let t = self.to_laid(position.offset, upstream);
3263 self.engine
3264 .geometry_caret_rect(&self.layout, TextPosition::new(t, position.affinity))
3265 }
3266
3267 pub fn range_rects(&self, range: Range<u32>) -> Vec<Bounds<Points>> {
3269 let mut out = Vec::new();
3270 if range.start < range.end {
3271 let r = self.to_laid(range.start, false)..self.to_laid(range.end, true);
3272 self.engine.geometry_range_rects(&self.layout, r, &mut out);
3273 }
3274 out
3275 }
3276}
3277
3278thread_local! {
3279 static GEOMETRY: std::cell::RefCell<Option<TextGeometry>> =
3280 const { std::cell::RefCell::new(None) };
3281}
3282
3283pub(crate) struct GeometryScope(Option<TextGeometry>);
3287
3288impl GeometryScope {
3289 pub(crate) fn enter(geometry: TextGeometry) -> Self {
3290 Self(GEOMETRY.with(|g| g.replace(Some(geometry))))
3291 }
3292
3293 pub(crate) fn current() -> Option<TextGeometry> {
3295 GEOMETRY.with(|g| g.borrow().clone())
3296 }
3297}
3298
3299impl Drop for GeometryScope {
3300 fn drop(&mut self) {
3301 let previous = self.0.take();
3302 GEOMETRY.with(|g| *g.borrow_mut() = previous);
3303 }
3304}
3305
3306impl fmt::Debug for TextGeometry {
3307 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3308 f.debug_struct("TextGeometry")
3309 .field("spacers", &self.spacers)
3310 .finish_non_exhaustive()
3311 }
3312}
3313
3314#[cfg(test)]
3315mod geometry_tests {
3316 use super::*;
3317
3318 fn padded() -> Arc<AttributedText> {
3320 let mut text = AttributedText {
3321 text: format!("a{ATTACHMENT_CHAR}bc{ATTACHMENT_CHAR}d"),
3322 ..AttributedText::default()
3323 };
3324 for index in [1, 4] {
3325 text.attachments.push(TextAttachment {
3326 index,
3327 width: Points(4.0),
3328 height: Points::ZERO,
3329 });
3330 }
3331 Arc::new(text)
3332 }
3333
3334 fn geometry() -> TextGeometry {
3335 let engine = ApproxTextEngine;
3336 let text = padded();
3337 let prepared = engine.prepare(&text);
3338 let layout = engine.layout(&prepared, size(Points(1000.0), Points(100.0)));
3339 TextGeometry::new(std::rc::Rc::new(ApproxTextEngine), layout, text, &[1, 4])
3340 }
3341
3342 #[test]
3343 fn padding_placeholders_are_not_offsets() {
3344 let g = geometry();
3345 let lines = g.lines();
3346 assert_eq!(lines.len(), 1);
3347 assert_eq!(lines[0].text, "abcd");
3348 assert_eq!((lines[0].start, lines[0].end), (0, 4));
3349 let at = |o| {
3350 g.caret_rect(TextPosition::new(o, Affinity::Downstream))
3351 .unwrap()
3352 .origin
3353 .x
3354 };
3355 let laid = |o: u32| {
3356 ApproxTextEngine
3357 .caret_rect(&g.layout, TextPosition::new(o, Affinity::Downstream))
3358 .unwrap()
3359 .origin
3360 .x
3361 };
3362 assert_eq!(at(1), laid(2));
3364 assert_eq!(at(3), laid(5));
3365 let p = point(laid(5), Points(1.0));
3367 assert_eq!(g.hit_test(p).offset, 3);
3368 let r = g.range_rects(1..3);
3370 assert_eq!(r.len(), 1);
3371 assert_eq!(r[0].origin.x, laid(2));
3372 }
3373
3374 #[test]
3375 fn zero_height_user_attachments_stay_in_source_offsets() {
3376 let engine = ApproxTextEngine;
3377 let mut text = AttributedText {
3378 text: format!("a{ATTACHMENT_CHAR}b"),
3379 ..AttributedText::default()
3380 };
3381 text.attachments.push(TextAttachment {
3382 index: 1,
3383 width: Points(40.0),
3384 height: Points::ZERO,
3385 });
3386 let text = Arc::new(text);
3387 let prepared = engine.prepare(&text);
3388 let layout = engine.layout(&prepared, size(Points(1000.0), Points(100.0)));
3389 let g = TextGeometry::new(std::rc::Rc::new(ApproxTextEngine), layout, text, &[]);
3391 let lines = g.lines();
3392 assert_eq!(lines.len(), 1);
3393 assert_eq!((lines[0].start, lines[0].end), (0, 3));
3394 assert_eq!(lines[0].text, format!("a{ATTACHMENT_CHAR}b"));
3395 let r = g.range_rects(1..2);
3396 assert_eq!(r.len(), 1);
3397 assert_eq!(r[0].size.width, Points(40.0));
3398 }
3399
3400 #[test]
3401 fn approx_engine_hit_test_and_range_rects_respect_attachment_widths() {
3402 let engine = ApproxTextEngine;
3403 let style = ResolvedTextStyle {
3404 font_size: px(10.0 / 0.55),
3405 ..ResolvedTextStyle::default()
3406 };
3407 let mut t = AttributedText::default();
3408 t.push("ab", style);
3409 t.push_attachment(size(px(80.0), px(16.0)), style);
3410 t.push("cd", style);
3411 let prepared = engine.prepare(&t);
3412 let layout = engine.layout(&prepared, size(px(300.0), px(20.0)));
3413
3414 let x = |o| {
3415 engine
3416 .caret_rect(&layout, TextPosition::new(o, Affinity::Downstream))
3417 .map(|b| b.origin.x.0.round())
3418 };
3419 assert_eq!(x(0), Some(0.0));
3420 assert_eq!(x(2), Some(20.0));
3421 assert_eq!(x(3), Some(100.0));
3422 assert_eq!(x(5), Some(120.0));
3423
3424 let mut rects = Vec::new();
3425 engine.range_rects(&layout, 2..3, &mut rects);
3426 assert_eq!(rects.len(), 1);
3427 assert_eq!(rects[0].origin.x.0.round(), 20.0);
3428 assert_eq!(rects[0].size.width.0.round(), 80.0);
3429
3430 assert_eq!(engine.hit_test(&layout, point(px(19.0), px(5.0))).offset, 2);
3431 assert_eq!(engine.hit_test(&layout, point(px(50.0), px(5.0))).offset, 2);
3432 assert_eq!(engine.hit_test(&layout, point(px(70.0), px(5.0))).offset, 3);
3433 assert_eq!(
3434 engine.hit_test(&layout, point(px(101.0), px(5.0))).offset,
3435 3
3436 );
3437 assert_eq!(
3438 engine.hit_test(&layout, point(px(118.0), px(5.0))).offset,
3439 5
3440 );
3441 }
3442}