1use cosmic_text::{
8 Attrs, Buffer, CacheKeyFlags, Ellipsize, EllipsizeHeightLimit, FontSystem, Metrics, Shaping,
9 Style as FontStyle, SwashContent, Weight, Wrap,
10};
11use rustc_hash::FxHashMap;
12
13use crate::atlas::GlyphAtlas;
14use crate::color::Color;
15use crate::display::{Clip, ClipId, Quad, QuadKind};
16use crate::geom::{Rect, Size, Vec2};
17use crate::key::Key;
18use crate::resources::Resources;
19use crate::retain::Kept;
20use crate::spec::{FontFamily, TextStyle, TextWrap, UnderlineStyle};
21use crate::tree::TextId;
22use crate::value::Value;
23
24pub(crate) struct Raster {
31 ctx: swash::scale::ScaleContext,
32 axes: FxHashMap<cosmic_text::fontdb::ID, Option<crate::weights::WghtAxis>>,
34 pub(crate) subpixel: bool,
38}
39
40impl Raster {
41 fn new() -> Self {
42 Self {
43 ctx: swash::scale::ScaleContext::new(),
44 axes: FxHashMap::default(),
45 subpixel: false,
46 }
47 }
48
49 fn image(
61 &mut self,
62 fs: &mut FontSystem,
63 key: cosmic_text::CacheKey,
64 format: swash::zeno::Format,
65 ) -> Option<cosmic_text::SwashImage> {
66 use swash::scale::{Render, Source, StrikeWith};
67 use swash::zeno::{Angle, Transform, Vector};
68 let font = fs.get_font(key.font_id, key.font_weight)?;
69 let swash_font = font.as_swash();
70 let axis = self
71 .axes
72 .entry(key.font_id)
73 .or_insert_with(|| {
74 let weight = fs.db().face(key.font_id).map_or(400, |face| face.weight.0);
75 crate::weights::WghtAxis::read(swash_font, weight)
76 })
77 .as_ref();
78 let size = f32::from_bits(key.font_size_bits);
79 let face_weight = f32::from(key.font_weight.0);
80 let bold = key.flags.contains(crate::weights::SYNTHETIC_BOLD);
81 let asked = if bold {
82 f32::from(Weight::BOLD.0)
83 } else {
84 face_weight
85 };
86 let at = axis.map(|axis| axis.coordinate(asked));
87 let embolden = bold
90 && match (axis, at) {
91 (Some(axis), Some(at)) => at <= axis.coordinate(face_weight),
92 _ => true,
93 };
94 let mut scaler = self
95 .ctx
96 .builder(swash_font)
97 .size(size)
98 .hint(!key.flags.contains(CacheKeyFlags::DISABLE_HINTING));
99 if let Some(at) = at {
100 scaler = scaler.normalized_coords(
101 swash_font
102 .variations()
103 .normalized_coords([(swash::Tag::from_be_bytes(*b"wght"), at)]),
104 );
105 }
106 let mut scaler = scaler.build();
107 let offset = if key.flags.contains(CacheKeyFlags::PIXEL_FONT) {
108 Vector::new(key.x_bin.as_float().round(), key.y_bin.as_float().round())
109 } else {
110 Vector::new(key.x_bin.as_float(), key.y_bin.as_float())
111 };
112 Render::new(&[
113 Source::ColorOutline(0),
114 Source::ColorBitmap(StrikeWith::BestFit),
115 Source::Outline,
116 ])
117 .format(format)
118 .offset(offset)
119 .embolden(if embolden {
120 crate::weights::embolden_strength(size)
121 } else {
122 0.0
123 })
124 .transform(
125 key.flags
126 .contains(CacheKeyFlags::FAKE_ITALIC)
127 .then(|| Transform::skew(Angle::from_degrees(14.0), Angle::from_degrees(0.0))),
128 )
129 .render(&mut scaler, key.glyph_id)
130 }
131}
132
133pub(crate) fn raster_glyph(
135 key: cosmic_text::CacheKey,
136 fs: &mut FontSystem,
137 raster: &mut Raster,
138 atlas: &mut crate::atlas::GlyphAtlas,
139) -> Option<crate::atlas::GlyphSlot> {
140 atlas.get_or_insert(key, || {
141 let format = if raster.subpixel {
142 swash::zeno::Format::Subpixel
143 } else {
144 swash::zeno::Format::Alpha
145 };
146 let image = raster.image(fs, key, format)?;
147 if image.placement.width == 0 || image.placement.height == 0 {
148 return None;
149 }
150 let (data, is_color, subpixel) = match image.content {
151 SwashContent::Mask => {
152 let mut rgba = Vec::with_capacity(image.data.len() * 4);
153 for &a in image.data.iter() {
154 rgba.extend_from_slice(&[255, 255, 255, a]);
155 }
156 (rgba, false, false)
157 }
158 SwashContent::Color => (image.data.to_vec(), true, false),
159 SwashContent::SubpixelMask => {
160 let mut rgba = image.data.to_vec();
164 for px in rgba.as_chunks_mut::<4>().0 {
165 px[3] = px[0].max(px[1]).max(px[2]);
166 }
167 (rgba, false, true)
168 }
169 };
170 Some(crate::atlas::RasterGlyph {
171 w: image.placement.width,
172 h: image.placement.height,
173 left: image.placement.left,
174 top: image.placement.top,
175 color: is_color,
176 subpixel,
177 data,
178 })
179 })
180}
181
182pub(crate) fn glyph_kind(slot: &crate::atlas::GlyphSlot) -> QuadKind {
184 if slot.color_glyph {
185 QuadKind::GlyphColor
186 } else if slot.subpixel {
187 QuadKind::GlyphSubpixel
188 } else {
189 QuadKind::GlyphMask
190 }
191}
192
193pub const DEFAULT_TEXT_CACHE_BYTES: usize = 64 << 20;
199
200const ENTRY_BASE_BYTES: usize = 4096;
210const ENTRY_GLYPH_BYTES: usize = 480;
211
212pub const LONG_LINE_BYTES: usize = 4096;
218const CHUNK_BYTES: usize = 1024;
223const LONG_SALT: u64 = 0x5f5f_6c6f_6e67_5f5f;
226const COPY_SALT: u64 = 0x5f5f_636f_7079_5f5f;
229
230const EVICT_TO_NUMERATOR: usize = 3;
234const EVICT_TO_DENOMINATOR: usize = 4;
235
236pub(crate) struct CachedText {
237 buffer: Buffer,
238 content: String,
241 wrap: Option<f32>,
243 intrinsic: Size,
245 max_lines: usize,
248 clamp_w: bool,
251 last_used: u64,
252 bytes: usize,
254 glyphs: Vec<GlyphTemplate>,
257 deco: Vec<DecoTemplate>,
261 span_deco: Vec<SpanDeco>,
264 glyphs_built_for: Option<(Option<u32>, u64)>,
266 claimed: u64,
271 claimed_wrap: Option<f32>,
272 breaks_anywhere: bool,
275 min_content: Option<f32>,
279}
280
281struct GlyphTemplate {
282 x: f32,
283 y: f32,
284 w: f32,
285 h: f32,
286 uv: [u32; 4],
287 kind: QuadKind,
288 color: Option<Color>,
290 byte: u32,
293}
294
295struct DecoTemplate {
297 x: f32,
298 y: f32,
299 w: f32,
300 h: f32,
301 color: Option<Color>,
304 under: bool,
306 style: UnderlineStyle,
309 radius: f32,
312}
313
314#[derive(Clone, Copy, Debug)]
323pub(crate) struct JoinBg {
324 pub quad: u32,
325 pub radius: f32,
326 pub outer: ClipId,
327 pub own: Option<(f32, f32)>,
328}
329
330#[derive(Clone, Copy, Default)]
332struct SpanDeco {
333 underline: bool,
334 underline_color: Option<Color>,
335 underline_style: UnderlineStyle,
336 strikethrough: bool,
337 bg: Option<Color>,
338 bg_radius: f32,
341}
342
343impl SpanDeco {
344 fn of_style(style: &TextStyle) -> Self {
345 Self {
346 underline: style.underline,
347 underline_color: style.underline_color,
348 underline_style: style.underline_style,
349 strikethrough: style.strikethrough,
350 bg: None,
351 bg_radius: 0.0,
352 }
353 }
354
355 fn any(&self) -> bool {
356 self.underline || self.strikethrough || self.bg.is_some()
357 }
358}
359
360#[derive(Clone, Copy, Debug)]
363pub struct Span<'a> {
364 pub text: &'a str,
365 pub color: Option<Color>,
366 pub bold: bool,
367 pub italic: bool,
368 pub underline: bool,
370 pub underline_color: Option<Color>,
372 pub underline_style: UnderlineStyle,
374 pub strikethrough: bool,
376 pub bg: Option<Color>,
379 pub bg_radius: f32,
386 pub family: Option<FontFamily>,
393 pub size: Option<f32>,
399}
400
401impl<'a> Span<'a> {
402 pub fn new(text: &'a str) -> Self {
403 Self {
404 text,
405 color: None,
406 bold: false,
407 italic: false,
408 underline: false,
409 underline_color: None,
410 underline_style: UnderlineStyle::Solid,
411 strikethrough: false,
412 bg: None,
413 bg_radius: 0.0,
414 family: None,
415 size: None,
416 }
417 }
418
419 pub fn family(mut self, family: FontFamily) -> Self {
421 self.family = Some(family);
422 self
423 }
424
425 pub fn mono(self) -> Self {
433 self.family(FontFamily::Mono)
434 }
435
436 pub fn size(mut self, px: f32) -> Self {
439 self.size = (px.is_finite() && px > 0.0).then_some(px);
440 self
441 }
442
443 pub fn color(mut self, c: Color) -> Self {
444 self.color = Some(c);
445 self
446 }
447
448 pub fn bold(mut self) -> Self {
449 self.bold = true;
450 self
451 }
452
453 pub fn italic(mut self) -> Self {
454 self.italic = true;
455 self
456 }
457
458 pub fn underline(mut self) -> Self {
459 self.underline = true;
460 self
461 }
462
463 pub fn underline_color(mut self, c: Color) -> Self {
465 self.underline = true;
466 self.underline_color = Some(c);
467 self
468 }
469
470 pub fn underline_style(mut self, s: UnderlineStyle) -> Self {
472 self.underline = true;
473 self.underline_style = s;
474 self
475 }
476
477 pub fn strikethrough(mut self) -> Self {
478 self.strikethrough = true;
479 self
480 }
481
482 pub fn bg(mut self, c: Color) -> Self {
483 self.bg = Some(c);
484 self
485 }
486
487 pub fn bg_radius(mut self, r: f32) -> Self {
490 self.bg_radius = r.max(0.0);
491 self
492 }
493
494 fn attrs_only(&self) -> SpanAttrs {
497 SpanAttrs {
498 color: self.color,
499 bold: self.bold,
500 italic: self.italic,
501 underline: self.underline,
502 underline_color: self.underline_color,
503 underline_style: self.underline_style,
504 strikethrough: self.strikethrough,
505 bg: self.bg,
506 bg_radius: self.bg_radius,
507 family: self.family,
508 size: self.size,
509 }
510 }
511
512 fn attrs<'r>(
513 &self,
514 family: cosmic_text::Family<'r>,
515 weights: crate::weights::Weights,
516 ) -> Attrs<'r> {
517 let mut attrs = weights.apply(Attrs::new().family(family), self.bold);
521 if self.italic {
522 attrs = attrs.style(FontStyle::Italic);
523 }
524 if let Some(c) = self.color {
525 attrs = attrs.color(cosmic_text::Color::rgba(
526 (c.r * 255.0) as u8,
527 (c.g * 255.0) as u8,
528 (c.b * 255.0) as u8,
529 (c.a * 255.0) as u8,
530 ));
531 }
532 attrs
533 }
534}
535
536#[derive(Clone, Copy)]
540struct SpanAttrs {
541 color: Option<Color>,
542 bold: bool,
543 italic: bool,
544 underline: bool,
545 underline_color: Option<Color>,
546 underline_style: UnderlineStyle,
547 strikethrough: bool,
548 bg: Option<Color>,
549 bg_radius: f32,
550 family: Option<FontFamily>,
551 size: Option<f32>,
552}
553
554impl SpanAttrs {
555 fn span<'a>(&self, text: &'a str) -> Span<'a> {
556 Span {
557 text,
558 color: self.color,
559 bold: self.bold,
560 italic: self.italic,
561 underline: self.underline,
562 underline_color: self.underline_color,
563 underline_style: self.underline_style,
564 strikethrough: self.strikethrough,
565 bg: self.bg,
566 bg_radius: self.bg_radius,
567 family: self.family,
568 size: self.size,
569 }
570 }
571}
572
573#[derive(Clone)]
576struct OwnedSpan {
577 start: usize,
578 end: usize,
579 attrs: SpanAttrs,
580}
581
582fn chunk_spans<'a>(
587 content: &'a str,
588 spans: &[OwnedSpan],
589 start: usize,
590 end: usize,
591) -> Vec<Span<'a>> {
592 let first = spans.partition_point(|s| s.end <= start);
593 spans[first..]
594 .iter()
595 .take_while(|s| s.start < end)
596 .filter_map(|s| {
597 let (a, b) = (s.start.max(start), s.end.min(end));
598 (a < b).then(|| s.attrs.span(&content[a..b]))
599 })
600 .collect()
601}
602
603struct FrameText {
604 cache_key: u64,
605 color: Color,
606}
607
608pub(crate) enum Entry {
616 Run(CachedText),
617 Long(LongLine),
618}
619
620impl Entry {
621 pub(crate) fn content(&self) -> &str {
622 match self {
623 Entry::Run(e) => &e.content,
624 Entry::Long(l) => &l.content,
625 }
626 }
627
628 fn last_used(&self) -> u64 {
629 match self {
630 Entry::Run(e) => e.last_used,
631 Entry::Long(l) => l.last_used,
632 }
633 }
634
635 fn touch(&mut self, frame_no: u64) {
636 match self {
637 Entry::Run(e) => e.last_used = frame_no,
638 Entry::Long(l) => l.last_used = frame_no,
639 }
640 }
641
642 fn bytes(&self) -> usize {
644 match self {
645 Entry::Run(e) => e.bytes,
646 Entry::Long(l) => l.bytes,
647 }
648 }
649
650 fn run(&self) -> Option<&CachedText> {
651 match self {
652 Entry::Run(e) => Some(e),
653 Entry::Long(_) => None,
654 }
655 }
656
657 fn run_mut(&mut self) -> Option<&mut CachedText> {
658 match self {
659 Entry::Run(e) => Some(e),
660 Entry::Long(_) => None,
661 }
662 }
663
664 fn long(&self) -> Option<&LongLine> {
665 match self {
666 Entry::Long(l) => Some(l),
667 Entry::Run(_) => None,
668 }
669 }
670
671 fn long_mut(&mut self) -> Option<&mut LongLine> {
672 match self {
673 Entry::Long(l) => Some(l),
674 Entry::Run(_) => None,
675 }
676 }
677}
678
679#[derive(Clone)]
683struct Chunk {
684 start: usize,
685 end: usize,
686 key: u64,
687 width: Option<f32>,
689 tab: Option<(f32, f32)>,
695 rows: Vec<RowStart>,
698}
699
700#[derive(Clone, Copy, Debug)]
704struct RowStart {
705 byte: u32,
706 x: f32,
707}
708
709#[derive(Clone)]
722pub(crate) struct LongLine {
723 content: String,
724 spans: Vec<OwnedSpan>,
728 style: TextStyle,
731 wrap: TextWrap,
737 wrap_w: Option<f32>,
740 starts: Vec<(u32, f32)>,
745 chunks: Vec<Chunk>,
746 prefix: Vec<f32>,
749 line_h: f32,
751 avg: f32,
754 last_used: u64,
755 claimed: u64,
758 laid_rows: u32,
765 asked_rows: u32,
766 bytes: usize,
767}
768
769impl LongLine {
770 fn chunk_at(&self, x: f32) -> usize {
772 match self.prefix[1..].partition_point(|&p| p <= x) {
773 i if i >= self.chunks.len() => self.chunks.len().saturating_sub(1),
774 i => i,
775 }
776 }
777
778 fn chunk_of_byte(&self, byte: usize) -> usize {
780 match self.chunks.partition_point(|c| c.end <= byte) {
781 i if i >= self.chunks.len() => self.chunks.len().saturating_sub(1),
782 i => i,
783 }
784 }
785
786 fn width(&self) -> f32 {
787 self.prefix.last().copied().unwrap_or(0.0)
788 }
789
790 fn rows(&self) -> u32 {
792 match self.starts.last() {
793 Some(&(r, _)) if self.wrap_w.is_some() => r + 1,
794 _ => 1,
795 }
796 }
797
798 fn chunks_on_rows(&self, ra: u32, rb: u32) -> Option<(usize, usize)> {
801 let n = self.chunks.len();
802 if n == 0 || self.starts.len() != n + 1 {
803 return None;
804 }
805 let first = self.starts[1..].partition_point(|s| s.0 < ra);
806 let last = self.starts[..n].partition_point(|s| s.0 <= rb);
807 (first < last).then_some((first, last - 1))
808 }
809
810 fn reprefix(&mut self) {
817 let mut at = 0.0f32;
818 self.prefix.clear();
819 self.prefix.push(0.0);
820 for c in &self.chunks {
821 at = match (c.width, c.tab) {
822 (Some(_), Some((tab_x, every))) => next_tab_stop(at + tab_x, every),
823 (Some(w), None) => at + w,
824 (None, _) => at + (c.end - c.start) as f32 * self.avg,
825 };
826 self.prefix.push(at);
827 }
828 }
829
830 fn tab_shift(&self, i: usize) -> f32 {
833 let c = &self.chunks[i];
834 match (c.width, c.tab) {
835 (Some(w), Some(_)) => self.prefix[i + 1] - self.prefix[i] - w,
836 _ => 0.0,
837 }
838 }
839
840 fn end_shift(&self, i: usize, local: usize) -> f32 {
845 let c = &self.chunks[i];
846 match local >= c.end - c.start {
847 true => self.tab_shift(i),
848 false => 0.0,
849 }
850 }
851
852 fn placed_tab_hit(&self, i: usize, x: f32) -> Option<usize> {
859 let c = &self.chunks[i];
860 let (tab_x, _) = c.tab?;
861 c.width?;
862 if x < tab_x {
863 return None;
864 }
865 let drawn_end = self.prefix[i + 1] - self.prefix[i];
866 Some(match x < (tab_x + drawn_end) / 2.0 {
867 true => c.end - 1,
868 false => c.end,
869 })
870 }
871}
872
873fn next_tab_stop(x: f32, every: f32) -> f32 {
879 if every <= 0.0 {
880 return x;
881 }
882 (((x + 1.0 / 16.0) / every).floor() + 1.0) * every
883}
884
885fn chunk_ranges(content: &str) -> Vec<(usize, usize)> {
902 use unicode_segmentation::UnicodeSegmentation;
903 if content.len() < LONG_LINE_BYTES {
904 return vec![(0, content.len())];
905 }
906 let bytes = content.as_bytes();
907 let mut out = Vec::with_capacity(content.len() / CHUNK_BYTES + 1);
908 let mut start = 0usize;
909 while start < content.len() {
910 let mut window_end = (start + CHUNK_BYTES).min(content.len());
914 while !content.is_char_boundary(window_end) {
915 window_end -= 1;
916 }
917 let window = &content[start..window_end];
918 let mut from = (CHUNK_BYTES / 2).min(window.len());
920 while !window.is_char_boundary(from) {
921 from += 1;
922 }
923 let off_stops = start > 0 && bytes[start - 1] != b'\t';
927 let early_tab = match off_stops {
928 true => window[..from].find('\t'),
929 false => None,
930 };
931 let end = if let Some(t) = early_tab {
932 start + t + 1
933 } else if window_end == content.len() && !(off_stops && window[from..].contains('\t')) {
934 window_end
935 } else {
936 let (mut first_tab, mut last_tab, mut space) = (None, None, None);
940 for (i, c) in window[from..].char_indices() {
941 if c.is_whitespace() {
942 let end = from + i + c.len_utf8();
943 space = Some(end);
944 if c == '\t' {
945 first_tab = first_tab.or(Some(end));
946 last_tab = Some(end);
947 }
948 }
949 }
950 let tab = if off_stops { first_tab } else { last_tab };
951 match tab.or(space) {
952 Some(i) => start + i,
953 None => {
954 let mut cut = 0usize;
956 for (i, _) in window.grapheme_indices(true) {
957 if i == 0 {
958 continue;
959 }
960 cut = i;
961 }
962 if cut == 0 { window_end } else { start + cut }
963 }
964 }
965 };
966 out.push((start, end));
967 start = end;
968 }
969 out
970}
971
972pub(crate) const PLACE_ANCESTORS: usize = 4;
977
978pub(crate) struct Ancestry {
982 pub(crate) keys: [Key; PLACE_ANCESTORS],
983 pub(crate) depth: usize,
984 pub(crate) none_at: Option<usize>,
985}
986
987pub(crate) struct TextPlace {
992 pub(crate) key: Key,
993 ancestors: [Key; PLACE_ANCESTORS],
995 depth: u8,
996 none_at: u8,
1002 cache_key: u64,
1003 origin: Vec2,
1005 scope: Option<Key>,
1009 drawn: bool,
1017}
1018
1019impl TextPlace {
1020 fn answers_to(&self, key: Key) -> bool {
1021 if self.key == key {
1022 return true;
1023 }
1024 self.ancestors[..self.depth as usize]
1028 .iter()
1029 .position(|k| *k == key)
1030 .is_some_and(|d| d <= self.none_at as usize)
1031 }
1032}
1033
1034pub(crate) struct ScopeRun<'a> {
1040 pub place: &'a TextPlace,
1041 pub text: &'a Entry,
1043 pub base: usize,
1044}
1045
1046impl ScopeRun<'_> {
1047 pub(crate) fn span(&self) -> (usize, usize) {
1050 (self.base, self.base + self.text.content().len())
1051 }
1052}
1053
1054#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1067pub struct TextHit {
1068 pub byte: usize,
1069 pub line: u32,
1070}
1071
1072impl TextHit {
1073 pub fn to_value(self) -> Value {
1075 Value::map([
1076 ("byte", Value::Int(self.byte as i64)),
1077 ("line", Value::Int(self.line as i64)),
1078 ])
1079 }
1080}
1081
1082#[derive(Clone, Copy, Debug, Default, PartialEq)]
1087pub struct TextMetrics {
1088 pub width: f32,
1089 pub height: f32,
1090 pub lines: u32,
1092}
1093
1094impl TextMetrics {
1095 pub fn to_value(self) -> Value {
1097 Value::map([
1098 ("width", Value::float(self.width)),
1099 ("height", Value::float(self.height)),
1100 ("lines", Value::Int(self.lines as i64)),
1101 ])
1102 }
1103}
1104
1105pub struct TextSystem {
1113 raster: Raster,
1114 joins: Vec<JoinBg>,
1117 entries: FxHashMap<u64, Entry>,
1120 bytes: usize,
1123 budget: usize,
1124 frame: Kept<FrameText>,
1129 places: Kept<TextPlace>,
1133 scale: f32,
1134 frame_no: u64,
1135 owed: bool,
1138}
1139
1140pub(crate) fn cosmic_features(f: &crate::spec::FontFeatures) -> cosmic_text::FontFeatures {
1143 let mut out = cosmic_text::FontFeatures::new();
1144 for (tag, value) in f.iter() {
1145 out.set(cosmic_text::FeatureTag::new(tag), value);
1146 }
1147 out
1148}
1149
1150#[cfg(target_os = "macos")]
1161const DEFAULT_FAMILIES: [&[&str]; 3] = [
1162 &["Helvetica Neue", "Helvetica"],
1163 &["Times New Roman", "Times"],
1164 &["SF Mono", "Menlo", "Monaco"],
1165];
1166#[cfg(target_os = "windows")]
1167const DEFAULT_FAMILIES: [&[&str]; 3] = [
1168 &["Segoe UI", "Arial"],
1169 &["Times New Roman"],
1170 &["Cascadia Mono", "Consolas", "Courier New"],
1171];
1172#[cfg(not(any(target_os = "macos", target_os = "windows")))]
1173const DEFAULT_FAMILIES: [&[&str]; 3] = [
1174 &["DejaVu Sans", "Noto Sans", "Liberation Sans", "Ubuntu"],
1175 &["DejaVu Serif", "Noto Serif", "Liberation Serif"],
1176 &[
1177 "DejaVu Sans Mono",
1178 "Noto Sans Mono",
1179 "Liberation Mono",
1180 "Ubuntu Mono",
1181 ],
1182];
1183
1184fn first_installed<'a>(db: &cosmic_text::fontdb::Database, list: &[&'a str]) -> Option<&'a str> {
1187 list.iter().copied().find(|name| {
1188 db.faces()
1189 .any(|face| face.families.iter().any(|(f, _)| f == name))
1190 })
1191}
1192
1193pub(crate) fn new_font_system() -> (FontSystem, std::sync::Arc<SystemFonts>) {
1207 let system = system_fonts();
1208 let fonts = font_system_over(system.locale.clone(), system.db.clone(), &[]);
1209 (fonts, system)
1210}
1211
1212pub(crate) fn font_system_over(
1217 locale: String,
1218 db: cosmic_text::fontdb::Database,
1219 first: &[String],
1220) -> FontSystem {
1221 FontSystem::new_with_locale_and_db_and_fallback(locale, db, AppFallback::new(first))
1222}
1223
1224pub(crate) struct AppFallback {
1231 platform: cosmic_text::PlatformFallback,
1232 first: &'static [&'static str],
1233 common: &'static [&'static str],
1234 scripts: std::sync::Mutex<
1237 rustc_hash::FxHashMap<(unicode_script::Script, String), &'static [&'static str]>,
1238 >,
1239}
1240
1241fn keep(names: Vec<&'static str>) -> &'static [&'static str] {
1244 static LISTS: std::sync::Mutex<Vec<&'static [&'static str]>> =
1245 std::sync::Mutex::new(Vec::new());
1246 let mut lists = LISTS.lock().unwrap_or_else(|e| e.into_inner());
1247 if let Some(&kept) = lists.iter().find(|l| ***l == names[..]) {
1248 return kept;
1249 }
1250 let kept: &'static [&'static str] = Box::leak(names.into_boxed_slice());
1251 lists.push(kept);
1252 kept
1253}
1254
1255fn keep_name(name: &str) -> &'static str {
1256 static NAMES: std::sync::Mutex<Vec<&'static str>> = std::sync::Mutex::new(Vec::new());
1257 let mut names = NAMES.lock().unwrap_or_else(|e| e.into_inner());
1258 if let Some(&kept) = names.iter().find(|n| **n == name) {
1259 return kept;
1260 }
1261 let kept: &'static str = Box::leak(name.to_string().into_boxed_str());
1262 names.push(kept);
1263 kept
1264}
1265
1266impl AppFallback {
1267 pub(crate) fn new(first: &[String]) -> Self {
1268 use cosmic_text::Fallback;
1269 let platform = cosmic_text::PlatformFallback;
1270 let first = keep(first.iter().map(|n| keep_name(n)).collect());
1271 let common = keep(
1272 first
1273 .iter()
1274 .chain(platform.common_fallback())
1275 .copied()
1276 .collect(),
1277 );
1278 Self {
1279 platform,
1280 first,
1281 common,
1282 scripts: Default::default(),
1283 }
1284 }
1285}
1286
1287impl cosmic_text::Fallback for AppFallback {
1288 fn common_fallback(&self) -> &[&'static str] {
1289 self.common
1290 }
1291
1292 fn forbidden_fallback(&self) -> &[&'static str] {
1293 self.platform.forbidden_fallback()
1294 }
1295
1296 fn script_fallback(&self, script: unicode_script::Script, locale: &str) -> &[&'static str] {
1297 let theirs = self.platform.script_fallback(script, locale);
1298 if self.first.is_empty() {
1299 return theirs;
1300 }
1301 let mut scripts = self.scripts.lock().unwrap_or_else(|e| e.into_inner());
1302 scripts
1303 .entry((script, locale.to_string()))
1304 .or_insert_with(|| keep(self.first.iter().chain(theirs).copied().collect()))
1305 }
1306}
1307
1308pub(crate) struct SystemFonts {
1312 locale: String,
1313 db: cosmic_text::fontdb::Database,
1314 pub(crate) faces: rustc_hash::FxHashSet<(std::path::PathBuf, u32)>,
1316}
1317
1318static SYSTEM: std::sync::Mutex<Option<std::sync::Arc<SystemFonts>>> = std::sync::Mutex::new(None);
1320
1321pub(crate) fn system_fonts() -> std::sync::Arc<SystemFonts> {
1325 let mut held = SYSTEM.lock().unwrap_or_else(|e| e.into_inner());
1326 held.get_or_insert_with(|| std::sync::Arc::new(scan_system_fonts()))
1327 .clone()
1328}
1329
1330pub(crate) fn rescan_system_fonts() -> std::sync::Arc<SystemFonts> {
1333 let fresh = std::sync::Arc::new(scan_system_fonts());
1334 *SYSTEM.lock().unwrap_or_else(|e| e.into_inner()) = Some(fresh.clone());
1335 fresh
1336}
1337
1338fn scan_system_fonts() -> SystemFonts {
1339 let (locale, db) = FontSystem::new().into_locale_and_db();
1340 SystemFonts::from_db(locale, db)
1341}
1342
1343impl SystemFonts {
1344 pub(crate) fn from_db(locale: String, mut db: cosmic_text::fontdb::Database) -> Self {
1347 let all: Vec<_> = db.faces().map(|face| face.id).collect();
1348 keep_measurable(&mut db, all);
1349 pin_default_families(&mut db);
1350 let faces = db.faces().filter_map(face_file).collect();
1351 Self { locale, db, faces }
1352 }
1353
1354 #[cfg(test)]
1356 pub(crate) fn db(&self) -> &cosmic_text::fontdb::Database {
1357 &self.db
1358 }
1359
1360 #[cfg(test)]
1361 pub(crate) fn locale(&self) -> &str {
1362 &self.locale
1363 }
1364}
1365
1366pub(crate) fn face_file(face: &cosmic_text::fontdb::FaceInfo) -> Option<(std::path::PathBuf, u32)> {
1369 use cosmic_text::fontdb::Source;
1370 match &face.source {
1371 Source::File(path) | Source::SharedFile(path, _) => Some((path.clone(), face.index)),
1372 Source::Binary(_) => None,
1373 }
1374}
1375
1376pub(crate) fn pin_default_families(db: &mut cosmic_text::fontdb::Database) {
1380 let [sans, serif, mono] = DEFAULT_FAMILIES;
1381 if let Some(name) = first_installed(db, sans) {
1382 db.set_sans_serif_family(name);
1383 }
1384 if let Some(name) = first_installed(db, serif) {
1385 db.set_serif_family(name);
1386 }
1387 if let Some(name) = first_installed(db, mono) {
1388 db.set_monospace_family(name);
1389 }
1390}
1391
1392#[cfg(test)]
1396fn font_system_with(locale: String, db: cosmic_text::fontdb::Database) -> FontSystem {
1397 let system = SystemFonts::from_db(locale, db);
1398 FontSystem::new_with_locale_and_db(system.locale, system.db)
1399}
1400
1401pub(crate) fn measurable(data: &[u8], index: u32) -> bool {
1412 use cosmic_text::skrifa::raw::{FontRef, TableProvider};
1413 let Ok(font) = FontRef::from_index(data, index) else {
1414 return false;
1415 };
1416 font.head()
1417 .is_ok_and(|head| (16..=16384).contains(&head.units_per_em()))
1418 && font.hhea().is_ok_and(|hhea| hhea.number_of_h_metrics() > 0)
1419 && font.hmtx().is_ok()
1420}
1421
1422const FILES_PER_CHECKER: usize = 64;
1425
1426pub(crate) fn keep_measurable(
1438 db: &mut cosmic_text::fontdb::Database,
1439 ids: Vec<cosmic_text::fontdb::ID>,
1440) -> Vec<cosmic_text::fontdb::ID> {
1441 use cosmic_text::fontdb::{ID, Source};
1442 let mut by_file = FxHashMap::<&std::path::Path, Vec<ID>>::default();
1444 let mut groups = Vec::new();
1445 for &id in &ids {
1446 match db.face(id).map(|face| &face.source) {
1447 Some(Source::File(path) | Source::SharedFile(path, _)) => {
1448 by_file.entry(path).or_default().push(id);
1449 }
1450 Some(Source::Binary(_)) => groups.push(vec![id]),
1451 None => {}
1452 }
1453 }
1454 groups.extend(by_file.into_values());
1455 let db_ref = &*db;
1456 let unmeasurable_in = |groups: &[Vec<ID>]| -> Vec<ID> {
1457 let mut out = Vec::new();
1458 for group in groups {
1459 let read = db_ref.with_face_data(group[0], |data, _| {
1460 group
1461 .iter()
1462 .filter(|&&id| {
1463 db_ref
1464 .face(id)
1465 .is_none_or(|face| !measurable(data, face.index))
1466 })
1467 .copied()
1468 .collect::<Vec<_>>()
1469 });
1470 out.extend(read.unwrap_or_else(|| group.clone()));
1471 }
1472 out
1473 };
1474 let checkers = std::thread::available_parallelism()
1475 .map_or(1, |n| n.get())
1476 .min(groups.len().div_ceil(FILES_PER_CHECKER));
1477 let unmeasurable = if checkers <= 1 {
1478 unmeasurable_in(&groups)
1479 } else {
1480 let per = groups.len().div_ceil(checkers);
1481 std::thread::scope(|scope| {
1482 let parts: Vec<_> = groups
1483 .chunks(per)
1484 .map(|part| {
1485 let spawned = std::thread::Builder::new()
1486 .name("kui-font-check".into())
1487 .spawn_scoped(scope, move || unmeasurable_in(part));
1488 (part, spawned.ok())
1489 })
1490 .collect();
1491 let mut out = Vec::new();
1492 for (part, checker) in parts {
1493 out.extend(match checker {
1494 Some(checker) => checker
1495 .join()
1496 .unwrap_or_else(|panic| std::panic::resume_unwind(panic)),
1497 None => unmeasurable_in(part),
1499 });
1500 }
1501 out
1502 })
1503 };
1504 for &id in &unmeasurable {
1505 db.remove_face(id);
1506 }
1507 ids.into_iter()
1508 .filter(|id| !unmeasurable.contains(id))
1509 .collect()
1510}
1511
1512pub(crate) fn default_families(fs: &FontSystem) -> [&str; 3] {
1516 let db = fs.db();
1517 [
1518 db.family_name(&cosmic_text::Family::SansSerif),
1519 db.family_name(&cosmic_text::Family::Serif),
1520 db.family_name(&cosmic_text::Family::Monospace),
1521 ]
1522}
1523
1524impl TextSystem {
1525 pub fn new() -> Self {
1526 Self {
1527 raster: Raster::new(),
1528 joins: Vec::new(),
1529 entries: FxHashMap::default(),
1530 bytes: 0,
1531 budget: DEFAULT_TEXT_CACHE_BYTES,
1532 frame: Kept::default(),
1533 places: Kept::default(),
1534 scale: 1.0,
1535 frame_no: 0,
1536 owed: false,
1537 }
1538 }
1539
1540 pub(crate) fn take_owed(&mut self) -> bool {
1543 std::mem::take(&mut self.owed)
1544 }
1545
1546 pub(crate) fn take_joins(&mut self) -> Vec<JoinBg> {
1549 std::mem::take(&mut self.joins)
1550 }
1551
1552 pub(crate) fn raster_mut(&mut self) -> &mut Raster {
1554 &mut self.raster
1555 }
1556
1557 pub(crate) fn subpixel(&self) -> bool {
1558 self.raster.subpixel
1559 }
1560
1561 pub(crate) fn set_subpixel(&mut self, on: bool) -> bool {
1564 let changed = self.raster.subpixel != on;
1565 self.raster.subpixel = on;
1566 changed
1567 }
1568
1569 pub fn budget(&self) -> usize {
1572 self.budget
1573 }
1574
1575 pub fn set_budget(&mut self, bytes: usize) {
1578 self.budget = bytes;
1579 }
1580
1581 pub fn bytes(&self) -> usize {
1583 self.bytes
1584 }
1585
1586 pub fn len(&self) -> usize {
1589 self.entries.len() - self.long_lines()
1590 }
1591
1592 pub fn long_lines(&self) -> usize {
1594 self.entries.values().filter(|e| e.long().is_some()).count()
1595 }
1596
1597 pub fn is_empty(&self) -> bool {
1598 self.len() == 0
1599 }
1600
1601 fn evict_to_budget(&mut self, fs: &mut FontSystem) {
1608 if self.bytes <= self.budget {
1609 return;
1610 }
1611 let floor = self.budget / EVICT_TO_DENOMINATOR * EVICT_TO_NUMERATOR;
1612 let drawn_last_frame = self.frame_no.saturating_sub(1);
1613 let mut order: Vec<(u64, u64)> = self
1618 .entries
1619 .iter()
1620 .filter(|(_, e)| e.last_used() < drawn_last_frame)
1621 .map(|(k, e)| (e.last_used(), *k))
1622 .collect();
1623 order.sort_unstable();
1624 for (_, key) in order {
1625 if self.bytes <= floor {
1626 break;
1627 }
1628 let freed = self.entries.remove(&key).map(|e| e.bytes());
1629 self.bytes -= freed.unwrap_or(0);
1630 }
1631 fs.shape_run_cache.trim(0);
1640 }
1641
1642 pub(crate) fn begin_frame(
1646 &mut self,
1647 fs: &mut FontSystem,
1648 scale: f32,
1649 keep_prev: bool,
1650 frame_no: u64,
1651 ) {
1652 self.joins.clear();
1653 if (scale - self.scale).abs() > f32::EPSILON {
1655 self.entries.clear();
1656 self.bytes = 0;
1657 }
1658 self.scale = scale;
1659 self.frame.begin(keep_prev);
1660 self.places.begin(true);
1663 self.frame_no = frame_no;
1665 if let Some(cutoff) = crate::retain::sweep_cutoff(self.frame_no) {
1666 let mut freed = 0usize;
1667 self.entries.retain(|_, e| {
1668 let keep = e.last_used() >= cutoff;
1669 if !keep {
1670 freed += e.bytes();
1671 }
1672 keep
1673 });
1674 self.bytes -= freed;
1675 fs.shape_run_cache.trim(2);
1678 }
1679 self.evict_to_budget(fs);
1683 }
1684
1685 pub(crate) fn forget_shaped(&mut self) {
1688 self.entries.clear();
1689 self.bytes = 0;
1690 }
1691
1692 fn insert(&mut self, key: u64, entry: Entry) {
1694 self.bytes += entry.bytes();
1695 if let Some(old) = self.entries.insert(key, entry) {
1696 self.bytes -= old.bytes();
1697 }
1698 }
1699
1700 fn run(&self, key: u64) -> Option<&CachedText> {
1702 self.entries.get(&key)?.run()
1703 }
1704
1705 fn run_mut(&mut self, key: u64) -> Option<&mut CachedText> {
1706 self.entries.get_mut(&key)?.run_mut()
1707 }
1708
1709 fn long(&self, key: u64) -> Option<&LongLine> {
1711 self.entries.get(&key)?.long()
1712 }
1713
1714 fn long_mut(&mut self, key: u64) -> Option<&mut LongLine> {
1715 self.entries.get_mut(&key)?.long_mut()
1716 }
1717
1718 pub(crate) fn style_key(content: &str, style: &TextStyle, scale: f32) -> u64 {
1719 let mut h = crate::key::mix_content(crate::key::FNV_OFFSET, content.as_bytes());
1722 let mut mix = |bytes: &[u8]| h = crate::key::fnv(h, bytes);
1723 mix(&style.size.to_bits().to_le_bytes());
1724 mix(&style.line_height.to_bits().to_le_bytes());
1725 mix(&scale.to_bits().to_le_bytes());
1726 mix(&[style.wrap as u8, style.ellipsis as u8]);
1727 mix(&style.max_lines.to_le_bytes());
1728 let (tag, font) = match style.family {
1729 FontFamily::Sans => (0u8, 0u64),
1730 FontFamily::Serif => (1, 0),
1731 FontFamily::Mono => (2, 0),
1732 FontFamily::Custom(id) => (3, id.to_ffi()),
1733 };
1734 mix(&[tag]);
1735 mix(&font.to_le_bytes());
1736 for (t, v) in style.features.iter() {
1737 mix(t);
1738 mix(&v.to_le_bytes());
1739 }
1740 mix(&[
1744 style.underline as u8,
1745 style.strikethrough as u8,
1746 style.underline_style as u8,
1747 style.underline_color.is_some() as u8,
1748 ]);
1749 if let Some(c) = style.underline_color {
1750 mix(&c.to_hex().to_le_bytes());
1751 }
1752 h
1753 }
1754
1755 fn intern(
1759 &mut self,
1760 content: &str,
1761 style: &TextStyle,
1762 res: &Resources,
1763 fs: &mut FontSystem,
1764 ) -> u64 {
1765 let key = Self::style_key(content, style, self.scale);
1766 self.intern_keyed(key, content, style, res, fs)
1767 }
1768
1769 fn intern_keyed(
1771 &mut self,
1772 key: u64,
1773 content: &str,
1774 style: &TextStyle,
1775 res: &Resources,
1776 fs: &mut FontSystem,
1777 ) -> u64 {
1778 let frame_no = self.frame_no;
1779 let scale = self.scale;
1780 if !self.entries.contains_key(&key) {
1781 let mut buffer = new_buffer(fs, style, scale);
1782 buffer.set_text(
1786 content,
1787 &res.weights_of(style.family).apply(
1788 Attrs::new()
1789 .family(res.family_of(style.family))
1790 .font_features(cosmic_features(&style.features)),
1791 false,
1792 ),
1793 Shaping::Advanced,
1794 None,
1795 );
1796 let entry = CachedText::new(
1797 buffer,
1798 content.to_string(),
1799 style,
1800 vec![SpanDeco::of_style(style)],
1801 fs,
1802 frame_no,
1803 );
1804 self.insert(key, Entry::Run(entry));
1805 }
1806 self.entries
1807 .get_mut(&key)
1808 .expect("just inserted")
1809 .touch(frame_no);
1810 key
1811 }
1812
1813 pub(crate) fn content(&self, id: TextId) -> &str {
1815 let key = self.frame[id.0 as usize].cache_key;
1816 self.entries.get(&key).map_or("", |e| e.content())
1817 }
1818
1819 pub(crate) fn access_runs(
1825 &self,
1826 id: TextId,
1827 src: crate::access::RunSource,
1828 run_no: &mut usize,
1829 out: &mut Vec<crate::access::AccessRun>,
1830 ) {
1831 use crate::access::{RowGlyphs, push_row_runs};
1832 let Some(ft) = self.frame.get(id.0 as usize) else {
1833 return;
1834 };
1835 let line = match self.entries.get(&ft.cache_key) {
1836 Some(Entry::Run(e)) => {
1837 crate::access::runs_of_buffer(&e.buffer, src, run_no, out);
1838 return;
1839 }
1840 Some(Entry::Long(line)) => line,
1841 None => return,
1842 };
1843 let whole = [RowStart { byte: 0, x: 0.0 }];
1844 for (i, c) in line.chunks.iter().enumerate() {
1845 let Some(run) = c
1846 .width
1847 .and_then(|_| self.run(c.key))
1848 .and_then(|e| e.buffer.layout_runs().next())
1849 else {
1850 continue;
1851 };
1852 let (rows, row0, head_x) = match (line.wrap_w, line.starts.get(i)) {
1855 (Some(_), Some(&(row0, head_x))) if !c.rows.is_empty() => {
1856 (&c.rows[..], row0, head_x)
1857 }
1858 (Some(_), _) => continue,
1859 (None, _) => (&whole[..], 0, line.prefix[i]),
1860 };
1861 for (r, rs) in rows.iter().enumerate() {
1862 let hi = rows.get(r + 1).map_or(usize::MAX, |n| n.byte as usize);
1863 let a = run.glyphs.partition_point(|g| g.start < rs.byte as usize);
1864 let b = run.glyphs.partition_point(|g| g.start < hi).max(a);
1865 if a == b {
1866 continue;
1867 }
1868 let last = i + 1 == line.chunks.len() && r + 1 == rows.len();
1869 push_row_runs(
1870 &RowGlyphs {
1871 glyphs: &run.glyphs[a..b],
1872 text: run.text,
1873 line: 0,
1874 top: (row0 as usize + r) as f32 * line.line_h,
1875 height: line.line_h,
1876 rtl: run.rtl,
1877 dx: if r == 0 { head_x } else { 0.0 } - rs.x,
1878 base: c.start,
1879 newline: last && src.newline_after_last,
1880 },
1881 &src,
1882 run_no,
1883 out,
1884 );
1885 }
1886 }
1887 }
1888
1889 pub(crate) fn prev_frame_text(&self, id: TextId) -> (u64, Color) {
1895 match self.frame.prev().get(id.0 as usize) {
1896 Some(t) => (t.cache_key, t.color),
1897 None => (0, Color::TRANSPARENT),
1898 }
1899 }
1900
1901 pub(crate) fn readd(&mut self, cache_key: u64, color: Color) -> Option<TextId> {
1907 let frame_no = self.frame_no;
1908 let e = self.entries.get_mut(&cache_key)?;
1909 e.touch(frame_no);
1910 let cache_key = if e.long().is_some() {
1911 self.claim_long(cache_key)
1912 } else {
1913 cache_key
1914 };
1915 self.frame.push(FrameText { cache_key, color });
1916 Some(TextId((self.frame.len() - 1) as u32))
1917 }
1918
1919 pub fn add(
1921 &mut self,
1922 content: &str,
1923 style: &TextStyle,
1924 res: &Resources,
1925 fs: &mut FontSystem,
1926 ) -> TextId {
1927 let key = self.intern_any(content, style, res, fs);
1930 let key = if could_be_long(content.len(), style) {
1931 self.claim_long(key)
1932 } else {
1933 key
1934 };
1935 self.frame.push(FrameText {
1936 cache_key: key,
1937 color: style.color_or_default(),
1938 });
1939 TextId((self.frame.len() - 1) as u32)
1940 }
1941
1942 #[inline(never)]
1951 fn claim_long(&mut self, key: u64) -> u64 {
1952 let frame_no = self.frame_no;
1953 let mut at = key;
1954 let mut n = 0u64;
1955 loop {
1956 match self.entries.get_mut(&at) {
1957 Some(Entry::Long(l)) if l.claimed != frame_no => {
1958 l.claimed = frame_no;
1959 l.last_used = frame_no;
1960 return at;
1961 }
1962 Some(Entry::Run(_)) if n == 0 => return key,
1964 Some(_) => {}
1965 None => {
1966 let Some(line) = self.long(key) else {
1967 return key;
1968 };
1969 let mut copy = line.clone();
1970 copy.claimed = frame_no;
1971 copy.last_used = frame_no;
1972 self.insert(at, Entry::Long(copy));
1973 return at;
1974 }
1975 }
1976 n += 1;
1977 at = crate::key::fnv(key ^ COPY_SALT, &n.to_le_bytes());
1978 }
1979 }
1980
1981 fn intern_any(
1987 &mut self,
1988 content: &str,
1989 style: &TextStyle,
1990 res: &Resources,
1991 fs: &mut FontSystem,
1992 ) -> u64 {
1993 if !could_be_long(content.len(), style) {
1994 return self.intern(content, style, res, fs);
1995 }
1996 let key = Self::style_key(content, style, self.scale);
1997 let long_key = key ^ LONG_SALT;
1998 let frame_no = self.frame_no;
1999 if let Some(e) = self.entries.get_mut(&long_key) {
2000 e.touch(frame_no);
2001 return long_key;
2002 }
2003 if let Some(e) = self.entries.get_mut(&key) {
2004 e.touch(frame_no);
2005 return key;
2006 }
2007 if has_line_break(content) || content.len() < LONG_LINE_BYTES && has_rtl(content) {
2008 self.intern_keyed(key, content, style, res, fs)
2009 } else {
2010 self.build_long(long_key, content.to_string(), Vec::new(), style, res, fs)
2011 }
2012 }
2013
2014 fn intern_rich_any(
2019 &mut self,
2020 spans: &[Span<'_>],
2021 base: &TextStyle,
2022 res: &Resources,
2023 fs: &mut FontSystem,
2024 ) -> u64 {
2025 let len: usize = spans.iter().map(|s| s.text.len()).sum();
2026 if !could_be_long(len, base) {
2027 return self.intern_rich(spans, base, res, fs);
2028 }
2029 let key = Self::rich_key(spans, base, self.scale);
2030 let long_key = key ^ LONG_SALT;
2031 let frame_no = self.frame_no;
2032 if let Some(e) = self.entries.get_mut(&long_key) {
2033 e.touch(frame_no);
2034 return long_key;
2035 }
2036 if let Some(e) = self.entries.get_mut(&key) {
2037 e.touch(frame_no);
2038 return key;
2039 }
2040 if spans
2043 .iter()
2044 .any(|s| has_line_break(s.text) || s.size.is_some())
2045 || len < LONG_LINE_BYTES && spans.iter().any(|s| has_rtl(s.text))
2046 {
2047 return self.intern_rich_keyed(key, spans, base, res, fs);
2048 }
2049 let mut content = String::with_capacity(len);
2050 let mut owned = Vec::with_capacity(spans.len());
2051 for s in spans {
2052 let start = content.len();
2053 content.push_str(s.text);
2054 owned.push(OwnedSpan {
2055 start,
2056 end: content.len(),
2057 attrs: s.attrs_only(),
2058 });
2059 }
2060 self.build_long(long_key, content, owned, base, res, fs)
2061 }
2062
2063 fn build_long(
2068 &mut self,
2069 key: u64,
2070 content: String,
2071 spans: Vec<OwnedSpan>,
2072 style: &TextStyle,
2073 res: &Resources,
2074 fs: &mut FontSystem,
2075 ) -> u64 {
2076 let frame_no = self.frame_no;
2077 let wrap = style.wrap;
2078 let style = &TextStyle {
2079 wrap: TextWrap::None,
2080 ..*style
2081 };
2082 let scale = self.scale;
2083 let chunks: Vec<Chunk> = chunk_ranges(&content)
2084 .into_iter()
2085 .map(|(start, end)| Chunk {
2086 start,
2087 end,
2088 key: if spans.is_empty() {
2089 Self::style_key(&content[start..end], style, scale)
2090 } else {
2091 Self::rich_key(&chunk_spans(&content, &spans, start, end), style, scale)
2092 },
2093 width: None,
2094 tab: None,
2095 rows: Vec::new(),
2096 })
2097 .collect();
2098 let (w0, line_h) = match chunks.first() {
2101 Some(c) => {
2102 let k = self.shape_chunk(&content, &spans, c.start, c.end, style, res, fs);
2103 let e = self.run(k).expect("just interned");
2104 (e.intrinsic.w, e.buffer.metrics().line_height)
2105 }
2106 None => (0.0, style.line_height * self.scale),
2107 };
2108 let avg = chunks
2109 .first()
2110 .map_or(0.0, |c| w0 / (c.end - c.start).max(1) as f32);
2111 let mut line = LongLine {
2112 content,
2113 spans,
2114 style: *style,
2115 wrap,
2116 wrap_w: None,
2117 starts: Vec::new(),
2118 chunks,
2119 prefix: Vec::new(),
2120 line_h,
2121 avg,
2122 last_used: frame_no,
2123 claimed: u64::MAX,
2124 laid_rows: 1,
2125 asked_rows: u32::MAX,
2126 bytes: 0,
2127 };
2128 if let Some(c) = line.chunks.first_mut() {
2129 c.width = Some(w0);
2130 }
2131 line.reprefix();
2132 line.bytes = ENTRY_BASE_BYTES
2133 + line.content.len()
2134 + line.chunks.len() * 48
2135 + line.spans.len() * std::mem::size_of::<OwnedSpan>();
2136 self.insert(key, Entry::Long(line));
2140 key
2141 }
2142
2143 #[allow(clippy::too_many_arguments)]
2147 fn shape_chunk(
2148 &mut self,
2149 content: &str,
2150 spans: &[OwnedSpan],
2151 start: usize,
2152 end: usize,
2153 style: &TextStyle,
2154 res: &Resources,
2155 fs: &mut FontSystem,
2156 ) -> u64 {
2157 if spans.is_empty() {
2158 self.intern(&content[start..end], style, res, fs)
2159 } else {
2160 let spans = chunk_spans(content, spans, start, end);
2161 self.intern_rich(&spans, style, res, fs)
2162 }
2163 }
2164
2165 fn ensure_chunk(&mut self, key: u64, i: usize, res: &Resources, fs: &mut FontSystem) -> bool {
2169 let (chunk_key, known) = {
2170 let c = &self.long(key).expect("a long line").chunks[i];
2171 (c.key, c.width)
2172 };
2173 let frame_no = self.frame_no;
2174 if known.is_some()
2175 && let Some(e) = self.run_mut(chunk_key)
2176 {
2177 e.last_used = frame_no;
2178 return false;
2179 }
2180 let (text, spans, style, off_stops) = {
2183 let line = self.long(key).expect("a long line");
2184 let c = &line.chunks[i];
2185 let first = line.spans.partition_point(|s| s.end <= c.start);
2186 let spans: Vec<OwnedSpan> = line.spans[first..]
2187 .iter()
2188 .take_while(|s| s.start < c.end)
2189 .map(|s| OwnedSpan {
2190 start: s.start.max(c.start) - c.start,
2191 end: s.end.min(c.end) - c.start,
2192 attrs: s.attrs,
2193 })
2194 .collect();
2195 let bytes = line.content.as_bytes();
2196 let off_stops = c.start > 0 && bytes[c.start - 1] != b'\t';
2197 (
2198 line.content[c.start..c.end].to_string(),
2199 spans,
2200 line.style,
2201 off_stops,
2202 )
2203 };
2204 let k = self.shape_chunk(&text, &spans, 0, text.len(), &style, res, fs);
2205 let w = self.run(k).expect("just interned").intrinsic.w;
2206 let tab = match off_stops && text.ends_with('\t') {
2207 true => self.chunk_tab(k, &text, &spans, &style, res, fs),
2208 false => None,
2209 };
2210 let line = self.long_mut(key).expect("just read");
2211 line.chunks[i].key = k;
2212 line.chunks[i].tab = tab;
2213 if line.chunks[i].width != Some(w) {
2214 line.chunks[i].width = Some(w);
2215 line.reprefix();
2216 }
2217 true
2218 }
2219
2220 #[inline(never)]
2226 #[allow(clippy::too_many_arguments)]
2227 fn chunk_tab(
2228 &mut self,
2229 chunk: u64,
2230 text: &str,
2231 spans: &[OwnedSpan],
2232 style: &TextStyle,
2233 res: &Resources,
2234 fs: &mut FontSystem,
2235 ) -> Option<(f32, f32)> {
2236 let at = text.len() - 1;
2237 let tab_x = {
2238 let run = self.run(chunk)?.buffer.layout_runs().next()?;
2239 if run.rtl {
2240 return None;
2241 }
2242 run.glyphs.iter().rev().find(|g| g.start == at)?.x
2243 };
2244 let alone = self.shape_chunk(text, spans, at, text.len(), style, res, fs);
2245 let every = self.run(alone)?.intrinsic.w;
2246 Some((tab_x, every))
2247 }
2248
2249 fn relayout_long(&mut self, key: u64, w: Option<f32>) {
2257 let Some(w) = w else {
2258 let line = self.long_mut(key).expect("a long line");
2259 line.wrap_w = None;
2260 line.starts.clear();
2261 for c in &mut line.chunks {
2262 c.rows.clear();
2263 }
2264 return;
2265 };
2266 let w = w.max(1.0);
2267 let line = self.long(key).expect("a long line");
2270 let mut starts = Vec::with_capacity(line.chunks.len() + 1);
2271 starts.push((0, 0.0));
2272 let (mut row, mut x) = (0u32, 0.0f32);
2273 let rows: Vec<Vec<RowStart>> = line
2274 .chunks
2275 .iter()
2276 .enumerate()
2277 .map(|(i, c)| {
2278 let shaped = c.width.and_then(|_| self.run(c.key));
2279 let rows = match shaped {
2280 Some(e) => {
2281 let text = &line.content[c.start..c.end];
2282 let (rows, end) = break_rows(&e.buffer, text, line.wrap, w, x);
2283 row += rows.len() as u32 - 1;
2284 x = end + line.tab_shift(i);
2288 rows
2289 }
2290 None => {
2291 let est = x + c
2292 .width
2293 .unwrap_or_else(|| (c.end - c.start) as f32 * line.avg);
2294 let added = (est / w).floor();
2295 row += added as u32;
2296 x = est - added * w;
2297 Vec::new()
2298 }
2299 };
2300 starts.push((row, x));
2301 rows
2302 })
2303 .collect();
2304 let line = self.long_mut(key).expect("a long line");
2305 line.wrap_w = Some(w);
2306 line.starts = starts;
2307 for (c, rows) in line.chunks.iter_mut().zip(rows) {
2308 c.rows = rows;
2309 }
2310 }
2311
2312 fn long_size(&mut self, key: u64, max_w: Option<f32>) -> (Size, u32) {
2316 let (wrap, width, line_h, cur) = {
2317 let l = self.long(key).expect("a long line");
2318 (l.wrap, l.width(), l.line_h, l.wrap_w)
2319 };
2320 let target = match max_w {
2321 Some(w) if wrap != TextWrap::None && width > w + 0.5 => Some(w.max(1.0)),
2322 _ => None,
2323 };
2324 let differs = match (cur, target) {
2325 (None, None) => false,
2326 (Some(a), Some(b)) => (a - b).abs() > 0.5,
2327 _ => true,
2328 };
2329 if differs {
2330 self.relayout_long(key, target);
2331 }
2332 match target {
2333 Some(w) => {
2334 let rows = self.long(key).expect("a long line").rows();
2335 (Size::new(w, rows as f32 * line_h), rows)
2336 }
2337 None => (Size::new(max_w.map_or(width, |m| width.min(m)), line_h), 1),
2338 }
2339 }
2340
2341 pub fn measure(
2347 &mut self,
2348 content: &str,
2349 style: &TextStyle,
2350 res: &Resources,
2351 fs: &mut FontSystem,
2352 max_w: Option<f32>,
2353 ) -> TextMetrics {
2354 let key = self.intern_any(content, style, res, fs);
2355 self.measure_any(key, fs, max_w)
2356 }
2357
2358 fn measure_any(&mut self, key: u64, fs: &mut FontSystem, max_w: Option<f32>) -> TextMetrics {
2360 if self.long(key).is_some() {
2361 let scale = self.scale;
2362 let (size, lines) = match max_w {
2365 Some(m) => {
2366 let held = self.long(key).expect("checked").wrap_w;
2369 let measured = self.long_size(key, Some(m * scale));
2370 if wrap_differs(held, self.long(key).expect("checked").wrap_w) {
2371 self.relayout_long(key, held);
2372 }
2373 measured
2374 }
2375 None => {
2376 let line = self.long(key).expect("checked");
2377 (Size::new(line.width(), line.line_h), 1)
2378 }
2379 };
2380 return TextMetrics {
2381 width: size.w / scale,
2382 height: size.h / scale,
2383 lines,
2384 };
2385 }
2386 self.measure_key(key, fs, max_w)
2387 }
2388
2389 pub fn measure_rich(
2391 &mut self,
2392 spans: &[Span<'_>],
2393 base: &TextStyle,
2394 res: &Resources,
2395 fs: &mut FontSystem,
2396 max_w: Option<f32>,
2397 ) -> TextMetrics {
2398 let key = self.intern_rich_any(spans, base, res, fs);
2399 self.measure_any(key, fs, max_w)
2400 }
2401
2402 fn measure_key(&mut self, key: u64, fs: &mut FontSystem, max_w: Option<f32>) -> TextMetrics {
2403 let scale = self.scale;
2404 let entry = self.run_mut(key).expect("just interned");
2405 let target = wrap_target(entry, max_w, scale);
2406 let key = if entry.claimed != u64::MAX && wrap_differs(entry.wrap, target) {
2413 self.wrap_copy(key, target, fs)
2414 } else {
2415 key
2416 };
2417 let entry = self.run_mut(key).expect("just interned");
2418 wrap_entry(entry, fs, target);
2419 let (mut m, lines) = measure_buffer(&entry.buffer, entry.max_lines);
2420 if entry.clamp_w
2421 && let Some(t) = target
2422 {
2423 m.w = m.w.min(t);
2424 }
2425 TextMetrics {
2426 width: m.w / scale,
2427 height: m.h / scale,
2428 lines,
2429 }
2430 }
2431
2432 pub fn add_rich(
2436 &mut self,
2437 spans: &[Span<'_>],
2438 base: &TextStyle,
2439 res: &Resources,
2440 fs: &mut FontSystem,
2441 ) -> TextId {
2442 let key = self.intern_rich_any(spans, base, res, fs);
2443 let len = spans.iter().map(|s| s.text.len()).sum();
2444 let key = if could_be_long(len, base) {
2445 self.claim_long(key)
2446 } else {
2447 key
2448 };
2449 self.frame.push(FrameText {
2450 cache_key: key,
2451 color: base.color_or_default(),
2452 });
2453 TextId((self.frame.len() - 1) as u32)
2454 }
2455
2456 fn intern_rich(
2457 &mut self,
2458 spans: &[Span<'_>],
2459 base: &TextStyle,
2460 res: &Resources,
2461 fs: &mut FontSystem,
2462 ) -> u64 {
2463 let key = Self::rich_key(spans, base, self.scale);
2464 self.intern_rich_keyed(key, spans, base, res, fs)
2465 }
2466
2467 fn rich_key(spans: &[Span<'_>], base: &TextStyle, scale: f32) -> u64 {
2471 let mut key = Self::style_key("", base, scale) ^ 0x9e37_79b9_7f4a_7c15;
2472 for s in spans {
2473 key = crate::key::mix_content(key, s.text.as_bytes());
2474 let mut mix = |bytes: &[u8]| key = crate::key::fnv(key, bytes);
2475 mix(&[
2476 s.bold as u8,
2477 s.italic as u8,
2478 s.color.is_some() as u8,
2479 s.underline as u8,
2480 s.strikethrough as u8,
2481 s.bg.is_some() as u8,
2482 s.underline_style as u8,
2483 s.underline_color.is_some() as u8,
2484 ]);
2485 mix(&s.bg_radius.to_bits().to_le_bytes());
2486 let (tag, font) = match s.family {
2489 None => (0u8, 0u64),
2490 Some(FontFamily::Sans) => (1, 0),
2491 Some(FontFamily::Serif) => (2, 0),
2492 Some(FontFamily::Mono) => (3, 0),
2493 Some(FontFamily::Custom(id)) => (4, id.to_ffi()),
2494 };
2495 mix(&[tag]);
2496 mix(&font.to_le_bytes());
2497 mix(&s.size.map_or(0, f32::to_bits).to_le_bytes());
2498 for c in [s.color, s.bg, s.underline_color].into_iter().flatten() {
2499 mix(&c.r.to_bits().to_le_bytes());
2500 mix(&c.g.to_bits().to_le_bytes());
2501 mix(&c.b.to_bits().to_le_bytes());
2502 mix(&c.a.to_bits().to_le_bytes());
2503 }
2504 }
2505 key
2506 }
2507
2508 fn intern_rich_keyed(
2510 &mut self,
2511 key: u64,
2512 spans: &[Span<'_>],
2513 base: &TextStyle,
2514 res: &Resources,
2515 fs: &mut FontSystem,
2516 ) -> u64 {
2517 let frame_no = self.frame_no;
2518 let scale = self.scale;
2519 if !self.entries.contains_key(&key) {
2520 let mut buffer = new_buffer(fs, base, scale);
2521 let family = res.family_of(base.family);
2522 let weights = res.weights_of(base.family);
2523 let features = cosmic_features(&base.features);
2524 let sized = spans.iter().any(|s| s.size.is_some());
2529 let metrics_of = |size: Option<f32>| {
2530 let size = size.unwrap_or(base.size);
2531 let ratio = if base.size > 0.0 {
2532 base.line_height / base.size
2533 } else {
2534 1.0
2535 };
2536 shaper_metrics(size * scale, size * ratio * scale)
2537 };
2538 buffer.set_rich_text(
2542 spans.iter().enumerate().map(|(i, s)| {
2543 let (family, weights) = match s.family {
2544 Some(f) => (res.family_of(f), res.weights_of(f)),
2545 None => (family, weights),
2546 };
2547 let mut attrs = s
2548 .attrs(family, weights)
2549 .font_features(features.clone())
2550 .metadata(i);
2551 if sized {
2552 attrs = attrs.metrics(metrics_of(s.size));
2553 }
2554 (s.text, attrs)
2555 }),
2556 &{
2557 let attrs = weights.apply(
2558 Attrs::new().family(family).font_features(features.clone()),
2559 false,
2560 );
2561 if sized {
2562 attrs.metrics(metrics_of(None))
2563 } else {
2564 attrs
2565 }
2566 },
2567 Shaping::Advanced,
2568 None,
2569 );
2570 let content = spans.iter().map(|s| s.text).collect::<String>();
2571 let decos = spans
2572 .iter()
2573 .map(|s| SpanDeco {
2574 underline: s.underline || base.underline,
2575 underline_color: s.underline_color.or(base.underline_color),
2577 underline_style: if s.underline {
2578 s.underline_style
2579 } else {
2580 base.underline_style
2581 },
2582 strikethrough: s.strikethrough || base.strikethrough,
2583 bg: s.bg,
2584 bg_radius: s.bg_radius,
2585 })
2586 .collect();
2587 let entry = CachedText::new(buffer, content, base, decos, fs, frame_no);
2588 self.insert(key, Entry::Run(entry));
2589 }
2590 self.entries
2591 .get_mut(&key)
2592 .expect("just inserted")
2593 .touch(frame_no);
2594 key
2595 }
2596
2597 fn entry_mut(&mut self, id: TextId) -> &mut CachedText {
2600 let key = self.frame[id.0 as usize].cache_key;
2601 self.run_mut(key).expect("frame text missing from cache")
2602 }
2603
2604 fn ensure_wrap(&mut self, id: TextId, max_w_logical: f32, fs: &mut FontSystem) {
2609 let (scale, frame_no) = (self.scale, self.frame_no);
2610 let entry = self.entry_mut(id);
2611 let target = wrap_target(entry, Some(max_w_logical), scale);
2612 if entry.claimed == frame_no && wrap_differs(entry.claimed_wrap, target) {
2613 self.own_wrap(id, target, fs);
2614 return;
2615 }
2616 entry.claimed = frame_no;
2617 entry.claimed_wrap = target;
2618 wrap_entry(entry, fs, target);
2619 }
2620
2621 #[inline(never)]
2629 fn own_wrap(&mut self, id: TextId, target: Option<f32>, fs: &mut FontSystem) {
2630 let frame_no = self.frame_no;
2631 let key = self.frame[id.0 as usize].cache_key;
2632 let copy = self.wrap_copy(key, target, fs);
2633 self.frame[id.0 as usize].cache_key = copy;
2634 let entry = self.run_mut(copy).expect("just made");
2635 entry.claimed = frame_no;
2636 entry.claimed_wrap = target;
2637 }
2638
2639 #[inline(never)]
2645 fn wrap_copy(&mut self, key: u64, target: Option<f32>, fs: &mut FontSystem) -> u64 {
2646 let frame_no = self.frame_no;
2647 let slot = target.map_or(u64::MAX, |t| (t * 2.0).round() as u64);
2649 let copy = crate::key::fnv(key ^ COPY_SALT, &slot.to_le_bytes());
2650 if self.run(copy).is_none() {
2651 let fork = self.run(key).expect("a run").fork(frame_no);
2652 self.insert(copy, Entry::Run(fork));
2653 }
2654 let entry = self.run_mut(copy).expect("just made");
2655 entry.last_used = frame_no;
2656 wrap_entry(entry, fs, target);
2657 copy
2658 }
2659
2660 #[allow(clippy::too_many_arguments)]
2665 pub(crate) fn emit(
2666 &mut self,
2667 id: TextId,
2668 origin: Vec2,
2669 node: Size,
2670 clip: Clip,
2671 clip_id: ClipId,
2672 clips: &mut Vec<Clip>,
2673 res: &Resources,
2674 fs: &mut FontSystem,
2675 atlas: &mut GlyphAtlas,
2676 out: &mut Vec<Quad>,
2677 sel: Option<((usize, usize), Color)>,
2678 ) {
2679 let from = self.joins.len();
2680 self.emit_text(
2681 id, origin, node, clip, clip_id, clips, res, fs, atlas, out, sel,
2682 );
2683 if self.joins.len() == from {
2684 return;
2685 }
2686 let key = self.frame[id.0 as usize].cache_key;
2689 let clamps = match self.entries.get(&key) {
2690 Some(Entry::Long(l)) => l.wrap == TextWrap::None,
2691 Some(Entry::Run(e)) => e.clamp_w,
2692 None => false,
2693 };
2694 let own = clamps.then(|| {
2695 let ox = crate::geom::snap_px(origin.x * self.scale);
2696 (ox, ox + (node.w * self.scale).ceil())
2697 });
2698 for j in &mut self.joins[from..] {
2699 j.outer = clip_id;
2700 j.own = own;
2701 }
2702 }
2703
2704 #[allow(clippy::too_many_arguments)]
2710 #[inline(never)]
2711 fn emit_long(
2712 &mut self,
2713 key: u64,
2714 node: Size,
2715 ox: f32,
2716 oy: f32,
2717 nudge: Vec2,
2718 color: Color,
2719 clip: Clip,
2720 clip_id: ClipId,
2721 clips: &mut Vec<Clip>,
2722 res: &Resources,
2723 fs: &mut FontSystem,
2724 atlas: &mut GlyphAtlas,
2725 out: &mut Vec<Quad>,
2726 sel: Option<((usize, usize), Color)>,
2727 ) {
2728 let scale = self.scale;
2729 let line = self.long(key).expect("a long line");
2730 let (clip, clip_id) = if line.wrap == TextWrap::None {
2736 let own = Rect::new(ox, oy, (node.w * scale).ceil(), (node.h * scale).ceil());
2737 let clip = clip.intersect(own, crate::display::SQUARE);
2738 if clip.rect.w <= 0.0 || clip.rect.h <= 0.0 {
2739 return;
2740 }
2741 (clip, crate::display::intern_clip(clips, clip))
2742 } else {
2743 (clip, clip_id)
2744 };
2745 if let Some(((from, to), tint)) = sel {
2746 let rects = self.long_highlight(line, from, to);
2747 push_highlight(&rects, ox, oy, nudge, tint, clip_id, out);
2748 }
2749 if let Some(w) = line.wrap_w {
2750 self.emit_long_rows(
2751 key, w, ox, oy, nudge, color, clip, clip_id, res, fs, atlas, out,
2752 );
2753 return;
2754 }
2755 let (first, last) = {
2756 if line.chunks.is_empty() {
2757 return;
2758 }
2759 let a = line.chunk_at(clip.rect.x - ox).saturating_sub(1);
2760 let b = (line.chunk_at(clip.rect.x + clip.rect.w - ox) + 1).min(line.chunks.len() - 1);
2761 (a, b)
2762 };
2763 for i in first..=last {
2764 self.ensure_chunk(key, i, res, fs);
2765 }
2766 let frame_no = self.frame_no;
2767 self.long_mut(key).expect("checked").last_used = frame_no;
2768 for i in first..=last {
2769 let (chunk_key, x) = {
2770 let line = self.long(key).expect("checked");
2771 (line.chunks[i].key, line.prefix[i])
2772 };
2773 let raster = &mut self.raster;
2774 let entry = self
2775 .entries
2776 .get_mut(&chunk_key)
2777 .and_then(Entry::run_mut)
2778 .expect("just ensured");
2779 emit_entry(
2780 entry,
2781 ox + x,
2782 oy,
2783 nudge,
2784 color,
2785 clip,
2786 clip_id,
2787 raster,
2788 fs,
2789 atlas,
2790 out,
2791 &mut self.joins,
2792 );
2793 }
2794 }
2795
2796 #[allow(clippy::too_many_arguments)]
2798 fn emit_text(
2799 &mut self,
2800 id: TextId,
2801 origin: Vec2,
2802 node: Size,
2803 clip: Clip,
2804 clip_id: ClipId,
2805 clips: &mut Vec<Clip>,
2806 res: &Resources,
2807 fs: &mut FontSystem,
2808 atlas: &mut GlyphAtlas,
2809 out: &mut Vec<Quad>,
2810 sel: Option<((usize, usize), Color)>,
2815 ) {
2816 let FrameText {
2817 cache_key: key,
2818 color,
2819 } = self.frame[id.0 as usize];
2820 let scale = self.scale;
2821 let ox = crate::geom::snap_px(origin.x * scale);
2822 let oy = crate::geom::snap_px(origin.y * scale);
2823 let nudge = Vec2::new(origin.x * scale - ox, origin.y * scale - oy);
2826 if self.long(key).is_some() {
2829 self.emit_long(
2830 key, node, ox, oy, nudge, color, clip, clip_id, clips, res, fs, atlas, out, sel,
2831 );
2832 return;
2833 }
2834 self.ensure_wrap(id, node.w, fs);
2835 let raster = &mut self.raster;
2836 let entry = self
2837 .entries
2838 .get_mut(&key)
2839 .and_then(Entry::run_mut)
2840 .expect("frame text missing from cache");
2841
2842 let (clip, clip_id) = if entry.clamp_w {
2845 let own = Rect::new(ox, oy, (node.w * scale).ceil(), (node.h * scale).ceil());
2846 let clip = clip.intersect(own, crate::display::SQUARE);
2847 (clip, crate::display::intern_clip(clips, clip))
2848 } else {
2849 (clip, clip_id)
2850 };
2851 if let Some(((from, to), tint)) = sel {
2852 let rects = Self::run_highlight(entry, from, to);
2853 push_highlight(&rects, ox, oy, nudge, tint, clip_id, out);
2854 }
2855 emit_entry(
2856 entry,
2857 ox,
2858 oy,
2859 nudge,
2860 color,
2861 clip,
2862 clip_id,
2863 raster,
2864 fs,
2865 atlas,
2866 out,
2867 &mut self.joins,
2868 );
2869 }
2870}
2871
2872fn on_pixels(x: f32, y: f32, w: f32, h: f32, nudge: Vec2) -> Rect {
2886 Rect::new(x + nudge.x, y + nudge.y, w, h).on_pixels()
2887}
2888
2889fn push_highlight(
2892 rects: &[Rect],
2893 ox: f32,
2894 oy: f32,
2895 nudge: Vec2,
2896 tint: Color,
2897 clip: ClipId,
2898 out: &mut Vec<Quad>,
2899) {
2900 for r in rects {
2901 out.push(Quad {
2902 rect: on_pixels(ox + r.x, oy + r.y, r.w, r.h, nudge),
2903 color: tint,
2904 border_color: Color::TRANSPARENT,
2905 radius: [0.0; 4],
2906 border_w: 0.0,
2907 blur: 0.0,
2908 kind: QuadKind::Solid,
2909 uv: [0; 4],
2910 clip,
2911 });
2912 }
2913}
2914
2915impl TextSystem {
2916 #[allow(clippy::too_many_arguments)]
2920 fn emit_long_rows(
2921 &mut self,
2922 key: u64,
2923 w: f32,
2924 ox: f32,
2925 oy: f32,
2926 nudge: Vec2,
2927 color: Color,
2928 clip: Clip,
2929 clip_id: ClipId,
2930 res: &Resources,
2931 fs: &mut FontSystem,
2932 atlas: &mut GlyphAtlas,
2933 out: &mut Vec<Quad>,
2934 ) {
2935 let (first, last) = {
2936 let line = self.long(key).expect("a long line");
2937 let ra = ((clip.rect.y - oy) / line.line_h).floor().max(0.0) as u32;
2938 let rb = ((clip.rect.y + clip.rect.h - oy) / line.line_h)
2939 .floor()
2940 .max(0.0) as u32;
2941 let Some((a, b)) = line.chunks_on_rows(ra, rb) else {
2942 return;
2943 };
2944 (a.saturating_sub(1), (b + 1).min(line.chunks.len() - 1))
2945 };
2946 let mut fresh = false;
2947 for i in first..=last {
2948 fresh |= self.ensure_chunk(key, i, res, fs);
2949 }
2950 if fresh {
2951 self.relayout_long(key, Some(w));
2954 let line = self.long_mut(key).expect("checked");
2955 let rows = line.rows();
2956 if rows != line.laid_rows && rows != line.asked_rows {
2957 line.asked_rows = rows;
2958 self.owed = true;
2959 }
2960 }
2961 let frame_no = self.frame_no;
2962 self.long_mut(key).expect("checked").last_used = frame_no;
2963 for i in first..=last {
2964 let chunk_key = self.long(key).expect("checked").chunks[i].key;
2965 let [Some(Entry::Long(line)), Some(Entry::Run(entry))] =
2969 self.entries.get_disjoint_mut([&key, &chunk_key])
2970 else {
2971 continue;
2972 };
2973 let (row0, head_x) = line.starts[i];
2974 let chunk = &line.chunks[i];
2975 if chunk.rows.is_empty() {
2976 continue;
2977 }
2978 let raster = &mut self.raster;
2979 emit_entry_rows(
2980 entry,
2981 ox,
2982 oy + row0 as f32 * line.line_h,
2983 nudge,
2984 head_x,
2985 &chunk.rows,
2986 line.line_h,
2987 color,
2988 clip,
2989 clip_id,
2990 raster,
2991 fs,
2992 atlas,
2993 out,
2994 &mut self.joins,
2995 );
2996 }
2997 }
2998}
2999
3000#[allow(clippy::too_many_arguments)]
3005fn emit_entry_rows(
3006 entry: &mut CachedText,
3007 ox: f32,
3008 oy: f32,
3009 nudge: Vec2,
3010 head_x: f32,
3011 rows: &[RowStart],
3012 line_h: f32,
3013 color: Color,
3014 clip: Clip,
3015 clip_id: ClipId,
3016 raster: &mut Raster,
3017 fs: &mut FontSystem,
3018 atlas: &mut GlyphAtlas,
3019 out: &mut Vec<Quad>,
3020 joins: &mut Vec<JoinBg>,
3021) {
3022 build_templates(entry, raster, fs, atlas);
3023 let mut row_pieces = |d: &DecoTemplate, out: &mut Vec<Quad>| {
3029 let (x0, x1) = (d.x, d.x + d.w);
3030 for r in 0..rows.len() {
3031 let ra = rows[r].x;
3032 let rb = rows.get(r + 1).map_or(f32::INFINITY, |n| n.x);
3033 let (a, b) = (x0.max(ra), x1.min(rb));
3034 if b <= a {
3035 continue;
3036 }
3037 let dx = if r == 0 { head_x } else { 0.0 } - ra;
3038 let x = ox + a + dx;
3039 let y = oy + d.y + r as f32 * line_h;
3040 if y >= clip.rect.y + clip.rect.h {
3041 break;
3042 }
3043 if y + d.h <= clip.rect.y
3044 || x >= clip.rect.x + clip.rect.w
3045 || x + (b - a) <= clip.rect.x
3046 {
3047 continue;
3048 }
3049 let quad = Quad {
3050 rect: if d.under {
3051 on_pixels(x, y, b - a, d.h, nudge)
3052 } else {
3053 Rect::new(x, y, b - a, d.h)
3054 },
3055 color: d.color.unwrap_or(color),
3056 border_color: Color::TRANSPARENT,
3057 radius: [0.0; 4],
3058 border_w: 0.0,
3059 blur: 0.0,
3060 kind: QuadKind::Solid,
3061 clip: clip_id,
3062 uv: [0; 4],
3063 };
3064 if d.under && d.radius > 0.0 {
3068 joins.push(JoinBg {
3069 quad: out.len() as u32,
3070 radius: d.radius,
3071 outer: clip_id,
3072 own: None,
3073 });
3074 }
3075 if d.under || d.style == UnderlineStyle::Solid {
3076 out.push(quad);
3077 } else {
3078 crate::deco::push_line(
3079 out,
3080 d.style,
3081 x,
3082 y,
3083 b - a,
3084 d.h,
3085 d.color.unwrap_or(color),
3086 clip_id,
3087 );
3088 }
3089 }
3090 };
3091 for d in entry.deco.iter().filter(|d| d.under) {
3092 row_pieces(d, out);
3093 }
3094 let mut r = 0usize;
3095 for g in &entry.glyphs {
3096 while r + 1 < rows.len() && g.byte >= rows[r + 1].byte {
3097 r += 1;
3098 }
3099 let dx = if r == 0 { head_x } else { 0.0 } - rows[r].x;
3100 let x = ox + g.x + dx;
3101 let y = oy + g.y + r as f32 * line_h;
3102 if y >= clip.rect.y + clip.rect.h {
3109 break;
3110 }
3111 if y + g.h <= clip.rect.y || x >= clip.rect.x + clip.rect.w || x + g.w <= clip.rect.x {
3112 continue;
3113 }
3114 out.push(Quad {
3115 rect: Rect::new(x, y, g.w, g.h),
3116 color: g.color.unwrap_or(color),
3117 border_color: Color::TRANSPARENT,
3118 radius: [0.0; 4],
3119 border_w: 0.0,
3120 blur: 0.0,
3121 kind: g.kind,
3122 clip: clip_id,
3123 uv: g.uv,
3124 });
3125 }
3126 for d in entry.deco.iter().filter(|d| !d.under) {
3127 row_pieces(d, out);
3128 }
3129}
3130
3131fn break_rows(
3144 buffer: &Buffer,
3145 text: &str,
3146 wrap: TextWrap,
3147 w: f32,
3148 head_x: f32,
3149) -> (Vec<RowStart>, f32) {
3150 let mut rows = vec![RowStart { byte: 0, x: 0.0 }];
3151 let Some(run) = buffer.layout_runs().next() else {
3152 return (rows, head_x);
3153 };
3154 let glyphs = run.glyphs;
3155 let blank = |g: &cosmic_text::LayoutGlyph| {
3156 text.get(g.start..g.end)
3157 .is_some_and(|s| s.chars().all(char::is_whitespace))
3158 };
3159 let spaces = wrap == TextWrap::BreakSpaces;
3160 let mut pieces: Vec<(usize, usize)> = Vec::new();
3161 match wrap {
3162 TextWrap::Word | TextWrap::BreakSpaces => {
3163 let mut at = 0usize;
3164 let mut piece = |from: usize, to: usize| {
3165 if !spaces {
3166 pieces.push((from, to));
3167 return;
3168 }
3169 let ink = text[from..to].trim_end_matches(char::is_whitespace).len();
3172 if ink > 0 {
3173 pieces.push((from, from + ink));
3174 }
3175 for (i, c) in text[from + ink..to].char_indices() {
3176 let at = from + ink + i;
3177 pieces.push((at, at + c.len_utf8()));
3178 }
3179 };
3180 for (i, _) in unicode_linebreak::linebreaks(text) {
3181 if i > at {
3182 piece(at, i);
3183 at = i;
3184 }
3185 }
3186 if at < text.len() {
3187 piece(at, text.len());
3188 }
3189 }
3190 TextWrap::Glyph | TextWrap::None => {
3191 pieces.extend(glyphs.iter().map(|g| (g.start, g.end)));
3192 }
3193 }
3194 let mut row_x0 = 0.0f32;
3195 let mut avail = w - head_x;
3196 let mut gi = 0usize;
3197 for (s, e) in pieces {
3198 let g0 = gi;
3199 while gi < glyphs.len() && glyphs[gi].start < e {
3200 gi += 1;
3201 }
3202 if g0 == gi {
3203 continue;
3204 }
3205 let piece = &glyphs[g0..gi];
3206 let x0 = piece[0].x;
3207 let ink_end = piece
3208 .iter()
3209 .rev()
3210 .find(|g| spaces || !blank(g))
3211 .map_or(x0, |g| g.x + g.w);
3212 let opens = x0 > row_x0 || (rows.len() == 1 && head_x > 0.0);
3218 if ink_end - row_x0 > avail && opens {
3219 rows.push(RowStart {
3220 byte: s as u32,
3221 x: x0,
3222 });
3223 row_x0 = x0;
3224 avail = w;
3225 }
3226 if ink_end - row_x0 > avail {
3227 for g in piece {
3229 if g.x + g.w - row_x0 > avail && g.x > row_x0 && (spaces || !blank(g)) {
3230 rows.push(RowStart {
3231 byte: g.start as u32,
3232 x: g.x,
3233 });
3234 row_x0 = g.x;
3235 avail = w;
3236 }
3237 }
3238 }
3239 }
3240 let end = if rows.len() == 1 {
3241 head_x + run.line_w
3242 } else {
3243 run.line_w - row_x0
3244 };
3245 (rows, end)
3246}
3247
3248fn build_templates(
3251 entry: &mut CachedText,
3252 raster: &mut Raster,
3253 fs: &mut FontSystem,
3254 atlas: &mut GlyphAtlas,
3255) {
3256 {
3257 let built_for = (entry.wrap.map(f32::to_bits), atlas.stamp);
3259 if entry.glyphs_built_for != Some(built_for) {
3260 entry.glyphs.clear();
3261 entry.deco.clear();
3262 let lines = line_cap(entry.max_lines);
3263 let decorated = entry.span_deco.iter().any(SpanDeco::any);
3264 for run in entry.buffer.layout_runs().take(lines) {
3265 if decorated {
3266 build_decorations(&run, &entry.span_deco, fs, &mut entry.deco);
3267 }
3268 for glyph in run.glyphs.iter() {
3269 let physical = glyph.physical((0.0, 0.0), 1.0);
3270 let Some(slot) = raster_glyph(physical.cache_key, fs, raster, atlas) else {
3271 continue;
3272 };
3273 entry.glyphs.push(GlyphTemplate {
3274 x: physical.x as f32 + slot.left as f32,
3275 y: run.line_y.round() + physical.y as f32 - slot.top as f32,
3276 w: slot.w as f32,
3277 h: slot.h as f32,
3278 uv: [slot.x, slot.y, slot.w, slot.h],
3279 kind: glyph_kind(&slot),
3280 color: glyph
3281 .color_opt
3282 .map(|c| Color::rgba8(c.r(), c.g(), c.b(), c.a())),
3283 byte: glyph.start as u32,
3284 });
3285 }
3286 }
3287 entry.glyphs_built_for = Some((entry.wrap.map(f32::to_bits), atlas.stamp));
3291 }
3292 }
3293}
3294
3295#[allow(clippy::too_many_arguments)]
3299fn emit_entry(
3300 entry: &mut CachedText,
3301 ox: f32,
3302 oy: f32,
3303 nudge: Vec2,
3304 color: Color,
3305 clip: Clip,
3306 clip_id: ClipId,
3307 raster: &mut Raster,
3308 fs: &mut FontSystem,
3309 atlas: &mut GlyphAtlas,
3310 out: &mut Vec<Quad>,
3311 joins: &mut Vec<JoinBg>,
3312) {
3313 build_templates(entry, raster, fs, atlas);
3314 {
3315 let inside = |x: f32, y: f32, w: f32, h: f32| {
3316 oy + y + h >= clip.rect.y
3317 && oy + y <= clip.rect.y + clip.rect.h
3318 && ox + x < clip.rect.x + clip.rect.w
3319 && ox + x + w > clip.rect.x
3320 };
3321 let deco_quad = |d: &DecoTemplate| Quad {
3322 rect: Rect::new(ox + d.x, oy + d.y, d.w, d.h),
3323 color: d.color.unwrap_or(color),
3324 border_color: Color::TRANSPARENT,
3325 radius: [0.0; 4],
3326 border_w: 0.0,
3327 blur: 0.0,
3328 kind: QuadKind::Solid,
3329 clip: clip_id,
3330 uv: [0; 4],
3331 };
3332 for d in entry
3337 .deco
3338 .iter()
3339 .filter(|d| d.under && inside(d.x, d.y, d.w, d.h))
3340 {
3341 if d.radius > 0.0 {
3342 joins.push(JoinBg {
3343 quad: out.len() as u32,
3344 radius: d.radius,
3345 outer: clip_id,
3346 own: None,
3347 });
3348 }
3349 out.push(Quad {
3350 rect: on_pixels(ox + d.x, oy + d.y, d.w, d.h, nudge),
3351 ..deco_quad(d)
3352 });
3353 }
3354
3355 out.extend(
3359 entry
3360 .glyphs
3361 .iter()
3362 .filter(|g| {
3363 oy + g.y + g.h >= clip.rect.y
3364 && ox + g.x < clip.rect.x + clip.rect.w
3365 && ox + g.x + g.w > clip.rect.x
3366 })
3367 .take_while(|g| oy + g.y <= clip.rect.y + clip.rect.h)
3368 .map(|g| Quad {
3369 rect: Rect::new(ox + g.x, oy + g.y, g.w, g.h),
3370 color: g.color.unwrap_or(color),
3371 border_color: Color::TRANSPARENT,
3372 radius: [0.0; 4],
3373 border_w: 0.0,
3374 blur: 0.0,
3375 kind: g.kind,
3376 clip: clip_id,
3377 uv: g.uv,
3378 }),
3379 );
3380 for d in entry
3381 .deco
3382 .iter()
3383 .filter(|d| !d.under && inside(d.x, d.y, d.w, d.h))
3384 {
3385 match d.style {
3388 UnderlineStyle::Solid => out.push(deco_quad(d)),
3389 style => crate::deco::push_line(
3390 out,
3391 style,
3392 ox + d.x,
3393 oy + d.y,
3394 d.w,
3395 d.h,
3396 d.color.unwrap_or(color),
3397 clip_id,
3398 ),
3399 }
3400 }
3401 }
3402}
3403
3404fn could_be_long(len: usize, style: &TextStyle) -> bool {
3412 (len >= LONG_LINE_BYTES || len > 0 && style.wrap == TextWrap::BreakSpaces)
3413 && style.max_lines == 0
3414 && !style.ellipsis
3415}
3416
3417fn has_line_break(content: &str) -> bool {
3420 content.bytes().any(|b| b == b'\n' || b == b'\r')
3421}
3422
3423fn has_rtl(content: &str) -> bool {
3431 !content.is_ascii()
3432 && content.chars().any(|c| {
3433 matches!(c as u32,
3434 0x0590..=0x08FF
3435 | 0x200F | 0x202B | 0x202E | 0x2067
3436 | 0xFB1D..=0xFDFF
3437 | 0xFE70..=0xFEFF
3438 | 0x10800..=0x10FFF
3439 | 0x1E800..=0x1EFFF)
3440 })
3441}
3442
3443fn build_decorations(
3454 run: &cosmic_text::LayoutRun<'_>,
3455 spans: &[SpanDeco],
3456 fs: &mut FontSystem,
3457 out: &mut Vec<DecoTemplate>,
3458) {
3459 let mut last_bg: Option<usize> = None;
3462 let mut i = 0;
3463 while i < run.glyphs.len() {
3464 let span_no = run.glyphs[i].metadata;
3465 let mut j = i + 1;
3466 while j < run.glyphs.len() && run.glyphs[j].metadata == span_no {
3467 j += 1;
3468 }
3469 let deco = spans.get(span_no).copied().unwrap_or_default();
3470 if deco.any() {
3471 let group = &run.glyphs[i..j];
3472 let x0 = group.iter().map(|g| g.x).fold(f32::INFINITY, f32::min);
3473 let x1 = group
3474 .iter()
3475 .map(|g| g.x + g.w)
3476 .fold(f32::NEG_INFINITY, f32::max);
3477 let w = (x1 - x0).max(0.0);
3478 match (deco.bg, last_bg.map(|k| &mut out[k])) {
3479 (Some(bg), Some(prev))
3480 if prev.color == Some(bg)
3481 && prev.radius == deco.bg_radius
3482 && (prev.x + prev.w - x0).abs() < 0.01 =>
3483 {
3484 prev.w = (x1 - prev.x).max(prev.w);
3485 }
3486 (Some(bg), _) => {
3487 let (y, h) = match group[0].line_height_opt {
3491 Some(lh) if lh < run.line_height - 0.01 => {
3492 let g = &group[0];
3493 let (asc, desc) = fs
3494 .get_font(g.font_id, g.font_weight)
3495 .map(|font| {
3496 let m = font.as_swash().metrics(&[]).scale(g.font_size);
3497 (m.ascent, m.descent)
3498 })
3499 .unwrap_or((0.8 * g.font_size, 0.2 * g.font_size));
3500 let mid = run.line_y - (asc - desc) / 2.0;
3501 (mid - lh / 2.0, lh)
3502 }
3503 _ => (run.line_top, run.line_height),
3504 };
3505 last_bg = Some(out.len());
3506 out.push(DecoTemplate {
3507 x: x0,
3508 y,
3509 w,
3510 h,
3511 color: Some(bg),
3512 under: true,
3513 style: UnderlineStyle::Solid,
3514 radius: deco.bg_radius,
3515 });
3516 }
3517 (None, _) => last_bg = None,
3518 }
3519 if deco.underline || deco.strikethrough {
3520 let first = &group[0];
3521 let metrics = fs
3522 .get_font(first.font_id, first.font_weight)
3523 .map(|font| font.as_swash().metrics(&[]).scale(first.font_size));
3524 let (under_off, strike_off, stroke) = match metrics {
3527 Some(m) => (m.underline_offset, m.strikeout_offset, m.stroke_size),
3528 None => (
3529 -0.1 * first.font_size,
3530 0.3 * first.font_size,
3531 0.06 * first.font_size,
3532 ),
3533 };
3534 let stroke = stroke.max(1.0).round();
3535 let baseline = run.line_y.round();
3536 if deco.underline {
3537 out.push(DecoTemplate {
3538 x: x0,
3539 y: (baseline - under_off).round(),
3540 w,
3541 h: stroke,
3542 color: deco.underline_color.or_else(|| {
3543 first
3544 .color_opt
3545 .map(|c| Color::rgba8(c.r(), c.g(), c.b(), c.a()))
3546 }),
3547 under: false,
3548 style: deco.underline_style,
3549 radius: 0.0,
3550 });
3551 }
3552 if deco.strikethrough {
3553 out.push(DecoTemplate {
3554 x: x0,
3555 y: (baseline - strike_off).round(),
3556 w,
3557 h: stroke,
3558 color: first
3559 .color_opt
3560 .map(|c| Color::rgba8(c.r(), c.g(), c.b(), c.a())),
3561 under: false,
3562 style: UnderlineStyle::Solid,
3563 radius: 0.0,
3564 });
3565 }
3566 }
3567 } else {
3568 last_bg = None;
3569 }
3570 i = j;
3571 }
3572}
3573
3574impl TextSystem {
3575 pub(crate) fn place(
3580 &mut self,
3581 key: Key,
3582 ancestry: &Ancestry,
3583 id: TextId,
3584 origin: Vec2,
3585 scope: Option<Key>,
3586 drawn: bool,
3587 ) {
3588 let cache_key = self.frame[id.0 as usize].cache_key;
3589 self.places.push(TextPlace {
3590 key,
3591 ancestors: ancestry.keys,
3592 depth: ancestry.depth.min(PLACE_ANCESTORS) as u8,
3593 none_at: ancestry.none_at.map_or(u8::MAX, |n| n as u8),
3594 cache_key,
3595 origin,
3596 scope,
3597 drawn,
3598 });
3599 }
3600
3601 fn runs_of(&self, key: Key, prev: bool) -> Vec<(&TextPlace, &Entry, usize)> {
3607 let list = if prev {
3608 self.places.prev()
3609 } else {
3610 &self.places
3611 };
3612 let mut base = 0usize;
3613 let mut out = Vec::new();
3614 for place in list.iter().filter(|p| p.drawn && p.answers_to(key)) {
3615 let Some(entry) = self.entries.get(&place.cache_key) else {
3616 continue;
3617 };
3618 out.push((place, entry, base));
3619 base += entry.content().len();
3620 }
3621 out
3622 }
3623
3624 pub(crate) fn content_len(&self, id: TextId) -> usize {
3627 let key = self.frame[id.0 as usize].cache_key;
3628 self.entries.get(&key).map_or(0, |e| e.content().len())
3629 }
3630
3631 pub(crate) fn scope_runs(&self, scope: Key, prev: bool) -> Vec<ScopeRun<'_>> {
3640 let list = if prev {
3641 self.places.prev()
3642 } else {
3643 &self.places
3644 };
3645 let mut base = 0usize;
3646 let mut out = Vec::new();
3647 for place in list.iter().filter(|p| p.scope == Some(scope)) {
3648 let Some(text) = self.entries.get(&place.cache_key) else {
3649 continue;
3650 };
3651 let len = text.content().len();
3652 out.push(ScopeRun { place, text, base });
3653 base += len;
3654 }
3655 out
3656 }
3657
3658 pub(crate) fn scope_hit(&self, scope: Key, point: Vec2, prev: bool) -> Option<(Key, usize)> {
3665 let runs = self.scope_runs(scope, prev);
3666 let px = point.x * self.scale;
3667 let py = point.y * self.scale;
3668 let gap = |r: &Rect| {
3669 let dy = (r.y - py).max(py - (r.y + r.h)).max(0.0);
3670 let dx = (r.x - px).max(px - (r.x + r.w)).max(0.0);
3671 (dy, dx)
3672 };
3673 let run = runs.iter().filter(|r| r.place.drawn).min_by(|a, b| {
3674 let ga = gap(&self.scope_box(a));
3675 let gb = gap(&self.scope_box(b));
3676 ga.partial_cmp(&gb).unwrap_or(std::cmp::Ordering::Equal)
3677 })?;
3678 let byte = self.hit_in_run(run, point)?;
3679 Some((run.place.key, byte))
3680 }
3681
3682 fn scope_box(&self, run: &ScopeRun<'_>) -> Rect {
3684 self.entry_box(run.place, run.text)
3685 }
3686
3687 fn entry_box(&self, place: &TextPlace, entry: &Entry) -> Rect {
3692 match entry {
3693 Entry::Run(e) => self.physical_box(place, e),
3694 Entry::Long(l) => {
3695 let (ox, oy) = self.physical_origin(place);
3696 let w = l.wrap_w.unwrap_or_else(|| l.width());
3697 Rect::new(ox, oy, w, l.line_h * l.rows() as f32)
3698 }
3699 }
3700 }
3701
3702 fn row_tops(&self, place: &TextPlace, entry: &Entry) -> Vec<f32> {
3704 let (_, oy) = self.physical_origin(place);
3705 match entry {
3706 Entry::Run(e) => e.buffer.layout_runs().map(|r| oy + r.line_top).collect(),
3707 Entry::Long(l) => (0..l.rows()).map(|r| oy + r as f32 * l.line_h).collect(),
3708 }
3709 }
3710
3711 fn hit_in_run(&self, run: &ScopeRun<'_>, point: Vec2) -> Option<usize> {
3714 match run.text {
3715 Entry::Long(l) => Some(self.long_hit(run.place, l, point)?.byte),
3716 Entry::Run(e) => {
3717 let (ox, oy) = self.physical_origin(run.place);
3718 let cursor = e
3719 .buffer
3720 .hit(point.x * self.scale - ox, point.y * self.scale - oy)?;
3721 Some(e.byte_of(cursor))
3722 }
3723 }
3724 }
3725
3726 pub(crate) fn word_at(
3733 &self,
3734 scope: Key,
3735 node: Key,
3736 byte: usize,
3737 prev: bool,
3738 ) -> Option<(usize, usize)> {
3739 let run = self
3740 .scope_runs(scope, prev)
3741 .into_iter()
3742 .find(|r| r.place.key == node)?;
3743 let content = run.text.content();
3744 Some(word_range(content, byte))
3745 }
3746
3747 pub(crate) fn scope_offset(
3753 &self,
3754 scope: Key,
3755 node: Key,
3756 byte: usize,
3757 prev: bool,
3758 ) -> Option<usize> {
3759 let run = self
3760 .scope_runs(scope, prev)
3761 .into_iter()
3762 .find(|r| r.place.key == node)?;
3763 Some(run.base + byte.min(run.text.content().len()))
3764 }
3765
3766 pub(crate) fn scope_html(&self, scope: Key, from: usize, to: usize, prev: bool) -> String {
3781 let (from, to) = (from.min(to), from.max(to));
3782 let mut out = String::new();
3783 let mut prev_run: Option<&ScopeRun<'_>> = None;
3784 for run in &self.scope_runs(scope, prev) {
3785 let (start, end) = run.span();
3786 if end <= from || start >= to {
3787 continue;
3788 }
3789 if let Some(p) = prev_run
3790 && (p.place.origin.y - run.place.origin.y).abs() > f32::EPSILON
3791 {
3792 out.push_str("<br>");
3793 }
3794 let content = run.text.content();
3795 let lo = floor_boundary(content, from.saturating_sub(start));
3796 let hi = floor_boundary(content, (to - start).min(content.len()));
3797 match run.text {
3798 Entry::Long(line) => self.long_html(line, lo, hi, &mut out),
3799 Entry::Run(entry) => html_of_run(entry, lo, hi, &mut out),
3800 }
3801 prev_run = Some(run);
3802 }
3803 out
3804 }
3805
3806 fn long_html(&self, line: &LongLine, lo: usize, hi: usize, out: &mut String) {
3812 for c in &line.chunks {
3813 let (a, b) = (lo.max(c.start), hi.min(c.end));
3814 if a >= b {
3815 continue;
3816 }
3817 match c.width.and_then(|_| self.run(c.key)) {
3818 Some(e) => html_of_run(e, a - c.start, b - c.start, out),
3819 None => escape_into(&line.content[a..b], out),
3820 }
3821 }
3822 }
3823
3824 pub(crate) fn scope_selection_anchor(
3834 &self,
3835 scope: Key,
3836 from: usize,
3837 to: usize,
3838 prev: bool,
3839 ) -> Option<Vec2> {
3840 let (from, to) = (from.min(to), from.max(to));
3841 for run in self.scope_runs(scope, prev) {
3842 let (start, end) = run.span();
3843 if !run.place.drawn || end <= from || start >= to {
3844 continue;
3845 }
3846 let content = run.text.content();
3847 let lo = floor_boundary(content, from.saturating_sub(start));
3848 let hi = floor_boundary(content, (to - start).min(content.len()));
3849 let (ox, oy) = self.physical_origin(run.place);
3850 match run.text {
3851 Entry::Run(e) => {
3852 if let Some((x, base)) = Self::run_anchor(e, lo, hi) {
3853 return Some(Vec2::new((ox + x) / self.scale, (oy + base) / self.scale));
3854 }
3855 }
3856 Entry::Long(l) => {
3857 if let Some((x, y)) = self.long_caret_local(l, lo) {
3858 return Some(Vec2::new(
3859 (ox + x) / self.scale,
3860 (oy + y + self.long_baseline(l)) / self.scale,
3861 ));
3862 }
3863 }
3864 }
3865 }
3866 None
3867 }
3868
3869 fn run_anchor(entry: &CachedText, lo: usize, hi: usize) -> Option<(f32, f32)> {
3872 let (a, b) = (entry.cursor_of(lo), entry.cursor_of(hi));
3873 for run in entry.buffer.layout_runs() {
3874 if run.line_i < a.line || run.line_i > b.line {
3875 continue;
3876 }
3877 if let Some((x, _)) = run.highlight(a, b).next() {
3878 return Some((x, run.line_y));
3879 }
3880 }
3881 None
3882 }
3883
3884 pub(crate) fn scope_selection_rect(
3890 &self,
3891 scope: Key,
3892 from: usize,
3893 to: usize,
3894 prev: bool,
3895 ) -> Option<Rect> {
3896 let (from, to) = (from.min(to), from.max(to));
3897 let mut out: Option<Rect> = None;
3898 for run in self.scope_runs(scope, prev) {
3899 let (start, end) = run.span();
3900 if !run.place.drawn || end <= from || start >= to {
3901 continue;
3902 }
3903 let content = run.text.content();
3904 let lo = floor_boundary(content, from.saturating_sub(start));
3905 let hi = floor_boundary(content, (to - start).min(content.len()));
3906 let (ox, oy) = self.physical_origin(run.place);
3912 let rects = match run.text {
3913 Entry::Long(l) => self.long_highlight(l, lo, hi),
3914 Entry::Run(e) => Self::run_highlight(e, lo, hi),
3915 };
3916 for r in rects {
3917 let r = Rect::new(
3918 (ox + r.x) / self.scale,
3919 (oy + r.y) / self.scale,
3920 r.w / self.scale,
3921 r.h / self.scale,
3922 );
3923 out = Some(match out {
3924 None => r,
3925 Some(o) => o.union(&r),
3926 });
3927 }
3928 }
3929 out
3930 }
3931
3932 pub(crate) fn scope_slice(&self, scope: Key, from: usize, to: usize, prev: bool) -> String {
3937 let (from, to) = (from.min(to), from.max(to));
3938 let runs = self.scope_runs(scope, prev);
3939 let mut out = String::new();
3940 let mut reserved = false;
3941 let mut prev_run: Option<&ScopeRun<'_>> = None;
3942 for run in &runs {
3943 let (start, end) = run.span();
3944 if end <= from || start >= to {
3945 continue;
3946 }
3947 if !reserved {
3948 out.reserve(to - from + runs.len());
3949 reserved = true;
3950 }
3951 if let Some(p) = prev_run
3952 && (p.place.origin.y - run.place.origin.y).abs() > f32::EPSILON
3953 {
3954 out.push('\n');
3955 }
3956 let content = run.text.content();
3957 let lo = from.saturating_sub(start).min(content.len());
3958 let hi = (to - start).min(content.len());
3959 out.push_str(&content[floor_boundary(content, lo)..floor_boundary(content, hi)]);
3960 prev_run = Some(run);
3961 }
3962 out
3963 }
3964
3965 fn long_hit(&self, place: &TextPlace, line: &LongLine, point: Vec2) -> Option<TextHit> {
3969 let (ox, oy) = self.physical_origin(place);
3970 let px = point.x * self.scale - ox;
3971 let py = point.y * self.scale - oy;
3972 if line.chunks.is_empty() {
3973 return Some(TextHit { byte: 0, line: 0 });
3974 }
3975 if let Some(w) = line.wrap_w {
3976 return self.long_hit_wrapped(line, w, px, py);
3977 }
3978 if px >= line.width() {
3979 return Some(TextHit {
3980 byte: line.content.len(),
3981 line: 0,
3982 });
3983 }
3984 let i = line.chunk_at(px.max(0.0));
3985 let c = &line.chunks[i];
3986 let local = px - line.prefix[i];
3987 let byte = match self.run(c.key) {
3988 Some(_) if let Some(b) = line.placed_tab_hit(i, local) => b,
3989 Some(e) if c.width.is_some() => {
3990 let cursor = e.buffer.hit(local, py.clamp(0.0, line.line_h - 0.01))?;
3991 c.start + cursor.index.min(c.end - c.start)
3992 }
3993 _ => {
3994 let est = (local / line.avg.max(f32::EPSILON)).round() as usize;
3995 let mut b = (c.start + est).min(c.end);
3996 while !line.content.is_char_boundary(b) {
3997 b -= 1;
3998 }
3999 b
4000 }
4001 };
4002 Some(TextHit { byte, line: 0 })
4003 }
4004
4005 fn long_hit_wrapped(&self, line: &LongLine, w: f32, px: f32, py: f32) -> Option<TextHit> {
4009 let row = ((py / line.line_h).floor().max(0.0) as u32).min(line.rows() - 1);
4010 let Some((a, b)) = line.chunks_on_rows(row, row) else {
4011 return Some(TextHit {
4012 byte: line.content.len(),
4013 line: row,
4014 });
4015 };
4016 let i = (a..=b)
4019 .find(|&j| {
4020 let (r1, end_x) = line.starts[j + 1];
4021 px < if r1 == row { end_x } else { w }
4022 })
4023 .unwrap_or(b);
4024 let c = &line.chunks[i];
4025 let (row0, head_x) = line.starts[i];
4026 let r = (row - row0) as usize;
4027 let byte = match self.run(c.key) {
4028 Some(e) if r < c.rows.len() => {
4029 let rs = c.rows[r];
4030 let local_x = px - if r == 0 { head_x } else { 0.0 } + rs.x;
4031 let lo = rs.byte as usize;
4032 let hi = c
4033 .rows
4034 .get(r + 1)
4035 .map_or(c.end - c.start, |n| n.byte as usize);
4036 let tab_here = (lo..hi).contains(&(c.end - c.start - 1));
4038 match line.placed_tab_hit(i, local_x) {
4039 Some(b) if tab_here => b,
4040 _ => {
4041 let cursor = e.buffer.hit(local_x, line.line_h / 2.0)?;
4042 c.start + cursor.index.clamp(lo, hi)
4043 }
4044 }
4045 }
4046 _ => {
4047 let linear = r as f32 * w + px - head_x;
4050 let est = (linear / line.avg.max(f32::EPSILON)).round() as usize;
4051 let mut b = (c.start + est).min(c.end);
4052 while !line.content.is_char_boundary(b) {
4053 b -= 1;
4054 }
4055 b
4056 }
4057 };
4058 let next_row = self
4063 .long_caret_local(line, byte)
4064 .is_some_and(|(_, y)| y > (row as f32 + 0.5) * line.line_h);
4065 let byte = if next_row && byte > 0 {
4066 floor_boundary(&line.content, byte - 1)
4067 } else {
4068 byte
4069 };
4070 Some(TextHit { byte, line: row })
4071 }
4072
4073 fn long_caret(&self, place: &TextPlace, line: &LongLine, byte: usize) -> Option<Rect> {
4076 let (ox, oy) = self.physical_origin(place);
4077 let scale = self.scale;
4078 let (x, y) = self.long_caret_local(line, byte)?;
4079 Some(Rect::new(
4080 (ox + x) / scale,
4081 (oy + y) / scale,
4082 0.0,
4083 line.line_h / scale,
4084 ))
4085 }
4086
4087 fn long_baseline(&self, line: &LongLine) -> f32 {
4093 line.chunks
4094 .first()
4095 .and_then(|c| self.run(c.key))
4096 .and_then(|e| e.buffer.layout_runs().next())
4097 .map_or(line.line_h * 0.8, |r| r.line_y.round())
4098 }
4099
4100 fn long_caret_local(&self, line: &LongLine, byte: usize) -> Option<(f32, f32)> {
4105 let byte = byte.min(line.content.len());
4106 if let Some(w) = line.wrap_w
4107 && !line.chunks.is_empty()
4108 {
4109 let i = line.chunk_of_byte(byte);
4110 let c = &line.chunks[i];
4111 let local = byte - c.start;
4112 let (row0, head_x) = line.starts[i];
4113 let (r, x) = match self.run(c.key) {
4114 Some(e) if !c.rows.is_empty() => {
4115 let r = c.rows.partition_point(|rs| rs.byte as usize <= local) - 1;
4116 let run = e.buffer.layout_runs().next()?;
4117 let cx = caret_x(&run, local.min(c.end - c.start)) + line.end_shift(i, local);
4118 (r, cx - c.rows[r].x + if r == 0 { head_x } else { 0.0 })
4119 }
4120 _ => {
4121 let linear = head_x + local as f32 * line.avg;
4122 let r = (linear / w).floor();
4123 (r as usize, linear - r * w)
4124 }
4125 };
4126 let y = (row0 as usize + r) as f32 * line.line_h;
4127 return Some((x, y));
4128 }
4129 let x = if line.chunks.is_empty() {
4130 0.0
4131 } else {
4132 let i = line.chunk_of_byte(byte);
4133 let c = &line.chunks[i];
4134 let local = byte - c.start;
4135 match self.run(c.key) {
4136 Some(e) if c.width.is_some() => {
4137 let run = e.buffer.layout_runs().next()?;
4138 let x = caret_x(&run, local.min(c.end - c.start));
4139 line.prefix[i] + x + line.end_shift(i, local)
4140 }
4141 _ => line.prefix[i] + local as f32 * line.avg,
4142 }
4143 };
4144 Some((x, 0.0))
4145 }
4146
4147 fn long_highlight(&self, line: &LongLine, from: usize, to: usize) -> Vec<Rect> {
4153 let Some((x0, y0)) = self.long_caret_local(line, from) else {
4154 return Vec::new();
4155 };
4156 let Some((x1, y1)) = self.long_caret_local(line, to) else {
4157 return Vec::new();
4158 };
4159 let h = line.line_h;
4160 if (y1 - y0).abs() < f32::EPSILON {
4161 return vec![Rect::new(x0, y0, (x1 - x0).max(0.0), h)];
4162 }
4163 let w = line.wrap_w.unwrap_or_else(|| line.width());
4165 let mut out = vec![Rect::new(x0, y0, (w - x0).max(0.0), h)];
4166 let mut y = y0 + h;
4167 while y < y1 - h / 2.0 {
4168 out.push(Rect::new(0.0, y, w, h));
4169 y += h;
4170 }
4171 out.push(Rect::new(0.0, y1, x1.max(0.0), h));
4172 out
4173 }
4174
4175 fn run_highlight(entry: &CachedText, from: usize, to: usize) -> Vec<Rect> {
4181 let (a, b) = (entry.cursor_of(from), entry.cursor_of(to));
4182 let mut out = Vec::new();
4183 for run in entry.buffer.layout_runs() {
4184 if run.line_i < a.line || run.line_i > b.line {
4185 continue;
4186 }
4187 let h = run.line_height;
4190 let mut any = false;
4191 for (x, w) in run.highlight(a, b) {
4192 any = true;
4193 out.push(Rect::new(x, run.line_top, w.max(2.0), h));
4194 }
4195 if !any && run.glyphs.is_empty() && b.line > run.line_i {
4198 out.push(Rect::new(0.0, run.line_top, 2.0, h));
4199 }
4200 }
4201 out
4202 }
4203
4204 fn physical_origin(&self, place: &TextPlace) -> (f32, f32) {
4207 (
4208 crate::geom::snap_px(place.origin.x * self.scale),
4209 crate::geom::snap_px(place.origin.y * self.scale),
4210 )
4211 }
4212
4213 fn physical_box(&self, place: &TextPlace, entry: &CachedText) -> Rect {
4215 let (ox, oy) = self.physical_origin(place);
4216 let (size, _) = measure_buffer(&entry.buffer, entry.max_lines);
4217 Rect::new(ox, oy, size.w, size.h)
4218 }
4219
4220 pub(crate) fn hit_at(&self, key: Key, point: Vec2, prev: bool) -> Option<TextHit> {
4224 let runs = self.runs_of(key, prev);
4225 if runs.is_empty() {
4226 return None;
4227 }
4228 let px = point.x * self.scale;
4229 let py = point.y * self.scale;
4230 let gap = |r: &Rect| {
4233 let dy = (r.y - py).max(py - (r.y + r.h)).max(0.0);
4234 let dx = (r.x - px).max(px - (r.x + r.w)).max(0.0);
4235 (dy, dx)
4236 };
4237 let (place, entry, base) = runs
4238 .iter()
4239 .min_by(|a, b| {
4240 let ga = gap(&self.entry_box(a.0, a.1));
4241 let gb = gap(&self.entry_box(b.0, b.1));
4242 ga.partial_cmp(&gb).unwrap_or(std::cmp::Ordering::Equal)
4243 })
4244 .copied()?;
4245 let (ox, oy) = self.physical_origin(place);
4246 let (byte, hit_top) = match entry {
4247 Entry::Long(line) => {
4248 let hit = self.long_hit(place, line, point)?;
4249 (hit.byte, oy + hit.line as f32 * line.line_h)
4250 }
4251 Entry::Run(entry) => {
4252 let bx = self.physical_box(place, entry);
4259 let py = py.clamp(bx.y, (bx.y + bx.h - 0.01).max(bx.y));
4260 let cursor = entry.buffer.hit(px - ox, py - oy)?;
4261 let row =
4262 visual_line(&entry.buffer, cursor.line, cursor.index).map_or(0, |(l, _)| l);
4263 let top = entry
4264 .buffer
4265 .layout_runs()
4266 .nth(row)
4267 .map_or(0.0, |r| r.line_top);
4268 (entry.byte_of(cursor), oy + top)
4269 }
4270 };
4271 let mut tops: Vec<f32> = runs
4276 .iter()
4277 .flat_map(|(p, e, _)| self.row_tops(p, e))
4278 .collect();
4279 tops.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
4280 tops.dedup_by(|a, b| (*a - *b).abs() < 0.5);
4281 let line = tops.iter().filter(|t| **t < hit_top - 0.5).count();
4282 Some(TextHit {
4283 byte: base + byte,
4284 line: line as u32,
4285 })
4286 }
4287
4288 pub(crate) fn caret_at(&self, key: Key, byte: usize, prev: bool) -> Option<Rect> {
4292 let runs = self.runs_of(key, prev);
4293 let total = runs.last().map(|(_, e, base)| base + e.content().len())?;
4294 let byte = byte.min(total);
4295 let (place, entry, base) = runs
4296 .iter()
4297 .find(|(_, e, base)| byte < base + e.content().len())
4298 .or_else(|| runs.last())
4299 .copied()?;
4300 let byte = (byte - base).min(entry.content().len());
4301 let entry = match entry {
4302 Entry::Long(line) => return self.long_caret(place, line, byte),
4303 Entry::Run(entry) => entry,
4304 };
4305 let (ox, oy) = self.physical_origin(place);
4306 let cursor = entry.cursor_of(byte);
4307 let (_, run_no) = visual_line(&entry.buffer, cursor.line, cursor.index)?;
4308 let run = entry.buffer.layout_runs().nth(run_no)?;
4309 let x = caret_x(&run, cursor.index);
4310 let scale = self.scale;
4311 Some(Rect::new(
4312 (ox + x) / scale,
4313 (oy + run.line_top) / scale,
4314 0.0,
4315 run.line_height / scale,
4316 ))
4317 }
4318}
4319
4320fn word_range(content: &str, byte: usize) -> (usize, usize) {
4330 if content.is_empty() {
4331 return (0, 0);
4332 }
4333 #[derive(PartialEq)]
4334 enum Class {
4335 Word,
4336 Space,
4337 Other,
4338 }
4339 let class = |c: char| {
4340 if c.is_alphanumeric() || c == '_' {
4341 Class::Word
4342 } else if c.is_whitespace() {
4343 Class::Space
4344 } else {
4345 Class::Other
4346 }
4347 };
4348 let at = floor_boundary(content, byte.min(content.len()));
4351 let at = if at >= content.len() {
4352 content.char_indices().next_back().map_or(0, |(i, _)| i)
4353 } else {
4354 at
4355 };
4356 let Some(here) = content[at..].chars().next().map(class) else {
4357 return (at, at);
4358 };
4359 let mut start = at;
4360 for (i, c) in content[..at].char_indices().rev() {
4361 if class(c) != here {
4362 break;
4363 }
4364 start = i;
4365 }
4366 let mut end = at;
4367 for (i, c) in content[at..].char_indices() {
4368 if class(c) != here {
4369 break;
4370 }
4371 end = at + i + c.len_utf8();
4372 }
4373 (start, end)
4374}
4375
4376fn html_of_run(entry: &CachedText, lo: usize, hi: usize, out: &mut String) {
4381 let starts = line_starts(&entry.buffer, &entry.content);
4382 for (li, line) in entry.buffer.lines.iter().enumerate() {
4383 let base = starts.get(li).copied().unwrap_or(0);
4384 let text = line.text();
4385 if li > 0 {
4386 if base > lo && base <= hi {
4389 out.push_str("<br>");
4390 }
4391 }
4392 let attrs_list = line.attrs_list();
4398 let mut spans: Vec<(usize, usize, cosmic_text::AttrsOwned)> = Vec::new();
4399 for (i, _) in text.char_indices() {
4400 let a = cosmic_text::AttrsOwned::new(&attrs_list.get_span(i));
4401 match spans.last_mut() {
4402 Some((_, end, prev)) if *prev == a && *end == i => {
4403 *end = i + text[i..].chars().next().map_or(1, char::len_utf8);
4404 }
4405 _ => spans.push((i, i + text[i..].chars().next().map_or(1, char::len_utf8), a)),
4406 }
4407 }
4408 for (start, end, attrs) in &spans {
4409 let (s, e) = (base + start, base + end);
4410 let (s, e) = (s.max(lo), e.min(hi));
4411 if s >= e {
4412 continue;
4413 }
4414 let piece = &entry.content[s..e];
4415 let bold = attrs.weight > attrs_list.defaults().weight
4420 || attrs
4421 .cache_key_flags
4422 .contains(crate::weights::SYNTHETIC_BOLD);
4423 let italic = attrs.style != cosmic_text::Style::Normal;
4424 if let Some(c) = attrs.color_opt {
4425 let _ = std::fmt::Write::write_fmt(
4426 out,
4427 format_args!(
4428 "<span style=\"color:#{:02x}{:02x}{:02x}\">",
4429 c.r(),
4430 c.g(),
4431 c.b()
4432 ),
4433 );
4434 }
4435 if bold {
4436 out.push_str("<b>");
4437 }
4438 if italic {
4439 out.push_str("<i>");
4440 }
4441 escape_into(piece, out);
4442 if italic {
4443 out.push_str("</i>");
4444 }
4445 if bold {
4446 out.push_str("</b>");
4447 }
4448 if attrs.color_opt.is_some() {
4449 out.push_str("</span>");
4450 }
4451 }
4452 }
4453}
4454
4455fn escape_into(s: &str, out: &mut String) {
4459 for ch in s.chars() {
4460 match ch {
4461 '&' => out.push_str("&"),
4462 '<' => out.push_str("<"),
4463 '>' => out.push_str(">"),
4464 _ => out.push(ch),
4465 }
4466 }
4467}
4468
4469fn floor_boundary(s: &str, i: usize) -> usize {
4475 let mut i = i.min(s.len());
4476 while i > 0 && !s.is_char_boundary(i) {
4477 i -= 1;
4478 }
4479 i
4480}
4481
4482fn line_starts(buffer: &Buffer, content: &str) -> Vec<usize> {
4483 paragraph_starts(buffer, content).collect()
4484}
4485
4486fn paragraph_starts<'a>(buffer: &'a Buffer, content: &'a str) -> impl Iterator<Item = usize> + 'a {
4492 let mut at = 0usize;
4493 buffer.lines.iter().map(move |line| {
4494 let start = at.min(content.len());
4495 at += line.text().len();
4496 let rest = &content[at.min(content.len())..];
4497 for ending in ["\r\n", "\n\r", "\n", "\r"] {
4498 if rest.starts_with(ending) {
4499 at += ending.len();
4500 break;
4501 }
4502 }
4503 start
4504 })
4505}
4506
4507fn visual_line(buffer: &Buffer, line_i: usize, index: usize) -> Option<(usize, usize)> {
4517 let mut last_of_line = None;
4518 let mut before = None;
4519 for (n, run) in buffer.layout_runs().enumerate() {
4520 if run.line_i != line_i {
4521 if last_of_line.is_some() {
4522 break;
4523 }
4524 continue;
4525 }
4526 last_of_line = Some(n);
4527 if run.glyphs.iter().any(|g| g.start <= index && index < g.end) {
4528 return Some((n, n));
4529 }
4530 if run
4531 .glyphs
4532 .iter()
4533 .map(|g| g.start)
4534 .min()
4535 .is_some_and(|s| s <= index)
4536 {
4537 before = Some(n);
4538 }
4539 }
4540 before.or(last_of_line).map(|n| (n, n))
4541}
4542
4543fn caret_x(run: &cosmic_text::LayoutRun<'_>, index: usize) -> f32 {
4547 if let Some(g) = run
4548 .glyphs
4549 .iter()
4550 .find(|g| g.start <= index && index < g.end)
4551 {
4552 return if g.level.is_rtl() { g.x + g.w } else { g.x };
4553 }
4554 match run.glyphs.last() {
4555 Some(g) if !g.level.is_rtl() => g.x + g.w,
4556 Some(g) => g.x,
4557 None => 0.0,
4558 }
4559}
4560
4561impl Default for TextSystem {
4562 fn default() -> Self {
4563 Self::new()
4564 }
4565}
4566
4567fn wrap_target(entry: &CachedText, max_w_logical: Option<f32>, scale: f32) -> Option<f32> {
4570 let max_w = max_w_logical?;
4571 let intrinsic_fits = entry.intrinsic.w <= max_w * scale + 0.5;
4572 (!intrinsic_fits).then_some(max_w * scale)
4573}
4574
4575pub(crate) fn wrap_differs(current: Option<f32>, target: Option<f32>) -> bool {
4583 match (current, target) {
4584 (None, None) => false,
4585 (Some(a), Some(b)) => (a - b).abs() > 0.5,
4586 _ => true,
4587 }
4588}
4589
4590fn wrap_entry(entry: &mut CachedText, fs: &mut FontSystem, target: Option<f32>) {
4591 if wrap_differs(entry.wrap, target) {
4592 entry.buffer.set_size(target, None);
4593 entry.buffer.shape_until_scroll(fs, false);
4594 entry.wrap = target;
4595 }
4596}
4597
4598impl CachedText {
4599 fn byte_of(&self, cursor: cosmic_text::Cursor) -> usize {
4602 let start = paragraph_starts(&self.buffer, &self.content)
4603 .nth(cursor.line)
4604 .unwrap_or(0);
4605 (start + cursor.index).min(self.content.len())
4606 }
4607
4608 fn cursor_of(&self, byte: usize) -> cosmic_text::Cursor {
4614 let mut li = 0;
4615 let mut start = 0;
4616 for (i, s) in paragraph_starts(&self.buffer, &self.content).enumerate() {
4617 if s <= byte {
4618 (li, start) = (i, s);
4619 } else {
4620 break;
4621 }
4622 }
4623 let len = self.buffer.lines.get(li).map_or(0, |l| l.text().len());
4624 cosmic_text::Cursor::new(li, (byte - start).min(len))
4625 }
4626
4627 fn new(
4628 mut buffer: Buffer,
4629 content: String,
4630 style: &TextStyle,
4631 span_deco: Vec<SpanDeco>,
4632 fs: &mut FontSystem,
4633 frame_no: u64,
4634 ) -> Self {
4635 buffer.shape_until_scroll(fs, false);
4636 let max_lines = line_budget(style);
4637 let (intrinsic, _) = measure_buffer(&buffer, max_lines);
4638 let glyphs: usize = buffer.layout_runs().map(|r| r.glyphs.len()).sum();
4639 Self {
4640 buffer,
4641 bytes: ENTRY_BASE_BYTES + content.len() + ENTRY_GLYPH_BYTES * glyphs,
4642 content,
4643 wrap: None,
4644 intrinsic,
4645 max_lines,
4646 clamp_w: style.wrap == TextWrap::None || style.ellipsis,
4647 last_used: frame_no,
4648 glyphs: Vec::new(),
4649 deco: Vec::new(),
4650 span_deco,
4651 glyphs_built_for: None,
4652 claimed: u64::MAX,
4653 claimed_wrap: None,
4654 breaks_anywhere: style.wrap == TextWrap::Glyph,
4655 min_content: None,
4656 }
4657 }
4658
4659 fn fork(&self, frame_no: u64) -> Self {
4663 Self {
4664 buffer: self.buffer.clone(),
4665 content: self.content.clone(),
4666 wrap: self.wrap,
4667 intrinsic: self.intrinsic,
4668 max_lines: self.max_lines,
4669 clamp_w: self.clamp_w,
4670 last_used: frame_no,
4671 bytes: self.bytes,
4672 glyphs: Vec::new(),
4673 deco: Vec::new(),
4674 span_deco: self.span_deco.clone(),
4675 glyphs_built_for: None,
4676 claimed: u64::MAX,
4677 claimed_wrap: None,
4678 breaks_anywhere: self.breaks_anywhere,
4679 min_content: self.min_content,
4680 }
4681 }
4682
4683 fn min_content(&mut self) -> f32 {
4694 if let Some(w) = self.min_content {
4695 return w;
4696 }
4697 let w = if self.clamp_w {
4698 self.intrinsic.w
4699 } else {
4700 widest_unbreakable(&self.buffer, self.breaks_anywhere)
4701 };
4702 self.min_content = Some(w);
4703 w
4704 }
4705}
4706
4707fn widest_unbreakable(buffer: &Buffer, anywhere: bool) -> f32 {
4711 let mut widest = 0.0f32;
4712 let mut line = usize::MAX;
4713 let mut breaks: Vec<usize> = Vec::new();
4714 let (mut run_w, mut ink) = (0.0f32, 0.0f32);
4715 for run in buffer.layout_runs() {
4716 if run.line_i != line {
4717 widest = widest.max(ink);
4718 (run_w, ink) = (0.0, 0.0);
4719 line = run.line_i;
4720 breaks.clear();
4721 if !anywhere {
4722 breaks.extend(unicode_linebreak::linebreaks(run.text).map(|(i, _)| i));
4723 }
4724 }
4725 for g in run.glyphs {
4726 if anywhere || breaks.binary_search(&g.start).is_ok() {
4727 widest = widest.max(ink);
4728 (run_w, ink) = (0.0, 0.0);
4729 }
4730 run_w += g.w;
4731 let blank = run
4732 .text
4733 .get(g.start..g.end)
4734 .is_some_and(|t| t.chars().all(char::is_whitespace));
4735 if !blank {
4736 ink = run_w;
4737 }
4738 }
4739 }
4740 widest.max(ink)
4741}
4742
4743pub(crate) fn shaper_metrics(size: f32, line_height: f32) -> Metrics {
4750 let px = |v: f32| if v.is_finite() { v.max(1.0) } else { 1.0 };
4751 Metrics::new(px(size), px(line_height))
4752}
4753
4754fn new_buffer(fs: &mut FontSystem, style: &TextStyle, scale: f32) -> Buffer {
4757 let metrics = shaper_metrics(style.size * scale, style.line_height * scale);
4758 let mut buffer = Buffer::new(fs, metrics);
4759 buffer.set_wrap(match style.wrap {
4760 TextWrap::Word | TextWrap::BreakSpaces => Wrap::WordOrGlyph,
4761 TextWrap::Glyph => Wrap::Glyph,
4762 TextWrap::None => Wrap::None,
4763 });
4764 if style.ellipsis {
4765 let lines = line_budget(style).max(1);
4766 buffer.set_ellipsize(Ellipsize::End(EllipsizeHeightLimit::Lines(lines)));
4767 }
4768 buffer.set_size(None, None);
4769 buffer
4770}
4771
4772fn line_budget(style: &TextStyle) -> usize {
4775 if style.max_lines > 0 {
4776 style.max_lines as usize
4777 } else if style.ellipsis {
4778 1
4779 } else {
4780 0
4781 }
4782}
4783
4784fn line_cap(max_lines: usize) -> usize {
4785 if max_lines == 0 {
4786 usize::MAX
4787 } else {
4788 max_lines
4789 }
4790}
4791
4792pub(crate) fn measure_buffer(buffer: &Buffer, max_lines: usize) -> (Size, u32) {
4798 let mut w = 0.0f32;
4799 let mut lines = 0u32;
4800 let lh = buffer.metrics().line_height;
4804 let (mut sum, mut uniform) = (0.0f32, true);
4805 for run in buffer.layout_runs().take(line_cap(max_lines)) {
4806 w = w.max(run.line_w);
4807 lines += 1;
4808 sum += run.line_height;
4809 uniform &= run.line_height == lh;
4810 }
4811 (
4812 Size::new(w, if uniform { lines as f32 * lh } else { sum }),
4813 lines,
4814 )
4815}
4816
4817impl TextSystem {
4818 pub(crate) fn intrinsic(&mut self, id: TextId) -> Size {
4819 let scale = self.scale;
4820 if let Some(line) = self.long_of(id) {
4821 return Size::new(line.width() / scale, line.line_h / scale);
4822 }
4823 let e = self.entry_mut(id);
4824 Size::new(e.intrinsic.w / scale, e.intrinsic.h / scale)
4825 }
4826
4827 pub(crate) fn min_content(&mut self, id: TextId) -> f32 {
4832 let scale = self.scale;
4833 if self.long_of(id).is_some() {
4834 return 0.0;
4835 }
4836 self.entry_mut(id).min_content() / scale
4837 }
4838
4839 fn long_of(&self, id: TextId) -> Option<&LongLine> {
4841 self.long(self.frame[id.0 as usize].cache_key)
4842 }
4843
4844 pub(crate) fn wrapped(&mut self, id: TextId, max_w: f32, fs: &mut FontSystem) -> Size {
4845 let scale = self.scale;
4846 if self.long_of(id).is_some() {
4847 let key = self.frame[id.0 as usize].cache_key;
4850 let (size, rows) = self.long_size(key, Some(max_w * scale));
4851 self.long_mut(key).expect("a long line").laid_rows = rows;
4852 return Size::new(size.w / scale, size.h / scale);
4853 }
4854 self.ensure_wrap(id, max_w, fs);
4855 let e = self.entry_mut(id);
4856 let (mut m, _) = measure_buffer(&e.buffer, e.max_lines);
4857 if e.clamp_w {
4858 m.w = m.w.min(max_w * scale);
4861 }
4862 Size::new(m.w / scale, m.h / scale)
4863 }
4864}
4865
4866impl TextSystem {
4867 pub(crate) fn baseline(&mut self, id: TextId) -> f32 {
4872 let scale = self.scale;
4873 if let Some(line) = self.long_of(id) {
4874 return self.long_baseline(line) / scale;
4875 }
4876 let e = self.entry_mut(id);
4877 let b = e
4878 .buffer
4879 .layout_runs()
4880 .next()
4881 .map_or(e.buffer.metrics().line_height * 0.8, |r| r.line_y.round());
4882 b / scale
4883 }
4884}
4885
4886#[cfg(test)]
4889mod default_families {
4890 use super::*;
4891 use cosmic_text::Family;
4892 use cosmic_text::fontdb::FaceInfo;
4893
4894 fn resolved(fs: &mut FontSystem, family: Family<'_>) -> Option<FaceInfo> {
4897 let mut buffer = Buffer::new(fs, Metrics::new(14.0, 18.0));
4898 buffer.set_text("M", &Attrs::new().family(family), Shaping::Advanced, None);
4899 buffer.shape_until_scroll(fs, false);
4900 let id = buffer.layout_runs().next()?.glyphs.first()?.font_id;
4901 fs.db().face(id).cloned()
4902 }
4903
4904 #[test]
4905 fn mono_is_an_upright_monospaced_face() {
4906 let mut fs = new_font_system().0;
4907 if !fs.db().faces().any(|f| f.monospaced) {
4908 eprintln!("skipped: no monospaced face installed");
4909 return;
4910 }
4911 let face = resolved(&mut fs, Family::Monospace).expect("M shapes in Mono");
4912 let mono = default_families(&fs)[2].to_string();
4913 assert_eq!(
4914 face.style,
4915 cosmic_text::Style::Normal,
4916 "Mono ({mono}) resolved to {:?}",
4917 face.post_script_name
4918 );
4919 assert!(
4920 face.monospaced,
4921 "Mono ({mono}) resolved to {:?}, which is not monospaced",
4922 face.post_script_name
4923 );
4924 }
4925
4926 #[test]
4927 fn sans_and_serif_are_upright_and_not_monospaced() {
4928 let mut fs = new_font_system().0;
4929 if fs.db().faces().next().is_none() {
4930 eprintln!("skipped: no face installed");
4931 return;
4932 }
4933 let [sans, serif, _] = default_families(&fs).map(str::to_string);
4934 for (family, name) in [(Family::SansSerif, sans), (Family::Serif, serif)] {
4935 let face = resolved(&mut fs, family).expect("M shapes");
4936 assert_eq!(
4937 face.style,
4938 cosmic_text::Style::Normal,
4939 "{name} resolved to {:?}",
4940 face.post_script_name
4941 );
4942 assert!(
4943 !face.monospaced,
4944 "{name} resolved to {:?}, which is monospaced",
4945 face.post_script_name
4946 );
4947 }
4948 }
4949
4950 #[test]
4953 fn pinned_names_are_installed_or_cosmic_texts_own() {
4954 let fs = new_font_system().0;
4955 let db = fs.db();
4956 for (name, list) in default_families(&fs).into_iter().zip(DEFAULT_FAMILIES) {
4957 let installed = db
4958 .faces()
4959 .any(|f| f.families.iter().any(|(fam, _)| fam == name));
4960 let on_list = list.contains(&name);
4961 assert!(
4962 installed == on_list,
4963 "{name}: installed {installed}, on the platform list {on_list}"
4964 );
4965 }
4966 }
4967}
4968
4969#[cfg(test)]
4976mod unmeasurable_faces {
4977 use super::*;
4978 use crate::testing::{font_face, han_face, unmeasurable_face};
4979 use cosmic_text::Family;
4980 use cosmic_text::fontdb::{Database, Source};
4981
4982 fn font_system() -> FontSystem {
4987 let mut db = Database::new();
4988 for bytes in [
4989 font_face("Kui Mono", 400, false, true),
4990 unmeasurable_face("Kui Bitmap"),
4991 han_face("Kui Han"),
4992 ] {
4993 db.load_font_source(Source::Binary(std::sync::Arc::new(bytes)));
4994 }
4995 let mut fs = font_system_with("en-US".into(), db);
4996 fs.db_mut().set_monospace_family("Kui Mono");
4997 fs
4998 }
4999
5000 fn family(fs: &FontSystem, id: cosmic_text::fontdb::ID) -> String {
5001 fs.db()
5002 .face(id)
5003 .map_or_else(String::new, |f| f.families[0].0.clone())
5004 }
5005
5006 #[test]
5007 fn a_face_without_metrics_is_not_in_the_database() {
5008 let fs = font_system();
5009 let families: Vec<String> = fs.db().faces().map(|f| family(&fs, f.id)).collect();
5010 assert_eq!(families, ["Kui Mono", "Kui Han"]);
5011 }
5012
5013 #[test]
5017 fn han_in_mono_falls_back_to_a_face_that_measures() {
5018 let mut fs = font_system();
5019 let mut buffer = Buffer::new(&mut fs, Metrics::new(14.0, 21.0));
5020 let attrs = Attrs::new().family(Family::Monospace);
5021 buffer.set_text("字 a", &attrs, Shaping::Advanced, None);
5022 buffer.shape_until_scroll(&mut fs, false);
5023 let run = buffer.layout_runs().next().expect("one line");
5024 let glyphs: Vec<(&str, f32, f32, String)> = run
5025 .glyphs
5026 .iter()
5027 .map(|g| (&run.text[g.start..g.end], g.x, g.w, family(&fs, g.font_id)))
5028 .collect();
5029 for &(text, x, w, _) in &glyphs {
5030 assert!(x.is_finite() && w.is_finite(), "{text:?} at {x}, {w} wide");
5031 }
5032 let faces: Vec<(&str, &str)> = glyphs.iter().map(|g| (g.0, g.3.as_str())).collect();
5033 assert_eq!(
5034 faces,
5035 [("字", "Kui Han"), (" ", "Kui Mono"), ("a", "Kui Mono")]
5036 );
5037 let xs: Vec<f32> = glyphs.iter().map(|g| g.1).collect();
5039 assert_eq!(xs, [0.0, 7.0, 14.0]);
5040 for glyph in run.glyphs {
5041 glyph.physical((0.0, 0.0), 1.0);
5042 }
5043 }
5044}