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}
387
388impl<'a> Span<'a> {
389 pub fn new(text: &'a str) -> Self {
390 Self {
391 text,
392 color: None,
393 bold: false,
394 italic: false,
395 underline: false,
396 underline_color: None,
397 underline_style: UnderlineStyle::Solid,
398 strikethrough: false,
399 bg: None,
400 bg_radius: 0.0,
401 }
402 }
403
404 pub fn color(mut self, c: Color) -> Self {
405 self.color = Some(c);
406 self
407 }
408
409 pub fn bold(mut self) -> Self {
410 self.bold = true;
411 self
412 }
413
414 pub fn italic(mut self) -> Self {
415 self.italic = true;
416 self
417 }
418
419 pub fn underline(mut self) -> Self {
420 self.underline = true;
421 self
422 }
423
424 pub fn underline_color(mut self, c: Color) -> Self {
426 self.underline = true;
427 self.underline_color = Some(c);
428 self
429 }
430
431 pub fn underline_style(mut self, s: UnderlineStyle) -> Self {
433 self.underline = true;
434 self.underline_style = s;
435 self
436 }
437
438 pub fn strikethrough(mut self) -> Self {
439 self.strikethrough = true;
440 self
441 }
442
443 pub fn bg(mut self, c: Color) -> Self {
444 self.bg = Some(c);
445 self
446 }
447
448 pub fn bg_radius(mut self, r: f32) -> Self {
451 self.bg_radius = r.max(0.0);
452 self
453 }
454
455 fn attrs_only(&self) -> SpanAttrs {
458 SpanAttrs {
459 color: self.color,
460 bold: self.bold,
461 italic: self.italic,
462 underline: self.underline,
463 underline_color: self.underline_color,
464 underline_style: self.underline_style,
465 strikethrough: self.strikethrough,
466 bg: self.bg,
467 bg_radius: self.bg_radius,
468 }
469 }
470
471 fn attrs(
472 &self,
473 family: cosmic_text::Family<'a>,
474 weights: crate::weights::Weights,
475 ) -> Attrs<'a> {
476 let mut attrs = weights.apply(Attrs::new().family(family), self.bold);
480 if self.italic {
481 attrs = attrs.style(FontStyle::Italic);
482 }
483 if let Some(c) = self.color {
484 attrs = attrs.color(cosmic_text::Color::rgba(
485 (c.r * 255.0) as u8,
486 (c.g * 255.0) as u8,
487 (c.b * 255.0) as u8,
488 (c.a * 255.0) as u8,
489 ));
490 }
491 attrs
492 }
493}
494
495#[derive(Clone, Copy)]
499struct SpanAttrs {
500 color: Option<Color>,
501 bold: bool,
502 italic: bool,
503 underline: bool,
504 underline_color: Option<Color>,
505 underline_style: UnderlineStyle,
506 strikethrough: bool,
507 bg: Option<Color>,
508 bg_radius: f32,
509}
510
511impl SpanAttrs {
512 fn span<'a>(&self, text: &'a str) -> Span<'a> {
513 Span {
514 text,
515 color: self.color,
516 bold: self.bold,
517 italic: self.italic,
518 underline: self.underline,
519 underline_color: self.underline_color,
520 underline_style: self.underline_style,
521 strikethrough: self.strikethrough,
522 bg: self.bg,
523 bg_radius: self.bg_radius,
524 }
525 }
526}
527
528#[derive(Clone)]
531struct OwnedSpan {
532 start: usize,
533 end: usize,
534 attrs: SpanAttrs,
535}
536
537fn chunk_spans<'a>(
542 content: &'a str,
543 spans: &[OwnedSpan],
544 start: usize,
545 end: usize,
546) -> Vec<Span<'a>> {
547 let first = spans.partition_point(|s| s.end <= start);
548 spans[first..]
549 .iter()
550 .take_while(|s| s.start < end)
551 .filter_map(|s| {
552 let (a, b) = (s.start.max(start), s.end.min(end));
553 (a < b).then(|| s.attrs.span(&content[a..b]))
554 })
555 .collect()
556}
557
558struct FrameText {
559 cache_key: u64,
560 color: Color,
561}
562
563pub(crate) enum Entry {
571 Run(CachedText),
572 Long(LongLine),
573}
574
575impl Entry {
576 pub(crate) fn content(&self) -> &str {
577 match self {
578 Entry::Run(e) => &e.content,
579 Entry::Long(l) => &l.content,
580 }
581 }
582
583 fn last_used(&self) -> u64 {
584 match self {
585 Entry::Run(e) => e.last_used,
586 Entry::Long(l) => l.last_used,
587 }
588 }
589
590 fn touch(&mut self, frame_no: u64) {
591 match self {
592 Entry::Run(e) => e.last_used = frame_no,
593 Entry::Long(l) => l.last_used = frame_no,
594 }
595 }
596
597 fn bytes(&self) -> usize {
599 match self {
600 Entry::Run(e) => e.bytes,
601 Entry::Long(l) => l.bytes,
602 }
603 }
604
605 fn run(&self) -> Option<&CachedText> {
606 match self {
607 Entry::Run(e) => Some(e),
608 Entry::Long(_) => None,
609 }
610 }
611
612 fn run_mut(&mut self) -> Option<&mut CachedText> {
613 match self {
614 Entry::Run(e) => Some(e),
615 Entry::Long(_) => None,
616 }
617 }
618
619 fn long(&self) -> Option<&LongLine> {
620 match self {
621 Entry::Long(l) => Some(l),
622 Entry::Run(_) => None,
623 }
624 }
625
626 fn long_mut(&mut self) -> Option<&mut LongLine> {
627 match self {
628 Entry::Long(l) => Some(l),
629 Entry::Run(_) => None,
630 }
631 }
632}
633
634#[derive(Clone)]
638struct Chunk {
639 start: usize,
640 end: usize,
641 key: u64,
642 width: Option<f32>,
643 rows: Vec<RowStart>,
646}
647
648#[derive(Clone, Copy, Debug)]
652struct RowStart {
653 byte: u32,
654 x: f32,
655}
656
657#[derive(Clone)]
670pub(crate) struct LongLine {
671 content: String,
672 spans: Vec<OwnedSpan>,
676 style: TextStyle,
679 wrap: TextWrap,
685 wrap_w: Option<f32>,
688 starts: Vec<(u32, f32)>,
693 chunks: Vec<Chunk>,
694 prefix: Vec<f32>,
697 line_h: f32,
699 avg: f32,
702 last_used: u64,
703 claimed: u64,
706 laid_rows: u32,
713 asked_rows: u32,
714 bytes: usize,
715}
716
717impl LongLine {
718 fn chunk_at(&self, x: f32) -> usize {
720 match self.prefix[1..].partition_point(|&p| p <= x) {
721 i if i >= self.chunks.len() => self.chunks.len().saturating_sub(1),
722 i => i,
723 }
724 }
725
726 fn chunk_of_byte(&self, byte: usize) -> usize {
728 match self.chunks.partition_point(|c| c.end <= byte) {
729 i if i >= self.chunks.len() => self.chunks.len().saturating_sub(1),
730 i => i,
731 }
732 }
733
734 fn width(&self) -> f32 {
735 self.prefix.last().copied().unwrap_or(0.0)
736 }
737
738 fn rows(&self) -> u32 {
740 match self.starts.last() {
741 Some(&(r, _)) if self.wrap_w.is_some() => r + 1,
742 _ => 1,
743 }
744 }
745
746 fn chunks_on_rows(&self, ra: u32, rb: u32) -> Option<(usize, usize)> {
749 let n = self.chunks.len();
750 if n == 0 || self.starts.len() != n + 1 {
751 return None;
752 }
753 let first = self.starts[1..].partition_point(|s| s.0 < ra);
754 let last = self.starts[..n].partition_point(|s| s.0 <= rb);
755 (first < last).then_some((first, last - 1))
756 }
757
758 fn reprefix(&mut self) {
760 let mut at = 0.0f32;
761 self.prefix.clear();
762 self.prefix.push(0.0);
763 for c in &self.chunks {
764 at += c
765 .width
766 .unwrap_or_else(|| (c.end - c.start) as f32 * self.avg);
767 self.prefix.push(at);
768 }
769 }
770}
771
772fn chunk_ranges(content: &str) -> Vec<(usize, usize)> {
786 use unicode_segmentation::UnicodeSegmentation;
787 if content.len() < LONG_LINE_BYTES {
788 return vec![(0, content.len())];
789 }
790 let mut out = Vec::with_capacity(content.len() / CHUNK_BYTES + 1);
791 let mut start = 0usize;
792 while start < content.len() {
793 let mut window_end = (start + CHUNK_BYTES).min(content.len());
797 while !content.is_char_boundary(window_end) {
798 window_end -= 1;
799 }
800 let end = if window_end == content.len() {
801 window_end
802 } else {
803 let window = &content[start..window_end];
804 let half = CHUNK_BYTES / 2;
805 let mut from = half.min(window.len());
809 while !window.is_char_boundary(from) {
810 from += 1;
811 }
812 let (mut tab, mut space) = (None, None);
813 for (i, c) in window[from..].char_indices() {
814 if c.is_whitespace() {
815 let end = from + i + c.len_utf8();
816 space = Some(end);
817 if c == '\t' {
818 tab = Some(end);
819 }
820 }
821 }
822 match tab.or(space) {
823 Some(i) => start + i,
824 None => {
825 let mut cut = 0usize;
827 for (i, _) in window.grapheme_indices(true) {
828 if i == 0 {
829 continue;
830 }
831 cut = i;
832 }
833 if cut == 0 { window_end } else { start + cut }
834 }
835 }
836 };
837 out.push((start, end));
838 start = end;
839 }
840 out
841}
842
843pub(crate) const PLACE_ANCESTORS: usize = 4;
848
849pub(crate) struct Ancestry {
853 pub(crate) keys: [Key; PLACE_ANCESTORS],
854 pub(crate) depth: usize,
855 pub(crate) none_at: Option<usize>,
856}
857
858pub(crate) struct TextPlace {
863 pub(crate) key: Key,
864 ancestors: [Key; PLACE_ANCESTORS],
866 depth: u8,
867 none_at: u8,
873 cache_key: u64,
874 origin: Vec2,
876 scope: Option<Key>,
880 drawn: bool,
888}
889
890impl TextPlace {
891 fn answers_to(&self, key: Key) -> bool {
892 if self.key == key {
893 return true;
894 }
895 self.ancestors[..self.depth as usize]
899 .iter()
900 .position(|k| *k == key)
901 .is_some_and(|d| d <= self.none_at as usize)
902 }
903}
904
905pub(crate) struct ScopeRun<'a> {
911 pub place: &'a TextPlace,
912 pub text: &'a Entry,
914 pub base: usize,
915}
916
917impl ScopeRun<'_> {
918 pub(crate) fn span(&self) -> (usize, usize) {
921 (self.base, self.base + self.text.content().len())
922 }
923}
924
925#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
938pub struct TextHit {
939 pub byte: usize,
940 pub line: u32,
941}
942
943impl TextHit {
944 pub fn to_value(self) -> Value {
946 Value::map([
947 ("byte", Value::Int(self.byte as i64)),
948 ("line", Value::Int(self.line as i64)),
949 ])
950 }
951}
952
953#[derive(Clone, Copy, Debug, Default, PartialEq)]
958pub struct TextMetrics {
959 pub width: f32,
960 pub height: f32,
961 pub lines: u32,
963}
964
965impl TextMetrics {
966 pub fn to_value(self) -> Value {
968 Value::map([
969 ("width", Value::float(self.width)),
970 ("height", Value::float(self.height)),
971 ("lines", Value::Int(self.lines as i64)),
972 ])
973 }
974}
975
976pub struct TextSystem {
984 raster: Raster,
985 joins: Vec<JoinBg>,
988 entries: FxHashMap<u64, Entry>,
991 bytes: usize,
994 budget: usize,
995 frame: Kept<FrameText>,
1000 places: Kept<TextPlace>,
1004 scale: f32,
1005 frame_no: u64,
1006 owed: bool,
1009}
1010
1011pub(crate) fn cosmic_features(f: &crate::spec::FontFeatures) -> cosmic_text::FontFeatures {
1014 let mut out = cosmic_text::FontFeatures::new();
1015 for (tag, value) in f.iter() {
1016 out.set(cosmic_text::FeatureTag::new(tag), value);
1017 }
1018 out
1019}
1020
1021#[cfg(target_os = "macos")]
1032const DEFAULT_FAMILIES: [&[&str]; 3] = [
1033 &["Helvetica Neue", "Helvetica"],
1034 &["Times New Roman", "Times"],
1035 &["SF Mono", "Menlo", "Monaco"],
1036];
1037#[cfg(target_os = "windows")]
1038const DEFAULT_FAMILIES: [&[&str]; 3] = [
1039 &["Segoe UI", "Arial"],
1040 &["Times New Roman"],
1041 &["Cascadia Mono", "Consolas", "Courier New"],
1042];
1043#[cfg(not(any(target_os = "macos", target_os = "windows")))]
1044const DEFAULT_FAMILIES: [&[&str]; 3] = [
1045 &["DejaVu Sans", "Noto Sans", "Liberation Sans", "Ubuntu"],
1046 &["DejaVu Serif", "Noto Serif", "Liberation Serif"],
1047 &[
1048 "DejaVu Sans Mono",
1049 "Noto Sans Mono",
1050 "Liberation Mono",
1051 "Ubuntu Mono",
1052 ],
1053];
1054
1055fn first_installed<'a>(db: &cosmic_text::fontdb::Database, list: &[&'a str]) -> Option<&'a str> {
1058 list.iter().copied().find(|name| {
1059 db.faces()
1060 .any(|face| face.families.iter().any(|(f, _)| f == name))
1061 })
1062}
1063
1064pub(crate) fn new_font_system() -> (FontSystem, std::sync::Arc<SystemFonts>) {
1078 let system = system_fonts();
1079 let fonts = FontSystem::new_with_locale_and_db(system.locale.clone(), system.db.clone());
1080 (fonts, system)
1081}
1082
1083pub(crate) struct SystemFonts {
1087 locale: String,
1088 db: cosmic_text::fontdb::Database,
1089 pub(crate) faces: rustc_hash::FxHashSet<(std::path::PathBuf, u32)>,
1091}
1092
1093static SYSTEM: std::sync::Mutex<Option<std::sync::Arc<SystemFonts>>> = std::sync::Mutex::new(None);
1095
1096pub(crate) fn system_fonts() -> std::sync::Arc<SystemFonts> {
1100 let mut held = SYSTEM.lock().unwrap_or_else(|e| e.into_inner());
1101 held.get_or_insert_with(|| std::sync::Arc::new(scan_system_fonts()))
1102 .clone()
1103}
1104
1105pub(crate) fn rescan_system_fonts() -> std::sync::Arc<SystemFonts> {
1108 let fresh = std::sync::Arc::new(scan_system_fonts());
1109 *SYSTEM.lock().unwrap_or_else(|e| e.into_inner()) = Some(fresh.clone());
1110 fresh
1111}
1112
1113fn scan_system_fonts() -> SystemFonts {
1114 let (locale, db) = FontSystem::new().into_locale_and_db();
1115 SystemFonts::from_db(locale, db)
1116}
1117
1118impl SystemFonts {
1119 pub(crate) fn from_db(locale: String, mut db: cosmic_text::fontdb::Database) -> Self {
1122 let all: Vec<_> = db.faces().map(|face| face.id).collect();
1123 keep_measurable(&mut db, all);
1124 pin_default_families(&mut db);
1125 let faces = db.faces().filter_map(face_file).collect();
1126 Self { locale, db, faces }
1127 }
1128
1129 #[cfg(test)]
1131 pub(crate) fn db(&self) -> &cosmic_text::fontdb::Database {
1132 &self.db
1133 }
1134
1135 #[cfg(test)]
1136 pub(crate) fn locale(&self) -> &str {
1137 &self.locale
1138 }
1139}
1140
1141pub(crate) fn face_file(face: &cosmic_text::fontdb::FaceInfo) -> Option<(std::path::PathBuf, u32)> {
1144 use cosmic_text::fontdb::Source;
1145 match &face.source {
1146 Source::File(path) | Source::SharedFile(path, _) => Some((path.clone(), face.index)),
1147 Source::Binary(_) => None,
1148 }
1149}
1150
1151pub(crate) fn pin_default_families(db: &mut cosmic_text::fontdb::Database) {
1155 let [sans, serif, mono] = DEFAULT_FAMILIES;
1156 if let Some(name) = first_installed(db, sans) {
1157 db.set_sans_serif_family(name);
1158 }
1159 if let Some(name) = first_installed(db, serif) {
1160 db.set_serif_family(name);
1161 }
1162 if let Some(name) = first_installed(db, mono) {
1163 db.set_monospace_family(name);
1164 }
1165}
1166
1167#[cfg(test)]
1171fn font_system_with(locale: String, db: cosmic_text::fontdb::Database) -> FontSystem {
1172 let system = SystemFonts::from_db(locale, db);
1173 FontSystem::new_with_locale_and_db(system.locale, system.db)
1174}
1175
1176pub(crate) fn measurable(data: &[u8], index: u32) -> bool {
1187 use cosmic_text::skrifa::raw::{FontRef, TableProvider};
1188 let Ok(font) = FontRef::from_index(data, index) else {
1189 return false;
1190 };
1191 font.head()
1192 .is_ok_and(|head| (16..=16384).contains(&head.units_per_em()))
1193 && font.hhea().is_ok_and(|hhea| hhea.number_of_h_metrics() > 0)
1194 && font.hmtx().is_ok()
1195}
1196
1197const FILES_PER_CHECKER: usize = 64;
1200
1201pub(crate) fn keep_measurable(
1213 db: &mut cosmic_text::fontdb::Database,
1214 ids: Vec<cosmic_text::fontdb::ID>,
1215) -> Vec<cosmic_text::fontdb::ID> {
1216 use cosmic_text::fontdb::{ID, Source};
1217 let mut by_file = FxHashMap::<&std::path::Path, Vec<ID>>::default();
1219 let mut groups = Vec::new();
1220 for &id in &ids {
1221 match db.face(id).map(|face| &face.source) {
1222 Some(Source::File(path) | Source::SharedFile(path, _)) => {
1223 by_file.entry(path).or_default().push(id);
1224 }
1225 Some(Source::Binary(_)) => groups.push(vec![id]),
1226 None => {}
1227 }
1228 }
1229 groups.extend(by_file.into_values());
1230 let db_ref = &*db;
1231 let unmeasurable_in = |groups: &[Vec<ID>]| -> Vec<ID> {
1232 let mut out = Vec::new();
1233 for group in groups {
1234 let read = db_ref.with_face_data(group[0], |data, _| {
1235 group
1236 .iter()
1237 .filter(|&&id| {
1238 db_ref
1239 .face(id)
1240 .is_none_or(|face| !measurable(data, face.index))
1241 })
1242 .copied()
1243 .collect::<Vec<_>>()
1244 });
1245 out.extend(read.unwrap_or_else(|| group.clone()));
1246 }
1247 out
1248 };
1249 let checkers = std::thread::available_parallelism()
1250 .map_or(1, |n| n.get())
1251 .min(groups.len().div_ceil(FILES_PER_CHECKER));
1252 let unmeasurable = if checkers <= 1 {
1253 unmeasurable_in(&groups)
1254 } else {
1255 let per = groups.len().div_ceil(checkers);
1256 std::thread::scope(|scope| {
1257 let parts: Vec<_> = groups
1258 .chunks(per)
1259 .map(|part| {
1260 let spawned = std::thread::Builder::new()
1261 .name("kui-font-check".into())
1262 .spawn_scoped(scope, move || unmeasurable_in(part));
1263 (part, spawned.ok())
1264 })
1265 .collect();
1266 let mut out = Vec::new();
1267 for (part, checker) in parts {
1268 out.extend(match checker {
1269 Some(checker) => checker
1270 .join()
1271 .unwrap_or_else(|panic| std::panic::resume_unwind(panic)),
1272 None => unmeasurable_in(part),
1274 });
1275 }
1276 out
1277 })
1278 };
1279 for &id in &unmeasurable {
1280 db.remove_face(id);
1281 }
1282 ids.into_iter()
1283 .filter(|id| !unmeasurable.contains(id))
1284 .collect()
1285}
1286
1287pub(crate) fn default_families(fs: &FontSystem) -> [&str; 3] {
1291 let db = fs.db();
1292 [
1293 db.family_name(&cosmic_text::Family::SansSerif),
1294 db.family_name(&cosmic_text::Family::Serif),
1295 db.family_name(&cosmic_text::Family::Monospace),
1296 ]
1297}
1298
1299impl TextSystem {
1300 pub fn new() -> Self {
1301 Self {
1302 raster: Raster::new(),
1303 joins: Vec::new(),
1304 entries: FxHashMap::default(),
1305 bytes: 0,
1306 budget: DEFAULT_TEXT_CACHE_BYTES,
1307 frame: Kept::default(),
1308 places: Kept::default(),
1309 scale: 1.0,
1310 frame_no: 0,
1311 owed: false,
1312 }
1313 }
1314
1315 pub(crate) fn take_owed(&mut self) -> bool {
1318 std::mem::take(&mut self.owed)
1319 }
1320
1321 pub(crate) fn take_joins(&mut self) -> Vec<JoinBg> {
1324 std::mem::take(&mut self.joins)
1325 }
1326
1327 pub(crate) fn raster_mut(&mut self) -> &mut Raster {
1329 &mut self.raster
1330 }
1331
1332 pub(crate) fn subpixel(&self) -> bool {
1333 self.raster.subpixel
1334 }
1335
1336 pub(crate) fn set_subpixel(&mut self, on: bool) -> bool {
1339 let changed = self.raster.subpixel != on;
1340 self.raster.subpixel = on;
1341 changed
1342 }
1343
1344 pub fn budget(&self) -> usize {
1347 self.budget
1348 }
1349
1350 pub fn set_budget(&mut self, bytes: usize) {
1353 self.budget = bytes;
1354 }
1355
1356 pub fn bytes(&self) -> usize {
1358 self.bytes
1359 }
1360
1361 pub fn len(&self) -> usize {
1364 self.entries.len() - self.long_lines()
1365 }
1366
1367 pub fn long_lines(&self) -> usize {
1369 self.entries.values().filter(|e| e.long().is_some()).count()
1370 }
1371
1372 pub fn is_empty(&self) -> bool {
1373 self.len() == 0
1374 }
1375
1376 fn evict_to_budget(&mut self, fs: &mut FontSystem) {
1383 if self.bytes <= self.budget {
1384 return;
1385 }
1386 let floor = self.budget / EVICT_TO_DENOMINATOR * EVICT_TO_NUMERATOR;
1387 let drawn_last_frame = self.frame_no.saturating_sub(1);
1388 let mut order: Vec<(u64, u64)> = self
1393 .entries
1394 .iter()
1395 .filter(|(_, e)| e.last_used() < drawn_last_frame)
1396 .map(|(k, e)| (e.last_used(), *k))
1397 .collect();
1398 order.sort_unstable();
1399 for (_, key) in order {
1400 if self.bytes <= floor {
1401 break;
1402 }
1403 let freed = self.entries.remove(&key).map(|e| e.bytes());
1404 self.bytes -= freed.unwrap_or(0);
1405 }
1406 fs.shape_run_cache.trim(0);
1415 }
1416
1417 pub(crate) fn begin_frame(
1421 &mut self,
1422 fs: &mut FontSystem,
1423 scale: f32,
1424 keep_prev: bool,
1425 frame_no: u64,
1426 ) {
1427 self.joins.clear();
1428 if (scale - self.scale).abs() > f32::EPSILON {
1430 self.entries.clear();
1431 self.bytes = 0;
1432 }
1433 self.scale = scale;
1434 self.frame.begin(keep_prev);
1435 self.places.begin(true);
1438 self.frame_no = frame_no;
1440 if let Some(cutoff) = crate::retain::sweep_cutoff(self.frame_no) {
1441 let mut freed = 0usize;
1442 self.entries.retain(|_, e| {
1443 let keep = e.last_used() >= cutoff;
1444 if !keep {
1445 freed += e.bytes();
1446 }
1447 keep
1448 });
1449 self.bytes -= freed;
1450 fs.shape_run_cache.trim(2);
1453 }
1454 self.evict_to_budget(fs);
1458 }
1459
1460 pub(crate) fn forget_shaped(&mut self) {
1463 self.entries.clear();
1464 self.bytes = 0;
1465 }
1466
1467 fn insert(&mut self, key: u64, entry: Entry) {
1469 self.bytes += entry.bytes();
1470 if let Some(old) = self.entries.insert(key, entry) {
1471 self.bytes -= old.bytes();
1472 }
1473 }
1474
1475 fn run(&self, key: u64) -> Option<&CachedText> {
1477 self.entries.get(&key)?.run()
1478 }
1479
1480 fn run_mut(&mut self, key: u64) -> Option<&mut CachedText> {
1481 self.entries.get_mut(&key)?.run_mut()
1482 }
1483
1484 fn long(&self, key: u64) -> Option<&LongLine> {
1486 self.entries.get(&key)?.long()
1487 }
1488
1489 fn long_mut(&mut self, key: u64) -> Option<&mut LongLine> {
1490 self.entries.get_mut(&key)?.long_mut()
1491 }
1492
1493 pub(crate) fn style_key(content: &str, style: &TextStyle, scale: f32) -> u64 {
1494 let mut h = crate::key::mix_content(crate::key::FNV_OFFSET, content.as_bytes());
1497 let mut mix = |bytes: &[u8]| h = crate::key::fnv(h, bytes);
1498 mix(&style.size.to_bits().to_le_bytes());
1499 mix(&style.line_height.to_bits().to_le_bytes());
1500 mix(&scale.to_bits().to_le_bytes());
1501 mix(&[style.wrap as u8, style.ellipsis as u8]);
1502 mix(&style.max_lines.to_le_bytes());
1503 let (tag, font) = match style.family {
1504 FontFamily::Sans => (0u8, 0u64),
1505 FontFamily::Serif => (1, 0),
1506 FontFamily::Mono => (2, 0),
1507 FontFamily::Custom(id) => (3, id.to_ffi()),
1508 };
1509 mix(&[tag]);
1510 mix(&font.to_le_bytes());
1511 for (t, v) in style.features.iter() {
1512 mix(t);
1513 mix(&v.to_le_bytes());
1514 }
1515 mix(&[
1519 style.underline as u8,
1520 style.strikethrough as u8,
1521 style.underline_style as u8,
1522 style.underline_color.is_some() as u8,
1523 ]);
1524 if let Some(c) = style.underline_color {
1525 mix(&c.to_hex().to_le_bytes());
1526 }
1527 h
1528 }
1529
1530 fn intern(
1534 &mut self,
1535 content: &str,
1536 style: &TextStyle,
1537 res: &Resources,
1538 fs: &mut FontSystem,
1539 ) -> u64 {
1540 let key = Self::style_key(content, style, self.scale);
1541 self.intern_keyed(key, content, style, res, fs)
1542 }
1543
1544 fn intern_keyed(
1546 &mut self,
1547 key: u64,
1548 content: &str,
1549 style: &TextStyle,
1550 res: &Resources,
1551 fs: &mut FontSystem,
1552 ) -> u64 {
1553 let frame_no = self.frame_no;
1554 let scale = self.scale;
1555 if !self.entries.contains_key(&key) {
1556 let mut buffer = new_buffer(fs, style, scale);
1557 buffer.set_text(
1561 content,
1562 &res.weights_of(style.family).apply(
1563 Attrs::new()
1564 .family(res.family_of(style.family))
1565 .font_features(cosmic_features(&style.features)),
1566 false,
1567 ),
1568 Shaping::Advanced,
1569 None,
1570 );
1571 let entry = CachedText::new(
1572 buffer,
1573 content.to_string(),
1574 style,
1575 vec![SpanDeco::of_style(style)],
1576 fs,
1577 frame_no,
1578 );
1579 self.insert(key, Entry::Run(entry));
1580 }
1581 self.entries
1582 .get_mut(&key)
1583 .expect("just inserted")
1584 .touch(frame_no);
1585 key
1586 }
1587
1588 pub(crate) fn content(&self, id: TextId) -> &str {
1590 let key = self.frame[id.0 as usize].cache_key;
1591 self.entries.get(&key).map_or("", |e| e.content())
1592 }
1593
1594 pub(crate) fn access_runs(
1600 &self,
1601 id: TextId,
1602 src: crate::access::RunSource,
1603 run_no: &mut usize,
1604 out: &mut Vec<crate::access::AccessRun>,
1605 ) {
1606 use crate::access::{RowGlyphs, push_row_runs};
1607 let Some(ft) = self.frame.get(id.0 as usize) else {
1608 return;
1609 };
1610 let line = match self.entries.get(&ft.cache_key) {
1611 Some(Entry::Run(e)) => {
1612 crate::access::runs_of_buffer(&e.buffer, src, run_no, out);
1613 return;
1614 }
1615 Some(Entry::Long(line)) => line,
1616 None => return,
1617 };
1618 let whole = [RowStart { byte: 0, x: 0.0 }];
1619 for (i, c) in line.chunks.iter().enumerate() {
1620 let Some(run) = c
1621 .width
1622 .and_then(|_| self.run(c.key))
1623 .and_then(|e| e.buffer.layout_runs().next())
1624 else {
1625 continue;
1626 };
1627 let (rows, row0, head_x) = match (line.wrap_w, line.starts.get(i)) {
1630 (Some(_), Some(&(row0, head_x))) if !c.rows.is_empty() => {
1631 (&c.rows[..], row0, head_x)
1632 }
1633 (Some(_), _) => continue,
1634 (None, _) => (&whole[..], 0, line.prefix[i]),
1635 };
1636 for (r, rs) in rows.iter().enumerate() {
1637 let hi = rows.get(r + 1).map_or(usize::MAX, |n| n.byte as usize);
1638 let a = run.glyphs.partition_point(|g| g.start < rs.byte as usize);
1639 let b = run.glyphs.partition_point(|g| g.start < hi).max(a);
1640 if a == b {
1641 continue;
1642 }
1643 let last = i + 1 == line.chunks.len() && r + 1 == rows.len();
1644 push_row_runs(
1645 &RowGlyphs {
1646 glyphs: &run.glyphs[a..b],
1647 text: run.text,
1648 line: 0,
1649 top: (row0 as usize + r) as f32 * line.line_h,
1650 height: line.line_h,
1651 rtl: run.rtl,
1652 dx: if r == 0 { head_x } else { 0.0 } - rs.x,
1653 base: c.start,
1654 newline: last && src.newline_after_last,
1655 },
1656 &src,
1657 run_no,
1658 out,
1659 );
1660 }
1661 }
1662 }
1663
1664 pub(crate) fn prev_frame_text(&self, id: TextId) -> (u64, Color) {
1670 match self.frame.prev().get(id.0 as usize) {
1671 Some(t) => (t.cache_key, t.color),
1672 None => (0, Color::TRANSPARENT),
1673 }
1674 }
1675
1676 pub(crate) fn readd(&mut self, cache_key: u64, color: Color) -> Option<TextId> {
1682 let frame_no = self.frame_no;
1683 let e = self.entries.get_mut(&cache_key)?;
1684 e.touch(frame_no);
1685 let cache_key = if e.long().is_some() {
1686 self.claim_long(cache_key)
1687 } else {
1688 cache_key
1689 };
1690 self.frame.push(FrameText { cache_key, color });
1691 Some(TextId((self.frame.len() - 1) as u32))
1692 }
1693
1694 pub fn add(
1696 &mut self,
1697 content: &str,
1698 style: &TextStyle,
1699 res: &Resources,
1700 fs: &mut FontSystem,
1701 ) -> TextId {
1702 let key = self.intern_any(content, style, res, fs);
1705 let key = if could_be_long(content.len(), style) {
1706 self.claim_long(key)
1707 } else {
1708 key
1709 };
1710 self.frame.push(FrameText {
1711 cache_key: key,
1712 color: style.color_or_default(),
1713 });
1714 TextId((self.frame.len() - 1) as u32)
1715 }
1716
1717 #[inline(never)]
1726 fn claim_long(&mut self, key: u64) -> u64 {
1727 let frame_no = self.frame_no;
1728 let mut at = key;
1729 let mut n = 0u64;
1730 loop {
1731 match self.entries.get_mut(&at) {
1732 Some(Entry::Long(l)) if l.claimed != frame_no => {
1733 l.claimed = frame_no;
1734 l.last_used = frame_no;
1735 return at;
1736 }
1737 Some(Entry::Run(_)) if n == 0 => return key,
1739 Some(_) => {}
1740 None => {
1741 let Some(line) = self.long(key) else {
1742 return key;
1743 };
1744 let mut copy = line.clone();
1745 copy.claimed = frame_no;
1746 copy.last_used = frame_no;
1747 self.insert(at, Entry::Long(copy));
1748 return at;
1749 }
1750 }
1751 n += 1;
1752 at = crate::key::fnv(key ^ COPY_SALT, &n.to_le_bytes());
1753 }
1754 }
1755
1756 fn intern_any(
1762 &mut self,
1763 content: &str,
1764 style: &TextStyle,
1765 res: &Resources,
1766 fs: &mut FontSystem,
1767 ) -> u64 {
1768 if !could_be_long(content.len(), style) {
1769 return self.intern(content, style, res, fs);
1770 }
1771 let key = Self::style_key(content, style, self.scale);
1772 let long_key = key ^ LONG_SALT;
1773 let frame_no = self.frame_no;
1774 if let Some(e) = self.entries.get_mut(&long_key) {
1775 e.touch(frame_no);
1776 return long_key;
1777 }
1778 if let Some(e) = self.entries.get_mut(&key) {
1779 e.touch(frame_no);
1780 return key;
1781 }
1782 if has_line_break(content) || content.len() < LONG_LINE_BYTES && has_rtl(content) {
1783 self.intern_keyed(key, content, style, res, fs)
1784 } else {
1785 self.build_long(long_key, content.to_string(), Vec::new(), style, res, fs)
1786 }
1787 }
1788
1789 fn intern_rich_any(
1794 &mut self,
1795 spans: &[Span<'_>],
1796 base: &TextStyle,
1797 res: &Resources,
1798 fs: &mut FontSystem,
1799 ) -> u64 {
1800 let len: usize = spans.iter().map(|s| s.text.len()).sum();
1801 if !could_be_long(len, base) {
1802 return self.intern_rich(spans, base, res, fs);
1803 }
1804 let key = Self::rich_key(spans, base, self.scale);
1805 let long_key = key ^ LONG_SALT;
1806 let frame_no = self.frame_no;
1807 if let Some(e) = self.entries.get_mut(&long_key) {
1808 e.touch(frame_no);
1809 return long_key;
1810 }
1811 if let Some(e) = self.entries.get_mut(&key) {
1812 e.touch(frame_no);
1813 return key;
1814 }
1815 if spans.iter().any(|s| has_line_break(s.text))
1816 || len < LONG_LINE_BYTES && spans.iter().any(|s| has_rtl(s.text))
1817 {
1818 return self.intern_rich_keyed(key, spans, base, res, fs);
1819 }
1820 let mut content = String::with_capacity(len);
1821 let mut owned = Vec::with_capacity(spans.len());
1822 for s in spans {
1823 let start = content.len();
1824 content.push_str(s.text);
1825 owned.push(OwnedSpan {
1826 start,
1827 end: content.len(),
1828 attrs: s.attrs_only(),
1829 });
1830 }
1831 self.build_long(long_key, content, owned, base, res, fs)
1832 }
1833
1834 fn build_long(
1839 &mut self,
1840 key: u64,
1841 content: String,
1842 spans: Vec<OwnedSpan>,
1843 style: &TextStyle,
1844 res: &Resources,
1845 fs: &mut FontSystem,
1846 ) -> u64 {
1847 let frame_no = self.frame_no;
1848 let wrap = style.wrap;
1849 let style = &TextStyle {
1850 wrap: TextWrap::None,
1851 ..*style
1852 };
1853 let scale = self.scale;
1854 let chunks: Vec<Chunk> = chunk_ranges(&content)
1855 .into_iter()
1856 .map(|(start, end)| Chunk {
1857 start,
1858 end,
1859 key: if spans.is_empty() {
1860 Self::style_key(&content[start..end], style, scale)
1861 } else {
1862 Self::rich_key(&chunk_spans(&content, &spans, start, end), style, scale)
1863 },
1864 width: None,
1865 rows: Vec::new(),
1866 })
1867 .collect();
1868 let (w0, line_h) = match chunks.first() {
1871 Some(c) => {
1872 let k = self.shape_chunk(&content, &spans, c.start, c.end, style, res, fs);
1873 let e = self.run(k).expect("just interned");
1874 (e.intrinsic.w, e.buffer.metrics().line_height)
1875 }
1876 None => (0.0, style.line_height * self.scale),
1877 };
1878 let avg = chunks
1879 .first()
1880 .map_or(0.0, |c| w0 / (c.end - c.start).max(1) as f32);
1881 let mut line = LongLine {
1882 content,
1883 spans,
1884 style: *style,
1885 wrap,
1886 wrap_w: None,
1887 starts: Vec::new(),
1888 chunks,
1889 prefix: Vec::new(),
1890 line_h,
1891 avg,
1892 last_used: frame_no,
1893 claimed: u64::MAX,
1894 laid_rows: 1,
1895 asked_rows: u32::MAX,
1896 bytes: 0,
1897 };
1898 if let Some(c) = line.chunks.first_mut() {
1899 c.width = Some(w0);
1900 }
1901 line.reprefix();
1902 line.bytes = ENTRY_BASE_BYTES
1903 + line.content.len()
1904 + line.chunks.len() * 48
1905 + line.spans.len() * std::mem::size_of::<OwnedSpan>();
1906 self.insert(key, Entry::Long(line));
1910 key
1911 }
1912
1913 #[allow(clippy::too_many_arguments)]
1917 fn shape_chunk(
1918 &mut self,
1919 content: &str,
1920 spans: &[OwnedSpan],
1921 start: usize,
1922 end: usize,
1923 style: &TextStyle,
1924 res: &Resources,
1925 fs: &mut FontSystem,
1926 ) -> u64 {
1927 if spans.is_empty() {
1928 self.intern(&content[start..end], style, res, fs)
1929 } else {
1930 let spans = chunk_spans(content, spans, start, end);
1931 self.intern_rich(&spans, style, res, fs)
1932 }
1933 }
1934
1935 fn ensure_chunk(&mut self, key: u64, i: usize, res: &Resources, fs: &mut FontSystem) -> bool {
1939 let (chunk_key, known) = {
1940 let c = &self.long(key).expect("a long line").chunks[i];
1941 (c.key, c.width)
1942 };
1943 let frame_no = self.frame_no;
1944 if known.is_some()
1945 && let Some(e) = self.run_mut(chunk_key)
1946 {
1947 e.last_used = frame_no;
1948 return false;
1949 }
1950 let (text, spans, style) = {
1953 let line = self.long(key).expect("a long line");
1954 let c = &line.chunks[i];
1955 let first = line.spans.partition_point(|s| s.end <= c.start);
1956 let spans: Vec<OwnedSpan> = line.spans[first..]
1957 .iter()
1958 .take_while(|s| s.start < c.end)
1959 .map(|s| OwnedSpan {
1960 start: s.start.max(c.start) - c.start,
1961 end: s.end.min(c.end) - c.start,
1962 attrs: s.attrs,
1963 })
1964 .collect();
1965 (line.content[c.start..c.end].to_string(), spans, line.style)
1966 };
1967 let k = self.shape_chunk(&text, &spans, 0, text.len(), &style, res, fs);
1968 let w = self.run(k).expect("just interned").intrinsic.w;
1969 let line = self.long_mut(key).expect("just read");
1970 line.chunks[i].key = k;
1971 if line.chunks[i].width != Some(w) {
1972 line.chunks[i].width = Some(w);
1973 line.reprefix();
1974 }
1975 true
1976 }
1977
1978 fn relayout_long(&mut self, key: u64, w: Option<f32>) {
1986 let Some(w) = w else {
1987 let line = self.long_mut(key).expect("a long line");
1988 line.wrap_w = None;
1989 line.starts.clear();
1990 for c in &mut line.chunks {
1991 c.rows.clear();
1992 }
1993 return;
1994 };
1995 let w = w.max(1.0);
1996 let line = self.long(key).expect("a long line");
1999 let mut starts = Vec::with_capacity(line.chunks.len() + 1);
2000 starts.push((0, 0.0));
2001 let (mut row, mut x) = (0u32, 0.0f32);
2002 let rows: Vec<Vec<RowStart>> = line
2003 .chunks
2004 .iter()
2005 .map(|c| {
2006 let shaped = c.width.and_then(|_| self.run(c.key));
2007 let rows = match shaped {
2008 Some(e) => {
2009 let text = &line.content[c.start..c.end];
2010 let (rows, end) = break_rows(&e.buffer, text, line.wrap, w, x);
2011 row += rows.len() as u32 - 1;
2012 x = end;
2013 rows
2014 }
2015 None => {
2016 let est = x + c
2017 .width
2018 .unwrap_or_else(|| (c.end - c.start) as f32 * line.avg);
2019 let added = (est / w).floor();
2020 row += added as u32;
2021 x = est - added * w;
2022 Vec::new()
2023 }
2024 };
2025 starts.push((row, x));
2026 rows
2027 })
2028 .collect();
2029 let line = self.long_mut(key).expect("a long line");
2030 line.wrap_w = Some(w);
2031 line.starts = starts;
2032 for (c, rows) in line.chunks.iter_mut().zip(rows) {
2033 c.rows = rows;
2034 }
2035 }
2036
2037 fn long_size(&mut self, key: u64, max_w: Option<f32>) -> (Size, u32) {
2041 let (wrap, width, line_h, cur) = {
2042 let l = self.long(key).expect("a long line");
2043 (l.wrap, l.width(), l.line_h, l.wrap_w)
2044 };
2045 let target = match max_w {
2046 Some(w) if wrap != TextWrap::None && width > w + 0.5 => Some(w.max(1.0)),
2047 _ => None,
2048 };
2049 let differs = match (cur, target) {
2050 (None, None) => false,
2051 (Some(a), Some(b)) => (a - b).abs() > 0.5,
2052 _ => true,
2053 };
2054 if differs {
2055 self.relayout_long(key, target);
2056 }
2057 match target {
2058 Some(w) => {
2059 let rows = self.long(key).expect("a long line").rows();
2060 (Size::new(w, rows as f32 * line_h), rows)
2061 }
2062 None => (Size::new(max_w.map_or(width, |m| width.min(m)), line_h), 1),
2063 }
2064 }
2065
2066 pub fn measure(
2072 &mut self,
2073 content: &str,
2074 style: &TextStyle,
2075 res: &Resources,
2076 fs: &mut FontSystem,
2077 max_w: Option<f32>,
2078 ) -> TextMetrics {
2079 let key = self.intern_any(content, style, res, fs);
2080 self.measure_any(key, fs, max_w)
2081 }
2082
2083 fn measure_any(&mut self, key: u64, fs: &mut FontSystem, max_w: Option<f32>) -> TextMetrics {
2085 if self.long(key).is_some() {
2086 let scale = self.scale;
2087 let (size, lines) = match max_w {
2090 Some(m) => {
2091 let held = self.long(key).expect("checked").wrap_w;
2094 let measured = self.long_size(key, Some(m * scale));
2095 if wrap_differs(held, self.long(key).expect("checked").wrap_w) {
2096 self.relayout_long(key, held);
2097 }
2098 measured
2099 }
2100 None => {
2101 let line = self.long(key).expect("checked");
2102 (Size::new(line.width(), line.line_h), 1)
2103 }
2104 };
2105 return TextMetrics {
2106 width: size.w / scale,
2107 height: size.h / scale,
2108 lines,
2109 };
2110 }
2111 self.measure_key(key, fs, max_w)
2112 }
2113
2114 pub fn measure_rich(
2116 &mut self,
2117 spans: &[Span<'_>],
2118 base: &TextStyle,
2119 res: &Resources,
2120 fs: &mut FontSystem,
2121 max_w: Option<f32>,
2122 ) -> TextMetrics {
2123 let key = self.intern_rich_any(spans, base, res, fs);
2124 self.measure_any(key, fs, max_w)
2125 }
2126
2127 fn measure_key(&mut self, key: u64, fs: &mut FontSystem, max_w: Option<f32>) -> TextMetrics {
2128 let scale = self.scale;
2129 let entry = self.run_mut(key).expect("just interned");
2130 let target = wrap_target(entry, max_w, scale);
2131 wrap_entry(entry, fs, target);
2132 let (mut m, lines) = measure_buffer(&entry.buffer, entry.max_lines);
2133 if entry.clamp_w
2134 && let Some(t) = target
2135 {
2136 m.w = m.w.min(t);
2137 }
2138 TextMetrics {
2139 width: m.w / scale,
2140 height: m.h / scale,
2141 lines,
2142 }
2143 }
2144
2145 pub fn add_rich(
2149 &mut self,
2150 spans: &[Span<'_>],
2151 base: &TextStyle,
2152 res: &Resources,
2153 fs: &mut FontSystem,
2154 ) -> TextId {
2155 let key = self.intern_rich_any(spans, base, res, fs);
2156 let len = spans.iter().map(|s| s.text.len()).sum();
2157 let key = if could_be_long(len, base) {
2158 self.claim_long(key)
2159 } else {
2160 key
2161 };
2162 self.frame.push(FrameText {
2163 cache_key: key,
2164 color: base.color_or_default(),
2165 });
2166 TextId((self.frame.len() - 1) as u32)
2167 }
2168
2169 fn intern_rich(
2170 &mut self,
2171 spans: &[Span<'_>],
2172 base: &TextStyle,
2173 res: &Resources,
2174 fs: &mut FontSystem,
2175 ) -> u64 {
2176 let key = Self::rich_key(spans, base, self.scale);
2177 self.intern_rich_keyed(key, spans, base, res, fs)
2178 }
2179
2180 fn rich_key(spans: &[Span<'_>], base: &TextStyle, scale: f32) -> u64 {
2184 let mut key = Self::style_key("", base, scale) ^ 0x9e37_79b9_7f4a_7c15;
2185 for s in spans {
2186 key = crate::key::mix_content(key, s.text.as_bytes());
2187 let mut mix = |bytes: &[u8]| key = crate::key::fnv(key, bytes);
2188 mix(&[
2189 s.bold as u8,
2190 s.italic as u8,
2191 s.color.is_some() as u8,
2192 s.underline as u8,
2193 s.strikethrough as u8,
2194 s.bg.is_some() as u8,
2195 s.underline_style as u8,
2196 s.underline_color.is_some() as u8,
2197 ]);
2198 mix(&s.bg_radius.to_bits().to_le_bytes());
2199 for c in [s.color, s.bg, s.underline_color].into_iter().flatten() {
2200 mix(&c.r.to_bits().to_le_bytes());
2201 mix(&c.g.to_bits().to_le_bytes());
2202 mix(&c.b.to_bits().to_le_bytes());
2203 mix(&c.a.to_bits().to_le_bytes());
2204 }
2205 }
2206 key
2207 }
2208
2209 fn intern_rich_keyed(
2211 &mut self,
2212 key: u64,
2213 spans: &[Span<'_>],
2214 base: &TextStyle,
2215 res: &Resources,
2216 fs: &mut FontSystem,
2217 ) -> u64 {
2218 let frame_no = self.frame_no;
2219 let scale = self.scale;
2220 if !self.entries.contains_key(&key) {
2221 let mut buffer = new_buffer(fs, base, scale);
2222 let family = res.family_of(base.family);
2223 let weights = res.weights_of(base.family);
2224 let features = cosmic_features(&base.features);
2225 buffer.set_rich_text(
2228 spans.iter().enumerate().map(|(i, s)| {
2229 (
2230 s.text,
2231 s.attrs(family, weights)
2232 .font_features(features.clone())
2233 .metadata(i),
2234 )
2235 }),
2236 &weights.apply(
2237 Attrs::new().family(family).font_features(features.clone()),
2238 false,
2239 ),
2240 Shaping::Advanced,
2241 None,
2242 );
2243 let content = spans.iter().map(|s| s.text).collect::<String>();
2244 let decos = spans
2245 .iter()
2246 .map(|s| SpanDeco {
2247 underline: s.underline || base.underline,
2248 underline_color: s.underline_color.or(base.underline_color),
2250 underline_style: if s.underline {
2251 s.underline_style
2252 } else {
2253 base.underline_style
2254 },
2255 strikethrough: s.strikethrough || base.strikethrough,
2256 bg: s.bg,
2257 bg_radius: s.bg_radius,
2258 })
2259 .collect();
2260 let entry = CachedText::new(buffer, content, base, decos, fs, frame_no);
2261 self.insert(key, Entry::Run(entry));
2262 }
2263 self.entries
2264 .get_mut(&key)
2265 .expect("just inserted")
2266 .touch(frame_no);
2267 key
2268 }
2269
2270 fn entry_mut(&mut self, id: TextId) -> &mut CachedText {
2273 let key = self.frame[id.0 as usize].cache_key;
2274 self.run_mut(key).expect("frame text missing from cache")
2275 }
2276
2277 fn ensure_wrap(&mut self, id: TextId, max_w_logical: f32, fs: &mut FontSystem) {
2282 let (scale, frame_no) = (self.scale, self.frame_no);
2283 let entry = self.entry_mut(id);
2284 let target = wrap_target(entry, Some(max_w_logical), scale);
2285 if entry.claimed == frame_no && wrap_differs(entry.claimed_wrap, target) {
2286 self.own_wrap(id, target, fs);
2287 return;
2288 }
2289 entry.claimed = frame_no;
2290 entry.claimed_wrap = target;
2291 wrap_entry(entry, fs, target);
2292 }
2293
2294 #[inline(never)]
2302 fn own_wrap(&mut self, id: TextId, target: Option<f32>, fs: &mut FontSystem) {
2303 let frame_no = self.frame_no;
2304 let key = self.frame[id.0 as usize].cache_key;
2305 let slot = target.map_or(u64::MAX, |t| (t * 2.0).round() as u64);
2307 let copy = crate::key::fnv(key ^ COPY_SALT, &slot.to_le_bytes());
2308 if self.run(copy).is_none() {
2309 let fork = self.run(key).expect("frame text").fork(frame_no);
2310 self.insert(copy, Entry::Run(fork));
2311 }
2312 self.frame[id.0 as usize].cache_key = copy;
2313 let entry = self.run_mut(copy).expect("just made");
2314 entry.last_used = frame_no;
2315 entry.claimed = frame_no;
2316 entry.claimed_wrap = target;
2317 wrap_entry(entry, fs, target);
2318 }
2319
2320 #[allow(clippy::too_many_arguments)]
2325 pub(crate) fn emit(
2326 &mut self,
2327 id: TextId,
2328 origin: Vec2,
2329 node: Size,
2330 clip: Clip,
2331 clip_id: ClipId,
2332 clips: &mut Vec<Clip>,
2333 res: &Resources,
2334 fs: &mut FontSystem,
2335 atlas: &mut GlyphAtlas,
2336 out: &mut Vec<Quad>,
2337 sel: Option<((usize, usize), Color)>,
2338 ) {
2339 let from = self.joins.len();
2340 self.emit_text(
2341 id, origin, node, clip, clip_id, clips, res, fs, atlas, out, sel,
2342 );
2343 if self.joins.len() == from {
2344 return;
2345 }
2346 let key = self.frame[id.0 as usize].cache_key;
2349 let clamps = match self.entries.get(&key) {
2350 Some(Entry::Long(l)) => l.wrap == TextWrap::None,
2351 Some(Entry::Run(e)) => e.clamp_w,
2352 None => false,
2353 };
2354 let own = clamps.then(|| {
2355 let ox = crate::geom::snap_px(origin.x * self.scale);
2356 (ox, ox + (node.w * self.scale).ceil())
2357 });
2358 for j in &mut self.joins[from..] {
2359 j.outer = clip_id;
2360 j.own = own;
2361 }
2362 }
2363
2364 #[allow(clippy::too_many_arguments)]
2370 #[inline(never)]
2371 fn emit_long(
2372 &mut self,
2373 key: u64,
2374 node: Size,
2375 ox: f32,
2376 oy: f32,
2377 nudge: Vec2,
2378 color: Color,
2379 clip: Clip,
2380 clip_id: ClipId,
2381 clips: &mut Vec<Clip>,
2382 res: &Resources,
2383 fs: &mut FontSystem,
2384 atlas: &mut GlyphAtlas,
2385 out: &mut Vec<Quad>,
2386 sel: Option<((usize, usize), Color)>,
2387 ) {
2388 let scale = self.scale;
2389 let line = self.long(key).expect("a long line");
2390 let (clip, clip_id) = if line.wrap == TextWrap::None {
2396 let own = Rect::new(ox, oy, (node.w * scale).ceil(), (node.h * scale).ceil());
2397 let clip = clip.intersect(own, crate::display::SQUARE);
2398 if clip.rect.w <= 0.0 || clip.rect.h <= 0.0 {
2399 return;
2400 }
2401 (clip, crate::display::intern_clip(clips, clip))
2402 } else {
2403 (clip, clip_id)
2404 };
2405 if let Some(((from, to), tint)) = sel {
2406 let rects = self.long_highlight(line, from, to);
2407 push_highlight(&rects, ox, oy, nudge, tint, clip_id, out);
2408 }
2409 if let Some(w) = line.wrap_w {
2410 self.emit_long_rows(
2411 key, w, ox, oy, nudge, color, clip, clip_id, res, fs, atlas, out,
2412 );
2413 return;
2414 }
2415 let (first, last) = {
2416 if line.chunks.is_empty() {
2417 return;
2418 }
2419 let a = line.chunk_at(clip.rect.x - ox).saturating_sub(1);
2420 let b = (line.chunk_at(clip.rect.x + clip.rect.w - ox) + 1).min(line.chunks.len() - 1);
2421 (a, b)
2422 };
2423 for i in first..=last {
2424 self.ensure_chunk(key, i, res, fs);
2425 }
2426 let frame_no = self.frame_no;
2427 self.long_mut(key).expect("checked").last_used = frame_no;
2428 for i in first..=last {
2429 let (chunk_key, x) = {
2430 let line = self.long(key).expect("checked");
2431 (line.chunks[i].key, line.prefix[i])
2432 };
2433 let raster = &mut self.raster;
2434 let entry = self
2435 .entries
2436 .get_mut(&chunk_key)
2437 .and_then(Entry::run_mut)
2438 .expect("just ensured");
2439 emit_entry(
2440 entry,
2441 ox + x,
2442 oy,
2443 nudge,
2444 color,
2445 clip,
2446 clip_id,
2447 raster,
2448 fs,
2449 atlas,
2450 out,
2451 &mut self.joins,
2452 );
2453 }
2454 }
2455
2456 #[allow(clippy::too_many_arguments)]
2458 fn emit_text(
2459 &mut self,
2460 id: TextId,
2461 origin: Vec2,
2462 node: Size,
2463 clip: Clip,
2464 clip_id: ClipId,
2465 clips: &mut Vec<Clip>,
2466 res: &Resources,
2467 fs: &mut FontSystem,
2468 atlas: &mut GlyphAtlas,
2469 out: &mut Vec<Quad>,
2470 sel: Option<((usize, usize), Color)>,
2475 ) {
2476 let FrameText {
2477 cache_key: key,
2478 color,
2479 } = self.frame[id.0 as usize];
2480 let scale = self.scale;
2481 let ox = crate::geom::snap_px(origin.x * scale);
2482 let oy = crate::geom::snap_px(origin.y * scale);
2483 let nudge = Vec2::new(origin.x * scale - ox, origin.y * scale - oy);
2486 if self.long(key).is_some() {
2489 self.emit_long(
2490 key, node, ox, oy, nudge, color, clip, clip_id, clips, res, fs, atlas, out, sel,
2491 );
2492 return;
2493 }
2494 self.ensure_wrap(id, node.w, fs);
2495 let raster = &mut self.raster;
2496 let entry = self
2497 .entries
2498 .get_mut(&key)
2499 .and_then(Entry::run_mut)
2500 .expect("frame text missing from cache");
2501
2502 let (clip, clip_id) = if entry.clamp_w {
2505 let own = Rect::new(ox, oy, (node.w * scale).ceil(), (node.h * scale).ceil());
2506 let clip = clip.intersect(own, crate::display::SQUARE);
2507 (clip, crate::display::intern_clip(clips, clip))
2508 } else {
2509 (clip, clip_id)
2510 };
2511 if let Some(((from, to), tint)) = sel {
2512 let rects = Self::run_highlight(entry, from, to);
2513 push_highlight(&rects, ox, oy, nudge, tint, clip_id, out);
2514 }
2515 emit_entry(
2516 entry,
2517 ox,
2518 oy,
2519 nudge,
2520 color,
2521 clip,
2522 clip_id,
2523 raster,
2524 fs,
2525 atlas,
2526 out,
2527 &mut self.joins,
2528 );
2529 }
2530}
2531
2532fn on_pixels(x: f32, y: f32, w: f32, h: f32, nudge: Vec2) -> Rect {
2546 Rect::new(x + nudge.x, y + nudge.y, w, h).on_pixels()
2547}
2548
2549fn push_highlight(
2552 rects: &[Rect],
2553 ox: f32,
2554 oy: f32,
2555 nudge: Vec2,
2556 tint: Color,
2557 clip: ClipId,
2558 out: &mut Vec<Quad>,
2559) {
2560 for r in rects {
2561 out.push(Quad {
2562 rect: on_pixels(ox + r.x, oy + r.y, r.w, r.h, nudge),
2563 color: tint,
2564 border_color: Color::TRANSPARENT,
2565 radius: [0.0; 4],
2566 border_w: 0.0,
2567 blur: 0.0,
2568 kind: QuadKind::Solid,
2569 uv: [0; 4],
2570 clip,
2571 });
2572 }
2573}
2574
2575impl TextSystem {
2576 #[allow(clippy::too_many_arguments)]
2580 fn emit_long_rows(
2581 &mut self,
2582 key: u64,
2583 w: f32,
2584 ox: f32,
2585 oy: f32,
2586 nudge: Vec2,
2587 color: Color,
2588 clip: Clip,
2589 clip_id: ClipId,
2590 res: &Resources,
2591 fs: &mut FontSystem,
2592 atlas: &mut GlyphAtlas,
2593 out: &mut Vec<Quad>,
2594 ) {
2595 let (first, last) = {
2596 let line = self.long(key).expect("a long line");
2597 let ra = ((clip.rect.y - oy) / line.line_h).floor().max(0.0) as u32;
2598 let rb = ((clip.rect.y + clip.rect.h - oy) / line.line_h)
2599 .floor()
2600 .max(0.0) as u32;
2601 let Some((a, b)) = line.chunks_on_rows(ra, rb) else {
2602 return;
2603 };
2604 (a.saturating_sub(1), (b + 1).min(line.chunks.len() - 1))
2605 };
2606 let mut fresh = false;
2607 for i in first..=last {
2608 fresh |= self.ensure_chunk(key, i, res, fs);
2609 }
2610 if fresh {
2611 self.relayout_long(key, Some(w));
2614 let line = self.long_mut(key).expect("checked");
2615 let rows = line.rows();
2616 if rows != line.laid_rows && rows != line.asked_rows {
2617 line.asked_rows = rows;
2618 self.owed = true;
2619 }
2620 }
2621 let frame_no = self.frame_no;
2622 self.long_mut(key).expect("checked").last_used = frame_no;
2623 for i in first..=last {
2624 let chunk_key = self.long(key).expect("checked").chunks[i].key;
2625 let [Some(Entry::Long(line)), Some(Entry::Run(entry))] =
2629 self.entries.get_disjoint_mut([&key, &chunk_key])
2630 else {
2631 continue;
2632 };
2633 let (row0, head_x) = line.starts[i];
2634 let chunk = &line.chunks[i];
2635 if chunk.rows.is_empty() {
2636 continue;
2637 }
2638 let raster = &mut self.raster;
2639 emit_entry_rows(
2640 entry,
2641 ox,
2642 oy + row0 as f32 * line.line_h,
2643 nudge,
2644 head_x,
2645 &chunk.rows,
2646 line.line_h,
2647 color,
2648 clip,
2649 clip_id,
2650 raster,
2651 fs,
2652 atlas,
2653 out,
2654 &mut self.joins,
2655 );
2656 }
2657 }
2658}
2659
2660#[allow(clippy::too_many_arguments)]
2665fn emit_entry_rows(
2666 entry: &mut CachedText,
2667 ox: f32,
2668 oy: f32,
2669 nudge: Vec2,
2670 head_x: f32,
2671 rows: &[RowStart],
2672 line_h: f32,
2673 color: Color,
2674 clip: Clip,
2675 clip_id: ClipId,
2676 raster: &mut Raster,
2677 fs: &mut FontSystem,
2678 atlas: &mut GlyphAtlas,
2679 out: &mut Vec<Quad>,
2680 joins: &mut Vec<JoinBg>,
2681) {
2682 build_templates(entry, raster, fs, atlas);
2683 let mut row_pieces = |d: &DecoTemplate, out: &mut Vec<Quad>| {
2689 let (x0, x1) = (d.x, d.x + d.w);
2690 for r in 0..rows.len() {
2691 let ra = rows[r].x;
2692 let rb = rows.get(r + 1).map_or(f32::INFINITY, |n| n.x);
2693 let (a, b) = (x0.max(ra), x1.min(rb));
2694 if b <= a {
2695 continue;
2696 }
2697 let dx = if r == 0 { head_x } else { 0.0 } - ra;
2698 let x = ox + a + dx;
2699 let y = oy + d.y + r as f32 * line_h;
2700 if y >= clip.rect.y + clip.rect.h {
2701 break;
2702 }
2703 if y + d.h <= clip.rect.y
2704 || x >= clip.rect.x + clip.rect.w
2705 || x + (b - a) <= clip.rect.x
2706 {
2707 continue;
2708 }
2709 let quad = Quad {
2710 rect: if d.under {
2711 on_pixels(x, y, b - a, d.h, nudge)
2712 } else {
2713 Rect::new(x, y, b - a, d.h)
2714 },
2715 color: d.color.unwrap_or(color),
2716 border_color: Color::TRANSPARENT,
2717 radius: [0.0; 4],
2718 border_w: 0.0,
2719 blur: 0.0,
2720 kind: QuadKind::Solid,
2721 clip: clip_id,
2722 uv: [0; 4],
2723 };
2724 if d.under && d.radius > 0.0 {
2728 joins.push(JoinBg {
2729 quad: out.len() as u32,
2730 radius: d.radius,
2731 outer: clip_id,
2732 own: None,
2733 });
2734 }
2735 if d.under || d.style == UnderlineStyle::Solid {
2736 out.push(quad);
2737 } else {
2738 crate::deco::push_line(
2739 out,
2740 d.style,
2741 x,
2742 y,
2743 b - a,
2744 d.h,
2745 d.color.unwrap_or(color),
2746 clip_id,
2747 );
2748 }
2749 }
2750 };
2751 for d in entry.deco.iter().filter(|d| d.under) {
2752 row_pieces(d, out);
2753 }
2754 let mut r = 0usize;
2755 for g in &entry.glyphs {
2756 while r + 1 < rows.len() && g.byte >= rows[r + 1].byte {
2757 r += 1;
2758 }
2759 let dx = if r == 0 { head_x } else { 0.0 } - rows[r].x;
2760 let x = ox + g.x + dx;
2761 let y = oy + g.y + r as f32 * line_h;
2762 if y >= clip.rect.y + clip.rect.h {
2769 break;
2770 }
2771 if y + g.h <= clip.rect.y || x >= clip.rect.x + clip.rect.w || x + g.w <= clip.rect.x {
2772 continue;
2773 }
2774 out.push(Quad {
2775 rect: Rect::new(x, y, g.w, g.h),
2776 color: g.color.unwrap_or(color),
2777 border_color: Color::TRANSPARENT,
2778 radius: [0.0; 4],
2779 border_w: 0.0,
2780 blur: 0.0,
2781 kind: g.kind,
2782 clip: clip_id,
2783 uv: g.uv,
2784 });
2785 }
2786 for d in entry.deco.iter().filter(|d| !d.under) {
2787 row_pieces(d, out);
2788 }
2789}
2790
2791fn break_rows(
2804 buffer: &Buffer,
2805 text: &str,
2806 wrap: TextWrap,
2807 w: f32,
2808 head_x: f32,
2809) -> (Vec<RowStart>, f32) {
2810 let mut rows = vec![RowStart { byte: 0, x: 0.0 }];
2811 let Some(run) = buffer.layout_runs().next() else {
2812 return (rows, head_x);
2813 };
2814 let glyphs = run.glyphs;
2815 let blank = |g: &cosmic_text::LayoutGlyph| {
2816 text.get(g.start..g.end)
2817 .is_some_and(|s| s.chars().all(char::is_whitespace))
2818 };
2819 let spaces = wrap == TextWrap::BreakSpaces;
2820 let mut pieces: Vec<(usize, usize)> = Vec::new();
2821 match wrap {
2822 TextWrap::Word | TextWrap::BreakSpaces => {
2823 let mut at = 0usize;
2824 let mut piece = |from: usize, to: usize| {
2825 if !spaces {
2826 pieces.push((from, to));
2827 return;
2828 }
2829 let ink = text[from..to].trim_end_matches(char::is_whitespace).len();
2832 if ink > 0 {
2833 pieces.push((from, from + ink));
2834 }
2835 for (i, c) in text[from + ink..to].char_indices() {
2836 let at = from + ink + i;
2837 pieces.push((at, at + c.len_utf8()));
2838 }
2839 };
2840 for (i, _) in unicode_linebreak::linebreaks(text) {
2841 if i > at {
2842 piece(at, i);
2843 at = i;
2844 }
2845 }
2846 if at < text.len() {
2847 piece(at, text.len());
2848 }
2849 }
2850 TextWrap::Glyph | TextWrap::None => {
2851 pieces.extend(glyphs.iter().map(|g| (g.start, g.end)));
2852 }
2853 }
2854 let mut row_x0 = 0.0f32;
2855 let mut avail = w - head_x;
2856 let mut gi = 0usize;
2857 for (s, e) in pieces {
2858 let g0 = gi;
2859 while gi < glyphs.len() && glyphs[gi].start < e {
2860 gi += 1;
2861 }
2862 if g0 == gi {
2863 continue;
2864 }
2865 let piece = &glyphs[g0..gi];
2866 let x0 = piece[0].x;
2867 let ink_end = piece
2868 .iter()
2869 .rev()
2870 .find(|g| spaces || !blank(g))
2871 .map_or(x0, |g| g.x + g.w);
2872 let opens = x0 > row_x0 || (rows.len() == 1 && head_x > 0.0);
2878 if ink_end - row_x0 > avail && opens {
2879 rows.push(RowStart {
2880 byte: s as u32,
2881 x: x0,
2882 });
2883 row_x0 = x0;
2884 avail = w;
2885 }
2886 if ink_end - row_x0 > avail {
2887 for g in piece {
2889 if g.x + g.w - row_x0 > avail && g.x > row_x0 && (spaces || !blank(g)) {
2890 rows.push(RowStart {
2891 byte: g.start as u32,
2892 x: g.x,
2893 });
2894 row_x0 = g.x;
2895 avail = w;
2896 }
2897 }
2898 }
2899 }
2900 let end = if rows.len() == 1 {
2901 head_x + run.line_w
2902 } else {
2903 run.line_w - row_x0
2904 };
2905 (rows, end)
2906}
2907
2908fn build_templates(
2911 entry: &mut CachedText,
2912 raster: &mut Raster,
2913 fs: &mut FontSystem,
2914 atlas: &mut GlyphAtlas,
2915) {
2916 {
2917 let built_for = (entry.wrap.map(f32::to_bits), atlas.stamp);
2919 if entry.glyphs_built_for != Some(built_for) {
2920 entry.glyphs.clear();
2921 entry.deco.clear();
2922 let lines = line_cap(entry.max_lines);
2923 let decorated = entry.span_deco.iter().any(SpanDeco::any);
2924 for run in entry.buffer.layout_runs().take(lines) {
2925 if decorated {
2926 build_decorations(&run, &entry.span_deco, fs, &mut entry.deco);
2927 }
2928 for glyph in run.glyphs.iter() {
2929 let physical = glyph.physical((0.0, 0.0), 1.0);
2930 let Some(slot) = raster_glyph(physical.cache_key, fs, raster, atlas) else {
2931 continue;
2932 };
2933 entry.glyphs.push(GlyphTemplate {
2934 x: physical.x as f32 + slot.left as f32,
2935 y: run.line_y.round() + physical.y as f32 - slot.top as f32,
2936 w: slot.w as f32,
2937 h: slot.h as f32,
2938 uv: [slot.x, slot.y, slot.w, slot.h],
2939 kind: glyph_kind(&slot),
2940 color: glyph
2941 .color_opt
2942 .map(|c| Color::rgba8(c.r(), c.g(), c.b(), c.a())),
2943 byte: glyph.start as u32,
2944 });
2945 }
2946 }
2947 entry.glyphs_built_for = Some((entry.wrap.map(f32::to_bits), atlas.stamp));
2951 }
2952 }
2953}
2954
2955#[allow(clippy::too_many_arguments)]
2959fn emit_entry(
2960 entry: &mut CachedText,
2961 ox: f32,
2962 oy: f32,
2963 nudge: Vec2,
2964 color: Color,
2965 clip: Clip,
2966 clip_id: ClipId,
2967 raster: &mut Raster,
2968 fs: &mut FontSystem,
2969 atlas: &mut GlyphAtlas,
2970 out: &mut Vec<Quad>,
2971 joins: &mut Vec<JoinBg>,
2972) {
2973 build_templates(entry, raster, fs, atlas);
2974 {
2975 let inside = |x: f32, y: f32, w: f32, h: f32| {
2976 oy + y + h >= clip.rect.y
2977 && oy + y <= clip.rect.y + clip.rect.h
2978 && ox + x < clip.rect.x + clip.rect.w
2979 && ox + x + w > clip.rect.x
2980 };
2981 let deco_quad = |d: &DecoTemplate| Quad {
2982 rect: Rect::new(ox + d.x, oy + d.y, d.w, d.h),
2983 color: d.color.unwrap_or(color),
2984 border_color: Color::TRANSPARENT,
2985 radius: [0.0; 4],
2986 border_w: 0.0,
2987 blur: 0.0,
2988 kind: QuadKind::Solid,
2989 clip: clip_id,
2990 uv: [0; 4],
2991 };
2992 for d in entry
2997 .deco
2998 .iter()
2999 .filter(|d| d.under && inside(d.x, d.y, d.w, d.h))
3000 {
3001 if d.radius > 0.0 {
3002 joins.push(JoinBg {
3003 quad: out.len() as u32,
3004 radius: d.radius,
3005 outer: clip_id,
3006 own: None,
3007 });
3008 }
3009 out.push(Quad {
3010 rect: on_pixels(ox + d.x, oy + d.y, d.w, d.h, nudge),
3011 ..deco_quad(d)
3012 });
3013 }
3014
3015 out.extend(
3019 entry
3020 .glyphs
3021 .iter()
3022 .filter(|g| {
3023 oy + g.y + g.h >= clip.rect.y
3024 && ox + g.x < clip.rect.x + clip.rect.w
3025 && ox + g.x + g.w > clip.rect.x
3026 })
3027 .take_while(|g| oy + g.y <= clip.rect.y + clip.rect.h)
3028 .map(|g| Quad {
3029 rect: Rect::new(ox + g.x, oy + g.y, g.w, g.h),
3030 color: g.color.unwrap_or(color),
3031 border_color: Color::TRANSPARENT,
3032 radius: [0.0; 4],
3033 border_w: 0.0,
3034 blur: 0.0,
3035 kind: g.kind,
3036 clip: clip_id,
3037 uv: g.uv,
3038 }),
3039 );
3040 for d in entry
3041 .deco
3042 .iter()
3043 .filter(|d| !d.under && inside(d.x, d.y, d.w, d.h))
3044 {
3045 match d.style {
3048 UnderlineStyle::Solid => out.push(deco_quad(d)),
3049 style => crate::deco::push_line(
3050 out,
3051 style,
3052 ox + d.x,
3053 oy + d.y,
3054 d.w,
3055 d.h,
3056 d.color.unwrap_or(color),
3057 clip_id,
3058 ),
3059 }
3060 }
3061 }
3062}
3063
3064fn could_be_long(len: usize, style: &TextStyle) -> bool {
3072 (len >= LONG_LINE_BYTES || len > 0 && style.wrap == TextWrap::BreakSpaces)
3073 && style.max_lines == 0
3074 && !style.ellipsis
3075}
3076
3077fn has_line_break(content: &str) -> bool {
3080 content.bytes().any(|b| b == b'\n' || b == b'\r')
3081}
3082
3083fn has_rtl(content: &str) -> bool {
3091 !content.is_ascii()
3092 && content.chars().any(|c| {
3093 matches!(c as u32,
3094 0x0590..=0x08FF
3095 | 0x200F | 0x202B | 0x202E | 0x2067
3096 | 0xFB1D..=0xFDFF
3097 | 0xFE70..=0xFEFF
3098 | 0x10800..=0x10FFF
3099 | 0x1E800..=0x1EFFF)
3100 })
3101}
3102
3103fn build_decorations(
3114 run: &cosmic_text::LayoutRun<'_>,
3115 spans: &[SpanDeco],
3116 fs: &mut FontSystem,
3117 out: &mut Vec<DecoTemplate>,
3118) {
3119 let mut last_bg: Option<usize> = None;
3122 let mut i = 0;
3123 while i < run.glyphs.len() {
3124 let span_no = run.glyphs[i].metadata;
3125 let mut j = i + 1;
3126 while j < run.glyphs.len() && run.glyphs[j].metadata == span_no {
3127 j += 1;
3128 }
3129 let deco = spans.get(span_no).copied().unwrap_or_default();
3130 if deco.any() {
3131 let group = &run.glyphs[i..j];
3132 let x0 = group.iter().map(|g| g.x).fold(f32::INFINITY, f32::min);
3133 let x1 = group
3134 .iter()
3135 .map(|g| g.x + g.w)
3136 .fold(f32::NEG_INFINITY, f32::max);
3137 let w = (x1 - x0).max(0.0);
3138 match (deco.bg, last_bg.map(|k| &mut out[k])) {
3139 (Some(bg), Some(prev))
3140 if prev.color == Some(bg)
3141 && prev.radius == deco.bg_radius
3142 && (prev.x + prev.w - x0).abs() < 0.01 =>
3143 {
3144 prev.w = (x1 - prev.x).max(prev.w);
3145 }
3146 (Some(bg), _) => {
3147 last_bg = Some(out.len());
3148 out.push(DecoTemplate {
3149 x: x0,
3150 y: run.line_top,
3151 w,
3152 h: run.line_height,
3153 color: Some(bg),
3154 under: true,
3155 style: UnderlineStyle::Solid,
3156 radius: deco.bg_radius,
3157 });
3158 }
3159 (None, _) => last_bg = None,
3160 }
3161 if deco.underline || deco.strikethrough {
3162 let first = &group[0];
3163 let metrics = fs
3164 .get_font(first.font_id, first.font_weight)
3165 .map(|font| font.as_swash().metrics(&[]).scale(first.font_size));
3166 let (under_off, strike_off, stroke) = match metrics {
3169 Some(m) => (m.underline_offset, m.strikeout_offset, m.stroke_size),
3170 None => (
3171 -0.1 * first.font_size,
3172 0.3 * first.font_size,
3173 0.06 * first.font_size,
3174 ),
3175 };
3176 let stroke = stroke.max(1.0).round();
3177 let baseline = run.line_y.round();
3178 if deco.underline {
3179 out.push(DecoTemplate {
3180 x: x0,
3181 y: (baseline - under_off).round(),
3182 w,
3183 h: stroke,
3184 color: deco.underline_color.or_else(|| {
3185 first
3186 .color_opt
3187 .map(|c| Color::rgba8(c.r(), c.g(), c.b(), c.a()))
3188 }),
3189 under: false,
3190 style: deco.underline_style,
3191 radius: 0.0,
3192 });
3193 }
3194 if deco.strikethrough {
3195 out.push(DecoTemplate {
3196 x: x0,
3197 y: (baseline - strike_off).round(),
3198 w,
3199 h: stroke,
3200 color: first
3201 .color_opt
3202 .map(|c| Color::rgba8(c.r(), c.g(), c.b(), c.a())),
3203 under: false,
3204 style: UnderlineStyle::Solid,
3205 radius: 0.0,
3206 });
3207 }
3208 }
3209 } else {
3210 last_bg = None;
3211 }
3212 i = j;
3213 }
3214}
3215
3216impl TextSystem {
3217 pub(crate) fn place(
3222 &mut self,
3223 key: Key,
3224 ancestry: &Ancestry,
3225 id: TextId,
3226 origin: Vec2,
3227 scope: Option<Key>,
3228 drawn: bool,
3229 ) {
3230 let cache_key = self.frame[id.0 as usize].cache_key;
3231 self.places.push(TextPlace {
3232 key,
3233 ancestors: ancestry.keys,
3234 depth: ancestry.depth.min(PLACE_ANCESTORS) as u8,
3235 none_at: ancestry.none_at.map_or(u8::MAX, |n| n as u8),
3236 cache_key,
3237 origin,
3238 scope,
3239 drawn,
3240 });
3241 }
3242
3243 fn runs_of(&self, key: Key, prev: bool) -> Vec<(&TextPlace, &Entry, usize)> {
3249 let list = if prev {
3250 self.places.prev()
3251 } else {
3252 &self.places
3253 };
3254 let mut base = 0usize;
3255 let mut out = Vec::new();
3256 for place in list.iter().filter(|p| p.drawn && p.answers_to(key)) {
3257 let Some(entry) = self.entries.get(&place.cache_key) else {
3258 continue;
3259 };
3260 out.push((place, entry, base));
3261 base += entry.content().len();
3262 }
3263 out
3264 }
3265
3266 pub(crate) fn content_len(&self, id: TextId) -> usize {
3269 let key = self.frame[id.0 as usize].cache_key;
3270 self.entries.get(&key).map_or(0, |e| e.content().len())
3271 }
3272
3273 pub(crate) fn scope_runs(&self, scope: Key, prev: bool) -> Vec<ScopeRun<'_>> {
3282 let list = if prev {
3283 self.places.prev()
3284 } else {
3285 &self.places
3286 };
3287 let mut base = 0usize;
3288 let mut out = Vec::new();
3289 for place in list.iter().filter(|p| p.scope == Some(scope)) {
3290 let Some(text) = self.entries.get(&place.cache_key) else {
3291 continue;
3292 };
3293 let len = text.content().len();
3294 out.push(ScopeRun { place, text, base });
3295 base += len;
3296 }
3297 out
3298 }
3299
3300 pub(crate) fn scope_hit(&self, scope: Key, point: Vec2, prev: bool) -> Option<(Key, usize)> {
3307 let runs = self.scope_runs(scope, prev);
3308 let px = point.x * self.scale;
3309 let py = point.y * self.scale;
3310 let gap = |r: &Rect| {
3311 let dy = (r.y - py).max(py - (r.y + r.h)).max(0.0);
3312 let dx = (r.x - px).max(px - (r.x + r.w)).max(0.0);
3313 (dy, dx)
3314 };
3315 let run = runs.iter().filter(|r| r.place.drawn).min_by(|a, b| {
3316 let ga = gap(&self.scope_box(a));
3317 let gb = gap(&self.scope_box(b));
3318 ga.partial_cmp(&gb).unwrap_or(std::cmp::Ordering::Equal)
3319 })?;
3320 let byte = self.hit_in_run(run, point)?;
3321 Some((run.place.key, byte))
3322 }
3323
3324 fn scope_box(&self, run: &ScopeRun<'_>) -> Rect {
3326 self.entry_box(run.place, run.text)
3327 }
3328
3329 fn entry_box(&self, place: &TextPlace, entry: &Entry) -> Rect {
3334 match entry {
3335 Entry::Run(e) => self.physical_box(place, e),
3336 Entry::Long(l) => {
3337 let (ox, oy) = self.physical_origin(place);
3338 let w = l.wrap_w.unwrap_or_else(|| l.width());
3339 Rect::new(ox, oy, w, l.line_h * l.rows() as f32)
3340 }
3341 }
3342 }
3343
3344 fn row_tops(&self, place: &TextPlace, entry: &Entry) -> Vec<f32> {
3346 let (_, oy) = self.physical_origin(place);
3347 match entry {
3348 Entry::Run(e) => e.buffer.layout_runs().map(|r| oy + r.line_top).collect(),
3349 Entry::Long(l) => (0..l.rows()).map(|r| oy + r as f32 * l.line_h).collect(),
3350 }
3351 }
3352
3353 fn hit_in_run(&self, run: &ScopeRun<'_>, point: Vec2) -> Option<usize> {
3356 match run.text {
3357 Entry::Long(l) => Some(self.long_hit(run.place, l, point)?.byte),
3358 Entry::Run(e) => {
3359 let (ox, oy) = self.physical_origin(run.place);
3360 let cursor = e
3361 .buffer
3362 .hit(point.x * self.scale - ox, point.y * self.scale - oy)?;
3363 Some(e.byte_of(cursor))
3364 }
3365 }
3366 }
3367
3368 pub(crate) fn word_at(
3375 &self,
3376 scope: Key,
3377 node: Key,
3378 byte: usize,
3379 prev: bool,
3380 ) -> Option<(usize, usize)> {
3381 let run = self
3382 .scope_runs(scope, prev)
3383 .into_iter()
3384 .find(|r| r.place.key == node)?;
3385 let content = run.text.content();
3386 Some(word_range(content, byte))
3387 }
3388
3389 pub(crate) fn scope_offset(
3395 &self,
3396 scope: Key,
3397 node: Key,
3398 byte: usize,
3399 prev: bool,
3400 ) -> Option<usize> {
3401 let run = self
3402 .scope_runs(scope, prev)
3403 .into_iter()
3404 .find(|r| r.place.key == node)?;
3405 Some(run.base + byte.min(run.text.content().len()))
3406 }
3407
3408 pub(crate) fn scope_html(&self, scope: Key, from: usize, to: usize, prev: bool) -> String {
3423 let (from, to) = (from.min(to), from.max(to));
3424 let mut out = String::new();
3425 let mut prev_run: Option<&ScopeRun<'_>> = None;
3426 for run in &self.scope_runs(scope, prev) {
3427 let (start, end) = run.span();
3428 if end <= from || start >= to {
3429 continue;
3430 }
3431 if let Some(p) = prev_run
3432 && (p.place.origin.y - run.place.origin.y).abs() > f32::EPSILON
3433 {
3434 out.push_str("<br>");
3435 }
3436 let content = run.text.content();
3437 let lo = floor_boundary(content, from.saturating_sub(start));
3438 let hi = floor_boundary(content, (to - start).min(content.len()));
3439 match run.text {
3440 Entry::Long(line) => self.long_html(line, lo, hi, &mut out),
3441 Entry::Run(entry) => html_of_run(entry, lo, hi, &mut out),
3442 }
3443 prev_run = Some(run);
3444 }
3445 out
3446 }
3447
3448 fn long_html(&self, line: &LongLine, lo: usize, hi: usize, out: &mut String) {
3454 for c in &line.chunks {
3455 let (a, b) = (lo.max(c.start), hi.min(c.end));
3456 if a >= b {
3457 continue;
3458 }
3459 match c.width.and_then(|_| self.run(c.key)) {
3460 Some(e) => html_of_run(e, a - c.start, b - c.start, out),
3461 None => escape_into(&line.content[a..b], out),
3462 }
3463 }
3464 }
3465
3466 pub(crate) fn scope_selection_anchor(
3476 &self,
3477 scope: Key,
3478 from: usize,
3479 to: usize,
3480 prev: bool,
3481 ) -> Option<Vec2> {
3482 let (from, to) = (from.min(to), from.max(to));
3483 for run in self.scope_runs(scope, prev) {
3484 let (start, end) = run.span();
3485 if !run.place.drawn || end <= from || start >= to {
3486 continue;
3487 }
3488 let content = run.text.content();
3489 let lo = floor_boundary(content, from.saturating_sub(start));
3490 let hi = floor_boundary(content, (to - start).min(content.len()));
3491 let (ox, oy) = self.physical_origin(run.place);
3492 match run.text {
3493 Entry::Run(e) => {
3494 if let Some((x, base)) = Self::run_anchor(e, lo, hi) {
3495 return Some(Vec2::new((ox + x) / self.scale, (oy + base) / self.scale));
3496 }
3497 }
3498 Entry::Long(l) => {
3499 if let Some((x, y)) = self.long_caret_local(l, lo) {
3500 return Some(Vec2::new(
3501 (ox + x) / self.scale,
3502 (oy + y + self.long_baseline(l)) / self.scale,
3503 ));
3504 }
3505 }
3506 }
3507 }
3508 None
3509 }
3510
3511 fn run_anchor(entry: &CachedText, lo: usize, hi: usize) -> Option<(f32, f32)> {
3514 let (a, b) = (entry.cursor_of(lo), entry.cursor_of(hi));
3515 for run in entry.buffer.layout_runs() {
3516 if run.line_i < a.line || run.line_i > b.line {
3517 continue;
3518 }
3519 if let Some((x, _)) = run.highlight(a, b).next() {
3520 return Some((x, run.line_y));
3521 }
3522 }
3523 None
3524 }
3525
3526 pub(crate) fn scope_selection_rect(
3532 &self,
3533 scope: Key,
3534 from: usize,
3535 to: usize,
3536 prev: bool,
3537 ) -> Option<Rect> {
3538 let (from, to) = (from.min(to), from.max(to));
3539 let mut out: Option<Rect> = None;
3540 for run in self.scope_runs(scope, prev) {
3541 let (start, end) = run.span();
3542 if !run.place.drawn || end <= from || start >= to {
3543 continue;
3544 }
3545 let content = run.text.content();
3546 let lo = floor_boundary(content, from.saturating_sub(start));
3547 let hi = floor_boundary(content, (to - start).min(content.len()));
3548 let (ox, oy) = self.physical_origin(run.place);
3554 let rects = match run.text {
3555 Entry::Long(l) => self.long_highlight(l, lo, hi),
3556 Entry::Run(e) => Self::run_highlight(e, lo, hi),
3557 };
3558 for r in rects {
3559 let r = Rect::new(
3560 (ox + r.x) / self.scale,
3561 (oy + r.y) / self.scale,
3562 r.w / self.scale,
3563 r.h / self.scale,
3564 );
3565 out = Some(match out {
3566 None => r,
3567 Some(o) => o.union(&r),
3568 });
3569 }
3570 }
3571 out
3572 }
3573
3574 pub(crate) fn scope_slice(&self, scope: Key, from: usize, to: usize, prev: bool) -> String {
3579 let (from, to) = (from.min(to), from.max(to));
3580 let runs = self.scope_runs(scope, prev);
3581 let mut out = String::new();
3582 let mut reserved = false;
3583 let mut prev_run: Option<&ScopeRun<'_>> = None;
3584 for run in &runs {
3585 let (start, end) = run.span();
3586 if end <= from || start >= to {
3587 continue;
3588 }
3589 if !reserved {
3590 out.reserve(to - from + runs.len());
3591 reserved = true;
3592 }
3593 if let Some(p) = prev_run
3594 && (p.place.origin.y - run.place.origin.y).abs() > f32::EPSILON
3595 {
3596 out.push('\n');
3597 }
3598 let content = run.text.content();
3599 let lo = from.saturating_sub(start).min(content.len());
3600 let hi = (to - start).min(content.len());
3601 out.push_str(&content[floor_boundary(content, lo)..floor_boundary(content, hi)]);
3602 prev_run = Some(run);
3603 }
3604 out
3605 }
3606
3607 fn long_hit(&self, place: &TextPlace, line: &LongLine, point: Vec2) -> Option<TextHit> {
3611 let (ox, oy) = self.physical_origin(place);
3612 let px = point.x * self.scale - ox;
3613 let py = point.y * self.scale - oy;
3614 if line.chunks.is_empty() {
3615 return Some(TextHit { byte: 0, line: 0 });
3616 }
3617 if let Some(w) = line.wrap_w {
3618 return self.long_hit_wrapped(line, w, px, py);
3619 }
3620 if px >= line.width() {
3621 return Some(TextHit {
3622 byte: line.content.len(),
3623 line: 0,
3624 });
3625 }
3626 let i = line.chunk_at(px.max(0.0));
3627 let c = &line.chunks[i];
3628 let local = px - line.prefix[i];
3629 let byte = match self.run(c.key) {
3630 Some(e) if c.width.is_some() => {
3631 let cursor = e.buffer.hit(local, py.clamp(0.0, line.line_h - 0.01))?;
3632 c.start + cursor.index.min(c.end - c.start)
3633 }
3634 _ => {
3635 let est = (local / line.avg.max(f32::EPSILON)).round() as usize;
3636 let mut b = (c.start + est).min(c.end);
3637 while !line.content.is_char_boundary(b) {
3638 b -= 1;
3639 }
3640 b
3641 }
3642 };
3643 Some(TextHit { byte, line: 0 })
3644 }
3645
3646 fn long_hit_wrapped(&self, line: &LongLine, w: f32, px: f32, py: f32) -> Option<TextHit> {
3650 let row = ((py / line.line_h).floor().max(0.0) as u32).min(line.rows() - 1);
3651 let Some((a, b)) = line.chunks_on_rows(row, row) else {
3652 return Some(TextHit {
3653 byte: line.content.len(),
3654 line: row,
3655 });
3656 };
3657 let i = (a..=b)
3660 .find(|&j| {
3661 let (r1, end_x) = line.starts[j + 1];
3662 px < if r1 == row { end_x } else { w }
3663 })
3664 .unwrap_or(b);
3665 let c = &line.chunks[i];
3666 let (row0, head_x) = line.starts[i];
3667 let r = (row - row0) as usize;
3668 let byte = match self.run(c.key) {
3669 Some(e) if r < c.rows.len() => {
3670 let rs = c.rows[r];
3671 let local_x = px - if r == 0 { head_x } else { 0.0 } + rs.x;
3672 let cursor = e.buffer.hit(local_x, line.line_h / 2.0)?;
3673 let lo = rs.byte as usize;
3674 let hi = c
3675 .rows
3676 .get(r + 1)
3677 .map_or(c.end - c.start, |n| n.byte as usize);
3678 c.start + cursor.index.clamp(lo, hi)
3679 }
3680 _ => {
3681 let linear = r as f32 * w + px - head_x;
3684 let est = (linear / line.avg.max(f32::EPSILON)).round() as usize;
3685 let mut b = (c.start + est).min(c.end);
3686 while !line.content.is_char_boundary(b) {
3687 b -= 1;
3688 }
3689 b
3690 }
3691 };
3692 let next_row = self
3697 .long_caret_local(line, byte)
3698 .is_some_and(|(_, y)| y > (row as f32 + 0.5) * line.line_h);
3699 let byte = if next_row && byte > 0 {
3700 floor_boundary(&line.content, byte - 1)
3701 } else {
3702 byte
3703 };
3704 Some(TextHit { byte, line: row })
3705 }
3706
3707 fn long_caret(&self, place: &TextPlace, line: &LongLine, byte: usize) -> Option<Rect> {
3710 let (ox, oy) = self.physical_origin(place);
3711 let scale = self.scale;
3712 let (x, y) = self.long_caret_local(line, byte)?;
3713 Some(Rect::new(
3714 (ox + x) / scale,
3715 (oy + y) / scale,
3716 0.0,
3717 line.line_h / scale,
3718 ))
3719 }
3720
3721 fn long_baseline(&self, line: &LongLine) -> f32 {
3727 line.chunks
3728 .first()
3729 .and_then(|c| self.run(c.key))
3730 .and_then(|e| e.buffer.layout_runs().next())
3731 .map_or(line.line_h * 0.8, |r| r.line_y.round())
3732 }
3733
3734 fn long_caret_local(&self, line: &LongLine, byte: usize) -> Option<(f32, f32)> {
3739 let byte = byte.min(line.content.len());
3740 if let Some(w) = line.wrap_w
3741 && !line.chunks.is_empty()
3742 {
3743 let i = line.chunk_of_byte(byte);
3744 let c = &line.chunks[i];
3745 let local = byte - c.start;
3746 let (row0, head_x) = line.starts[i];
3747 let (r, x) = match self.run(c.key) {
3748 Some(e) if !c.rows.is_empty() => {
3749 let r = c.rows.partition_point(|rs| rs.byte as usize <= local) - 1;
3750 let run = e.buffer.layout_runs().next()?;
3751 let cx = caret_x(&run, local.min(c.end - c.start));
3752 (r, cx - c.rows[r].x + if r == 0 { head_x } else { 0.0 })
3753 }
3754 _ => {
3755 let linear = head_x + local as f32 * line.avg;
3756 let r = (linear / w).floor();
3757 (r as usize, linear - r * w)
3758 }
3759 };
3760 let y = (row0 as usize + r) as f32 * line.line_h;
3761 return Some((x, y));
3762 }
3763 let x = if line.chunks.is_empty() {
3764 0.0
3765 } else {
3766 let i = line.chunk_of_byte(byte);
3767 let c = &line.chunks[i];
3768 let local = byte - c.start;
3769 match self.run(c.key) {
3770 Some(e) if c.width.is_some() => {
3771 let run = e.buffer.layout_runs().next()?;
3772 line.prefix[i] + caret_x(&run, local.min(c.end - c.start))
3773 }
3774 _ => line.prefix[i] + local as f32 * line.avg,
3775 }
3776 };
3777 Some((x, 0.0))
3778 }
3779
3780 fn long_highlight(&self, line: &LongLine, from: usize, to: usize) -> Vec<Rect> {
3786 let Some((x0, y0)) = self.long_caret_local(line, from) else {
3787 return Vec::new();
3788 };
3789 let Some((x1, y1)) = self.long_caret_local(line, to) else {
3790 return Vec::new();
3791 };
3792 let h = line.line_h;
3793 if (y1 - y0).abs() < f32::EPSILON {
3794 return vec![Rect::new(x0, y0, (x1 - x0).max(0.0), h)];
3795 }
3796 let w = line.wrap_w.unwrap_or_else(|| line.width());
3798 let mut out = vec![Rect::new(x0, y0, (w - x0).max(0.0), h)];
3799 let mut y = y0 + h;
3800 while y < y1 - h / 2.0 {
3801 out.push(Rect::new(0.0, y, w, h));
3802 y += h;
3803 }
3804 out.push(Rect::new(0.0, y1, x1.max(0.0), h));
3805 out
3806 }
3807
3808 fn run_highlight(entry: &CachedText, from: usize, to: usize) -> Vec<Rect> {
3814 let (a, b) = (entry.cursor_of(from), entry.cursor_of(to));
3815 let mut out = Vec::new();
3816 for run in entry.buffer.layout_runs() {
3817 if run.line_i < a.line || run.line_i > b.line {
3818 continue;
3819 }
3820 let h = entry.buffer.metrics().line_height;
3821 let mut any = false;
3822 for (x, w) in run.highlight(a, b) {
3823 any = true;
3824 out.push(Rect::new(x, run.line_top, w.max(2.0), h));
3825 }
3826 if !any && run.glyphs.is_empty() && b.line > run.line_i {
3829 out.push(Rect::new(0.0, run.line_top, 2.0, h));
3830 }
3831 }
3832 out
3833 }
3834
3835 fn physical_origin(&self, place: &TextPlace) -> (f32, f32) {
3838 (
3839 crate::geom::snap_px(place.origin.x * self.scale),
3840 crate::geom::snap_px(place.origin.y * self.scale),
3841 )
3842 }
3843
3844 fn physical_box(&self, place: &TextPlace, entry: &CachedText) -> Rect {
3846 let (ox, oy) = self.physical_origin(place);
3847 let (size, _) = measure_buffer(&entry.buffer, entry.max_lines);
3848 Rect::new(ox, oy, size.w, size.h)
3849 }
3850
3851 pub(crate) fn hit_at(&self, key: Key, point: Vec2, prev: bool) -> Option<TextHit> {
3855 let runs = self.runs_of(key, prev);
3856 if runs.is_empty() {
3857 return None;
3858 }
3859 let px = point.x * self.scale;
3860 let py = point.y * self.scale;
3861 let gap = |r: &Rect| {
3864 let dy = (r.y - py).max(py - (r.y + r.h)).max(0.0);
3865 let dx = (r.x - px).max(px - (r.x + r.w)).max(0.0);
3866 (dy, dx)
3867 };
3868 let (place, entry, base) = runs
3869 .iter()
3870 .min_by(|a, b| {
3871 let ga = gap(&self.entry_box(a.0, a.1));
3872 let gb = gap(&self.entry_box(b.0, b.1));
3873 ga.partial_cmp(&gb).unwrap_or(std::cmp::Ordering::Equal)
3874 })
3875 .copied()?;
3876 let (ox, oy) = self.physical_origin(place);
3877 let (byte, hit_top) = match entry {
3878 Entry::Long(line) => {
3879 let hit = self.long_hit(place, line, point)?;
3880 (hit.byte, oy + hit.line as f32 * line.line_h)
3881 }
3882 Entry::Run(entry) => {
3883 let bx = self.physical_box(place, entry);
3890 let py = py.clamp(bx.y, (bx.y + bx.h - 0.01).max(bx.y));
3891 let cursor = entry.buffer.hit(px - ox, py - oy)?;
3892 let row =
3893 visual_line(&entry.buffer, cursor.line, cursor.index).map_or(0, |(l, _)| l);
3894 let top = entry
3895 .buffer
3896 .layout_runs()
3897 .nth(row)
3898 .map_or(0.0, |r| r.line_top);
3899 (entry.byte_of(cursor), oy + top)
3900 }
3901 };
3902 let mut tops: Vec<f32> = runs
3907 .iter()
3908 .flat_map(|(p, e, _)| self.row_tops(p, e))
3909 .collect();
3910 tops.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
3911 tops.dedup_by(|a, b| (*a - *b).abs() < 0.5);
3912 let line = tops.iter().filter(|t| **t < hit_top - 0.5).count();
3913 Some(TextHit {
3914 byte: base + byte,
3915 line: line as u32,
3916 })
3917 }
3918
3919 pub(crate) fn caret_at(&self, key: Key, byte: usize, prev: bool) -> Option<Rect> {
3923 let runs = self.runs_of(key, prev);
3924 let total = runs.last().map(|(_, e, base)| base + e.content().len())?;
3925 let byte = byte.min(total);
3926 let (place, entry, base) = runs
3927 .iter()
3928 .find(|(_, e, base)| byte < base + e.content().len())
3929 .or_else(|| runs.last())
3930 .copied()?;
3931 let byte = (byte - base).min(entry.content().len());
3932 let entry = match entry {
3933 Entry::Long(line) => return self.long_caret(place, line, byte),
3934 Entry::Run(entry) => entry,
3935 };
3936 let (ox, oy) = self.physical_origin(place);
3937 let cursor = entry.cursor_of(byte);
3938 let (_, run_no) = visual_line(&entry.buffer, cursor.line, cursor.index)?;
3939 let run = entry.buffer.layout_runs().nth(run_no)?;
3940 let x = caret_x(&run, cursor.index);
3941 let scale = self.scale;
3942 Some(Rect::new(
3943 (ox + x) / scale,
3944 (oy + run.line_top) / scale,
3945 0.0,
3946 run.line_height / scale,
3947 ))
3948 }
3949}
3950
3951fn word_range(content: &str, byte: usize) -> (usize, usize) {
3961 if content.is_empty() {
3962 return (0, 0);
3963 }
3964 #[derive(PartialEq)]
3965 enum Class {
3966 Word,
3967 Space,
3968 Other,
3969 }
3970 let class = |c: char| {
3971 if c.is_alphanumeric() || c == '_' {
3972 Class::Word
3973 } else if c.is_whitespace() {
3974 Class::Space
3975 } else {
3976 Class::Other
3977 }
3978 };
3979 let at = floor_boundary(content, byte.min(content.len()));
3982 let at = if at >= content.len() {
3983 content.char_indices().next_back().map_or(0, |(i, _)| i)
3984 } else {
3985 at
3986 };
3987 let Some(here) = content[at..].chars().next().map(class) else {
3988 return (at, at);
3989 };
3990 let mut start = at;
3991 for (i, c) in content[..at].char_indices().rev() {
3992 if class(c) != here {
3993 break;
3994 }
3995 start = i;
3996 }
3997 let mut end = at;
3998 for (i, c) in content[at..].char_indices() {
3999 if class(c) != here {
4000 break;
4001 }
4002 end = at + i + c.len_utf8();
4003 }
4004 (start, end)
4005}
4006
4007fn html_of_run(entry: &CachedText, lo: usize, hi: usize, out: &mut String) {
4012 let starts = line_starts(&entry.buffer, &entry.content);
4013 for (li, line) in entry.buffer.lines.iter().enumerate() {
4014 let base = starts.get(li).copied().unwrap_or(0);
4015 let text = line.text();
4016 if li > 0 {
4017 if base > lo && base <= hi {
4020 out.push_str("<br>");
4021 }
4022 }
4023 let attrs_list = line.attrs_list();
4029 let mut spans: Vec<(usize, usize, cosmic_text::AttrsOwned)> = Vec::new();
4030 for (i, _) in text.char_indices() {
4031 let a = cosmic_text::AttrsOwned::new(&attrs_list.get_span(i));
4032 match spans.last_mut() {
4033 Some((_, end, prev)) if *prev == a && *end == i => {
4034 *end = i + text[i..].chars().next().map_or(1, char::len_utf8);
4035 }
4036 _ => spans.push((i, i + text[i..].chars().next().map_or(1, char::len_utf8), a)),
4037 }
4038 }
4039 for (start, end, attrs) in &spans {
4040 let (s, e) = (base + start, base + end);
4041 let (s, e) = (s.max(lo), e.min(hi));
4042 if s >= e {
4043 continue;
4044 }
4045 let piece = &entry.content[s..e];
4046 let bold = attrs.weight > attrs_list.defaults().weight
4051 || attrs
4052 .cache_key_flags
4053 .contains(crate::weights::SYNTHETIC_BOLD);
4054 let italic = attrs.style != cosmic_text::Style::Normal;
4055 if let Some(c) = attrs.color_opt {
4056 let _ = std::fmt::Write::write_fmt(
4057 out,
4058 format_args!(
4059 "<span style=\"color:#{:02x}{:02x}{:02x}\">",
4060 c.r(),
4061 c.g(),
4062 c.b()
4063 ),
4064 );
4065 }
4066 if bold {
4067 out.push_str("<b>");
4068 }
4069 if italic {
4070 out.push_str("<i>");
4071 }
4072 escape_into(piece, out);
4073 if italic {
4074 out.push_str("</i>");
4075 }
4076 if bold {
4077 out.push_str("</b>");
4078 }
4079 if attrs.color_opt.is_some() {
4080 out.push_str("</span>");
4081 }
4082 }
4083 }
4084}
4085
4086fn escape_into(s: &str, out: &mut String) {
4090 for ch in s.chars() {
4091 match ch {
4092 '&' => out.push_str("&"),
4093 '<' => out.push_str("<"),
4094 '>' => out.push_str(">"),
4095 _ => out.push(ch),
4096 }
4097 }
4098}
4099
4100fn floor_boundary(s: &str, i: usize) -> usize {
4106 let mut i = i.min(s.len());
4107 while i > 0 && !s.is_char_boundary(i) {
4108 i -= 1;
4109 }
4110 i
4111}
4112
4113fn line_starts(buffer: &Buffer, content: &str) -> Vec<usize> {
4114 paragraph_starts(buffer, content).collect()
4115}
4116
4117fn paragraph_starts<'a>(buffer: &'a Buffer, content: &'a str) -> impl Iterator<Item = usize> + 'a {
4123 let mut at = 0usize;
4124 buffer.lines.iter().map(move |line| {
4125 let start = at.min(content.len());
4126 at += line.text().len();
4127 let rest = &content[at.min(content.len())..];
4128 for ending in ["\r\n", "\n\r", "\n", "\r"] {
4129 if rest.starts_with(ending) {
4130 at += ending.len();
4131 break;
4132 }
4133 }
4134 start
4135 })
4136}
4137
4138fn visual_line(buffer: &Buffer, line_i: usize, index: usize) -> Option<(usize, usize)> {
4148 let mut last_of_line = None;
4149 let mut before = None;
4150 for (n, run) in buffer.layout_runs().enumerate() {
4151 if run.line_i != line_i {
4152 if last_of_line.is_some() {
4153 break;
4154 }
4155 continue;
4156 }
4157 last_of_line = Some(n);
4158 if run.glyphs.iter().any(|g| g.start <= index && index < g.end) {
4159 return Some((n, n));
4160 }
4161 if run
4162 .glyphs
4163 .iter()
4164 .map(|g| g.start)
4165 .min()
4166 .is_some_and(|s| s <= index)
4167 {
4168 before = Some(n);
4169 }
4170 }
4171 before.or(last_of_line).map(|n| (n, n))
4172}
4173
4174fn caret_x(run: &cosmic_text::LayoutRun<'_>, index: usize) -> f32 {
4178 if let Some(g) = run
4179 .glyphs
4180 .iter()
4181 .find(|g| g.start <= index && index < g.end)
4182 {
4183 return if g.level.is_rtl() { g.x + g.w } else { g.x };
4184 }
4185 match run.glyphs.last() {
4186 Some(g) if !g.level.is_rtl() => g.x + g.w,
4187 Some(g) => g.x,
4188 None => 0.0,
4189 }
4190}
4191
4192impl Default for TextSystem {
4193 fn default() -> Self {
4194 Self::new()
4195 }
4196}
4197
4198fn wrap_target(entry: &CachedText, max_w_logical: Option<f32>, scale: f32) -> Option<f32> {
4201 let max_w = max_w_logical?;
4202 let intrinsic_fits = entry.intrinsic.w <= max_w * scale + 0.5;
4203 (!intrinsic_fits).then_some(max_w * scale)
4204}
4205
4206pub(crate) fn wrap_differs(current: Option<f32>, target: Option<f32>) -> bool {
4214 match (current, target) {
4215 (None, None) => false,
4216 (Some(a), Some(b)) => (a - b).abs() > 0.5,
4217 _ => true,
4218 }
4219}
4220
4221fn wrap_entry(entry: &mut CachedText, fs: &mut FontSystem, target: Option<f32>) {
4222 if wrap_differs(entry.wrap, target) {
4223 entry.buffer.set_size(target, None);
4224 entry.buffer.shape_until_scroll(fs, false);
4225 entry.wrap = target;
4226 }
4227}
4228
4229impl CachedText {
4230 fn byte_of(&self, cursor: cosmic_text::Cursor) -> usize {
4233 let start = paragraph_starts(&self.buffer, &self.content)
4234 .nth(cursor.line)
4235 .unwrap_or(0);
4236 (start + cursor.index).min(self.content.len())
4237 }
4238
4239 fn cursor_of(&self, byte: usize) -> cosmic_text::Cursor {
4245 let mut li = 0;
4246 let mut start = 0;
4247 for (i, s) in paragraph_starts(&self.buffer, &self.content).enumerate() {
4248 if s <= byte {
4249 (li, start) = (i, s);
4250 } else {
4251 break;
4252 }
4253 }
4254 let len = self.buffer.lines.get(li).map_or(0, |l| l.text().len());
4255 cosmic_text::Cursor::new(li, (byte - start).min(len))
4256 }
4257
4258 fn new(
4259 mut buffer: Buffer,
4260 content: String,
4261 style: &TextStyle,
4262 span_deco: Vec<SpanDeco>,
4263 fs: &mut FontSystem,
4264 frame_no: u64,
4265 ) -> Self {
4266 buffer.shape_until_scroll(fs, false);
4267 let max_lines = line_budget(style);
4268 let (intrinsic, _) = measure_buffer(&buffer, max_lines);
4269 let glyphs: usize = buffer.layout_runs().map(|r| r.glyphs.len()).sum();
4270 Self {
4271 buffer,
4272 bytes: ENTRY_BASE_BYTES + content.len() + ENTRY_GLYPH_BYTES * glyphs,
4273 content,
4274 wrap: None,
4275 intrinsic,
4276 max_lines,
4277 clamp_w: style.wrap == TextWrap::None || style.ellipsis,
4278 last_used: frame_no,
4279 glyphs: Vec::new(),
4280 deco: Vec::new(),
4281 span_deco,
4282 glyphs_built_for: None,
4283 claimed: u64::MAX,
4284 claimed_wrap: None,
4285 breaks_anywhere: style.wrap == TextWrap::Glyph,
4286 min_content: None,
4287 }
4288 }
4289
4290 fn fork(&self, frame_no: u64) -> Self {
4294 Self {
4295 buffer: self.buffer.clone(),
4296 content: self.content.clone(),
4297 wrap: self.wrap,
4298 intrinsic: self.intrinsic,
4299 max_lines: self.max_lines,
4300 clamp_w: self.clamp_w,
4301 last_used: frame_no,
4302 bytes: self.bytes,
4303 glyphs: Vec::new(),
4304 deco: Vec::new(),
4305 span_deco: self.span_deco.clone(),
4306 glyphs_built_for: None,
4307 claimed: u64::MAX,
4308 claimed_wrap: None,
4309 breaks_anywhere: self.breaks_anywhere,
4310 min_content: self.min_content,
4311 }
4312 }
4313
4314 fn min_content(&mut self) -> f32 {
4325 if let Some(w) = self.min_content {
4326 return w;
4327 }
4328 let w = if self.clamp_w {
4329 self.intrinsic.w
4330 } else {
4331 widest_unbreakable(&self.buffer, self.breaks_anywhere)
4332 };
4333 self.min_content = Some(w);
4334 w
4335 }
4336}
4337
4338fn widest_unbreakable(buffer: &Buffer, anywhere: bool) -> f32 {
4342 let mut widest = 0.0f32;
4343 let mut line = usize::MAX;
4344 let mut breaks: Vec<usize> = Vec::new();
4345 let (mut run_w, mut ink) = (0.0f32, 0.0f32);
4346 for run in buffer.layout_runs() {
4347 if run.line_i != line {
4348 widest = widest.max(ink);
4349 (run_w, ink) = (0.0, 0.0);
4350 line = run.line_i;
4351 breaks.clear();
4352 if !anywhere {
4353 breaks.extend(unicode_linebreak::linebreaks(run.text).map(|(i, _)| i));
4354 }
4355 }
4356 for g in run.glyphs {
4357 if anywhere || breaks.binary_search(&g.start).is_ok() {
4358 widest = widest.max(ink);
4359 (run_w, ink) = (0.0, 0.0);
4360 }
4361 run_w += g.w;
4362 let blank = run
4363 .text
4364 .get(g.start..g.end)
4365 .is_some_and(|t| t.chars().all(char::is_whitespace));
4366 if !blank {
4367 ink = run_w;
4368 }
4369 }
4370 }
4371 widest.max(ink)
4372}
4373
4374fn new_buffer(fs: &mut FontSystem, style: &TextStyle, scale: f32) -> Buffer {
4377 let metrics = Metrics::new(style.size * scale, style.line_height * scale);
4378 let mut buffer = Buffer::new(fs, metrics);
4379 buffer.set_wrap(match style.wrap {
4380 TextWrap::Word | TextWrap::BreakSpaces => Wrap::WordOrGlyph,
4381 TextWrap::Glyph => Wrap::Glyph,
4382 TextWrap::None => Wrap::None,
4383 });
4384 if style.ellipsis {
4385 let lines = line_budget(style).max(1);
4386 buffer.set_ellipsize(Ellipsize::End(EllipsizeHeightLimit::Lines(lines)));
4387 }
4388 buffer.set_size(None, None);
4389 buffer
4390}
4391
4392fn line_budget(style: &TextStyle) -> usize {
4395 if style.max_lines > 0 {
4396 style.max_lines as usize
4397 } else if style.ellipsis {
4398 1
4399 } else {
4400 0
4401 }
4402}
4403
4404fn line_cap(max_lines: usize) -> usize {
4405 if max_lines == 0 {
4406 usize::MAX
4407 } else {
4408 max_lines
4409 }
4410}
4411
4412pub(crate) fn measure_buffer(buffer: &Buffer, max_lines: usize) -> (Size, u32) {
4418 let mut w = 0.0f32;
4419 let mut lines = 0u32;
4420 for run in buffer.layout_runs().take(line_cap(max_lines)) {
4421 w = w.max(run.line_w);
4422 lines += 1;
4423 }
4424 (
4425 Size::new(w, lines as f32 * buffer.metrics().line_height),
4426 lines,
4427 )
4428}
4429
4430impl TextSystem {
4431 pub(crate) fn intrinsic(&mut self, id: TextId) -> Size {
4432 let scale = self.scale;
4433 if let Some(line) = self.long_of(id) {
4434 return Size::new(line.width() / scale, line.line_h / scale);
4435 }
4436 let e = self.entry_mut(id);
4437 Size::new(e.intrinsic.w / scale, e.intrinsic.h / scale)
4438 }
4439
4440 pub(crate) fn min_content(&mut self, id: TextId) -> f32 {
4445 let scale = self.scale;
4446 if self.long_of(id).is_some() {
4447 return 0.0;
4448 }
4449 self.entry_mut(id).min_content() / scale
4450 }
4451
4452 fn long_of(&self, id: TextId) -> Option<&LongLine> {
4454 self.long(self.frame[id.0 as usize].cache_key)
4455 }
4456
4457 pub(crate) fn wrapped(&mut self, id: TextId, max_w: f32, fs: &mut FontSystem) -> Size {
4458 let scale = self.scale;
4459 if self.long_of(id).is_some() {
4460 let key = self.frame[id.0 as usize].cache_key;
4463 let (size, rows) = self.long_size(key, Some(max_w * scale));
4464 self.long_mut(key).expect("a long line").laid_rows = rows;
4465 return Size::new(size.w / scale, size.h / scale);
4466 }
4467 self.ensure_wrap(id, max_w, fs);
4468 let e = self.entry_mut(id);
4469 let (mut m, _) = measure_buffer(&e.buffer, e.max_lines);
4470 if e.clamp_w {
4471 m.w = m.w.min(max_w * scale);
4474 }
4475 Size::new(m.w / scale, m.h / scale)
4476 }
4477}
4478
4479impl TextSystem {
4480 pub(crate) fn baseline(&mut self, id: TextId) -> f32 {
4485 let scale = self.scale;
4486 if let Some(line) = self.long_of(id) {
4487 return self.long_baseline(line) / scale;
4488 }
4489 let e = self.entry_mut(id);
4490 let b = e
4491 .buffer
4492 .layout_runs()
4493 .next()
4494 .map_or(e.buffer.metrics().line_height * 0.8, |r| r.line_y.round());
4495 b / scale
4496 }
4497}
4498
4499#[cfg(test)]
4502mod default_families {
4503 use super::*;
4504 use cosmic_text::Family;
4505 use cosmic_text::fontdb::FaceInfo;
4506
4507 fn resolved(fs: &mut FontSystem, family: Family<'_>) -> Option<FaceInfo> {
4510 let mut buffer = Buffer::new(fs, Metrics::new(14.0, 18.0));
4511 buffer.set_text("M", &Attrs::new().family(family), Shaping::Advanced, None);
4512 buffer.shape_until_scroll(fs, false);
4513 let id = buffer.layout_runs().next()?.glyphs.first()?.font_id;
4514 fs.db().face(id).cloned()
4515 }
4516
4517 #[test]
4518 fn mono_is_an_upright_monospaced_face() {
4519 let mut fs = new_font_system().0;
4520 if !fs.db().faces().any(|f| f.monospaced) {
4521 eprintln!("skipped: no monospaced face installed");
4522 return;
4523 }
4524 let face = resolved(&mut fs, Family::Monospace).expect("M shapes in Mono");
4525 let mono = default_families(&fs)[2].to_string();
4526 assert_eq!(
4527 face.style,
4528 cosmic_text::Style::Normal,
4529 "Mono ({mono}) resolved to {:?}",
4530 face.post_script_name
4531 );
4532 assert!(
4533 face.monospaced,
4534 "Mono ({mono}) resolved to {:?}, which is not monospaced",
4535 face.post_script_name
4536 );
4537 }
4538
4539 #[test]
4540 fn sans_and_serif_are_upright_and_not_monospaced() {
4541 let mut fs = new_font_system().0;
4542 if fs.db().faces().next().is_none() {
4543 eprintln!("skipped: no face installed");
4544 return;
4545 }
4546 let [sans, serif, _] = default_families(&fs).map(str::to_string);
4547 for (family, name) in [(Family::SansSerif, sans), (Family::Serif, serif)] {
4548 let face = resolved(&mut fs, family).expect("M shapes");
4549 assert_eq!(
4550 face.style,
4551 cosmic_text::Style::Normal,
4552 "{name} resolved to {:?}",
4553 face.post_script_name
4554 );
4555 assert!(
4556 !face.monospaced,
4557 "{name} resolved to {:?}, which is monospaced",
4558 face.post_script_name
4559 );
4560 }
4561 }
4562
4563 #[test]
4566 fn pinned_names_are_installed_or_cosmic_texts_own() {
4567 let fs = new_font_system().0;
4568 let db = fs.db();
4569 for (name, list) in default_families(&fs).into_iter().zip(DEFAULT_FAMILIES) {
4570 let installed = db
4571 .faces()
4572 .any(|f| f.families.iter().any(|(fam, _)| fam == name));
4573 let on_list = list.contains(&name);
4574 assert!(
4575 installed == on_list,
4576 "{name}: installed {installed}, on the platform list {on_list}"
4577 );
4578 }
4579 }
4580}
4581
4582#[cfg(test)]
4589mod unmeasurable_faces {
4590 use super::*;
4591 use crate::testing::{font_face, han_face, unmeasurable_face};
4592 use cosmic_text::Family;
4593 use cosmic_text::fontdb::{Database, Source};
4594
4595 fn font_system() -> FontSystem {
4600 let mut db = Database::new();
4601 for bytes in [
4602 font_face("Kui Mono", 400, false, true),
4603 unmeasurable_face("Kui Bitmap"),
4604 han_face("Kui Han"),
4605 ] {
4606 db.load_font_source(Source::Binary(std::sync::Arc::new(bytes)));
4607 }
4608 let mut fs = font_system_with("en-US".into(), db);
4609 fs.db_mut().set_monospace_family("Kui Mono");
4610 fs
4611 }
4612
4613 fn family(fs: &FontSystem, id: cosmic_text::fontdb::ID) -> String {
4614 fs.db()
4615 .face(id)
4616 .map_or_else(String::new, |f| f.families[0].0.clone())
4617 }
4618
4619 #[test]
4620 fn a_face_without_metrics_is_not_in_the_database() {
4621 let fs = font_system();
4622 let families: Vec<String> = fs.db().faces().map(|f| family(&fs, f.id)).collect();
4623 assert_eq!(families, ["Kui Mono", "Kui Han"]);
4624 }
4625
4626 #[test]
4630 fn han_in_mono_falls_back_to_a_face_that_measures() {
4631 let mut fs = font_system();
4632 let mut buffer = Buffer::new(&mut fs, Metrics::new(14.0, 21.0));
4633 let attrs = Attrs::new().family(Family::Monospace);
4634 buffer.set_text("字 a", &attrs, Shaping::Advanced, None);
4635 buffer.shape_until_scroll(&mut fs, false);
4636 let run = buffer.layout_runs().next().expect("one line");
4637 let glyphs: Vec<(&str, f32, f32, String)> = run
4638 .glyphs
4639 .iter()
4640 .map(|g| (&run.text[g.start..g.end], g.x, g.w, family(&fs, g.font_id)))
4641 .collect();
4642 for &(text, x, w, _) in &glyphs {
4643 assert!(x.is_finite() && w.is_finite(), "{text:?} at {x}, {w} wide");
4644 }
4645 let faces: Vec<(&str, &str)> = glyphs.iter().map(|g| (g.0, g.3.as_str())).collect();
4646 assert_eq!(
4647 faces,
4648 [("字", "Kui Han"), (" ", "Kui Mono"), ("a", "Kui Mono")]
4649 );
4650 let xs: Vec<f32> = glyphs.iter().map(|g| g.1).collect();
4652 assert_eq!(xs, [0.0, 7.0, 14.0]);
4653 for glyph in run.glyphs {
4654 glyph.physical((0.0, 0.0), 1.0);
4655 }
4656 }
4657}