1use std::borrow::Cow;
15use std::cell::{Cell, RefCell, RefMut};
16use std::collections::{HashMap, HashSet};
17use std::ffi::CString;
18use std::path::PathBuf;
19use std::rc::Rc;
20use std::sync::Arc;
21
22use cosmic_text::fontdb::{self, Database, FaceInfo, ID, Query, Source};
23use cosmic_text::{
24 Align, Attrs, Buffer, Ellipsize, EllipsizeHeightLimit, Family, FeatureTag, FontFeatures,
25 FontSystem, LayoutGlyph, LayoutRun, Metrics, Shaping, Weight, Wrap,
26};
27use fontconfig::{CharSet, FC_FAMILY, FC_SLANT, FC_SLANT_ITALIC, FC_WEIGHT, Fontconfig, Pattern};
28use taffy::AvailableSpace;
29
30use crate::geometry::{Point, Rect};
31use crate::input::LinkHandler;
32use crate::rich::Span;
33use crate::style::{Color, Font, Style, TextAlign};
34use crate::widgets::Elide;
35
36#[derive(Clone, Default)]
48pub struct TextSystem(Rc<RefCell<Fonts>>);
49
50impl TextSystem {
51 pub fn new() -> TextSystem {
53 TextSystem::default()
54 }
55
56 pub fn font_system(&self) -> RefMut<'_, FontSystem> {
59 RefMut::map(self.fonts(), |fonts| &mut fonts.fonts)
60 }
61
62 pub(crate) fn fonts(&self) -> RefMut<'_, Fonts> {
64 self
65 .0
66 .try_borrow_mut()
67 .expect("nothing that holds the fonts runs user code, which may measure text")
68 }
69}
70
71thread_local! {
72 static FONTS_ADDED: Cell<u64> = const { Cell::new(0) };
75}
76
77pub(crate) fn fonts_added() -> u64 {
78 FONTS_ADDED.get()
79}
80
81#[derive(Clone, Copy, Debug, Default, PartialEq)]
84pub struct TextMetrics {
85 pub width: f32,
87 pub height: f32,
89 pub ascent: f32,
91 pub descent: f32,
93 pub line_height: f32,
95}
96
97pub(crate) struct Fonts {
99 fonts: FontSystem,
100 fontconfig: Lookup,
101 families: HashMap<(&'static str, u16, bool), Option<Rc<str>>>,
104 pub(crate) loaded: HashMap<(PathBuf, u32), Option<Rc<str>>>,
106 files: HashSet<PathBuf>,
108 fallback_tried: HashSet<(char, &'static str, u16, bool)>,
111 bundled: HashMap<ID, (u16, u16)>,
114}
115
116enum Lookup {
118 NotStarted,
119 Ready(Fontconfig),
120 Failed,
121}
122
123impl Fonts {
124 pub(crate) fn new() -> Fonts {
126 let fonts = FontSystem::new_with_locale_and_db("en-US".to_owned(), Database::new());
129 Fonts {
130 fonts,
131 fontconfig: Lookup::NotStarted,
132 families: HashMap::new(),
133 loaded: HashMap::new(),
134 files: HashSet::new(),
135 fallback_tried: HashSet::new(),
136 bundled: HashMap::new(),
137 }
138 }
139
140 pub(crate) fn font_system(&mut self) -> &mut FontSystem {
142 &mut self.fonts
143 }
144
145 #[cfg(test)]
147 pub(crate) fn fontconfig_started(&self) -> bool {
148 !matches!(self.fontconfig, Lookup::NotStarted)
149 }
150
151 fn fontconfig(&mut self) -> Option<&Fontconfig> {
152 if let Lookup::NotStarted = self.fontconfig {
153 self.fontconfig = match Fontconfig::new() {
154 Some(fontconfig) => Lookup::Ready(fontconfig),
155 None => {
156 tracing::error!("fontconfig failed to start, so no fonts can be loaded");
157 Lookup::Failed
158 }
159 };
160 }
161 match &self.fontconfig {
162 Lookup::Ready(fontconfig) => Some(fontconfig),
163 _ => None,
164 }
165 }
166
167 pub(crate) fn family(&mut self, font: &Font) -> Option<Rc<str>> {
172 let key = (font.family, font.weight, font.italic);
173 if let Some(name) = self.families.get(&key) {
174 return name.clone();
175 }
176 if let Some(name) = self.bundled(font) {
177 self.families.insert(key, Some(Rc::clone(&name)));
178 return Some(name);
179 }
180 let matched = self
181 .fontconfig()
182 .and_then(|fontconfig| match_font(fontconfig, font, None));
183 let name = matched.and_then(|file| self.load(file));
184 match &name {
185 Some(name) => tracing::debug!(requested = font.family, family = %name, "font loaded"),
186 None => tracing::warn!(
187 requested = font.family,
188 "no font found for this family, so its text shows nothing"
189 ),
190 }
191 self.families.insert(key, name.clone());
192 name
193 }
194
195 fn bundled(&self, font: &Font) -> Option<Rc<str>> {
199 let db = self.fonts.db();
200 self
201 .bundled
202 .iter()
203 .filter(|(_, (low, high))| (*low..=*high).contains(&font.weight))
204 .filter_map(|(&id, _)| db.face(id))
205 .filter(|face| (face.style != fontdb::Style::Normal) == font.italic)
206 .flat_map(|face| &face.families)
207 .find(|(name, _language)| name.eq_ignore_ascii_case(font.family))
208 .map(|(name, _language)| Rc::from(name.as_str()))
209 }
210
211 pub(crate) fn add(&mut self, bytes: &'static [u8]) {
215 let source = Source::Binary(Arc::new(bytes));
217 let mut probe = Database::new();
219 probe.load_font_source(source.clone());
220 let faces: Vec<_> = probe
221 .faces()
222 .map(|face| (face, weights(&probe, face)))
223 .collect();
224 if faces.is_empty() {
225 tracing::warn!(
226 bytes = bytes.len(),
227 "a bundled font has no face that could be read, so it is ignored"
228 );
229 return;
230 }
231 let names: Vec<&str> = faces
232 .iter()
233 .flat_map(|(face, _)| face.families.iter().map(|(name, _)| name.as_str()))
234 .collect();
235 tracing::debug!(?names, "font added");
236 let same_family = |a: &FaceInfo, b: &FaceInfo| {
237 a.families.iter().any(|(name, _)| {
238 b.families
239 .iter()
240 .any(|(other, _)| name.eq_ignore_ascii_case(other))
241 })
242 };
243 let replaced: Vec<_> = self
247 .fonts
248 .db()
249 .faces()
250 .filter(|old| {
251 faces.iter().any(|(new, (low, high))| {
252 new.style == old.style && (*low..=*high).contains(&old.weight.0) && same_family(new, old)
253 })
254 })
255 .filter_map(|old| {
256 let family = old
257 .families
258 .first()
259 .map(|(name, _)| Rc::from(name.as_str()));
260 Some((
261 old.id,
262 (source_path(&old.source)?.clone(), old.index),
263 family,
264 ))
265 })
266 .collect();
267 let db = self.fonts.db_mut();
268 for (id, face, family) in replaced {
269 db.remove_face(id);
270 self.loaded.entry(face).or_insert(family);
273 }
274 let ids = db.load_font_source(source);
276 for (id, (_, weights)) in ids.into_iter().zip(&faces) {
277 self.bundled.insert(id, *weights);
278 }
279 self
280 .families
281 .retain(|(family, _, _), _| !names.iter().any(|name| name.eq_ignore_ascii_case(family)));
282 self.fallback_tried.clear();
284 FONTS_ADDED.set(FONTS_ADDED.get() + 1);
285 }
286
287 pub(crate) fn measure(&mut self, content: &str, font: Font) -> TextMetrics {
289 let mut node = TextNode::new();
290 node.set_content(content.to_owned());
291 node.set_max_lines(u32::MAX);
292 node.prepare(font, self);
293 let Metrics {
294 font_size,
295 line_height,
296 } = node.buffer.metrics();
297 let weight = Weight(font.weight);
298 let face = self.family(&font).and_then(|name| {
299 self.fonts.db().query(&Query {
300 families: &[Family::Name(&name)],
301 weight,
302 style: if font.italic {
303 fontdb::Style::Italic
304 } else {
305 fontdb::Style::Normal
306 },
307 ..Query::default()
308 })
309 });
310 let (ascent, descent) =
311 face
312 .and_then(|id| self.fonts.get_font(id, weight))
313 .map_or((0.0, 0.0), |face| {
314 let metrics = face.metrics();
315 let scale = font_size / f32::from(metrics.units_per_em);
316 (metrics.ascent * scale, -metrics.descent * scale)
317 });
318 TextMetrics {
319 width: node.width(),
320 height: node.height(),
321 ascent,
322 descent,
323 line_height,
324 }
325 }
326
327 fn load_fallbacks(&mut self, font: &Font, missing: &[char]) -> bool {
331 let faces = self.fonts.db().len();
332 for &ch in missing {
333 if !self
334 .fallback_tried
335 .insert((ch, font.family, font.weight, font.italic))
336 {
337 continue;
338 }
339 let Some(file) = self
340 .fontconfig()
341 .and_then(|fontconfig| match_font(fontconfig, font, Some(ch)))
342 else {
343 continue;
344 };
345 self.load(file);
346 }
347 self.fonts.db().len() > faces
348 }
349
350 pub(crate) fn load(&mut self, (path, index): (PathBuf, u32)) -> Option<Rc<str>> {
353 let key = (path, index);
354 if let Some(name) = self.loaded.get(&key) {
355 return name.clone();
356 }
357 let (path, index) = &key;
358 if !self.files.contains(path) {
359 self.files.insert(path.clone());
360 if let Err(error) = self.fonts.db_mut().load_font_file(path) {
361 tracing::warn!(path = %path.display(), %error, "couldn't read a font file");
362 }
363 }
364 let name = self
365 .fonts
366 .db()
367 .faces()
368 .find(|face| face.index == *index && source_path(&face.source) == Some(path))
369 .and_then(|face| face.families.first())
370 .map(|(name, _language)| Rc::from(name.as_str()));
371 self.loaded.insert(key, name.clone());
372 name
373 }
374}
375
376impl Default for Fonts {
377 fn default() -> Self {
378 Self::new()
379 }
380}
381
382fn weights(db: &Database, face: &FaceInfo) -> (u16, u16) {
385 let wght = u32::from_be_bytes(*b"wght");
386 let axis = cosmic_text::Font::new(db, face.id, face.weight).and_then(|font| {
387 let axis = font
388 .as_swash()
389 .variations()
390 .find(|axis| axis.tag() == wght)?;
391 Some((axis.min_value() as u16, axis.max_value() as u16))
393 });
394 axis.unwrap_or((face.weight.0, face.weight.0))
395}
396
397fn source_path(source: &Source) -> Option<&PathBuf> {
398 match source {
399 Source::File(path) | Source::SharedFile(path, _) => Some(path),
400 Source::Binary(_) => None,
401 }
402}
403
404fn match_font(
407 fontconfig: &Fontconfig,
408 font: &Font,
409 covering: Option<char>,
410) -> Option<(PathBuf, u32)> {
411 let mut pattern = Pattern::new(fontconfig).ok()?;
412 pattern
413 .add_string(FC_FAMILY, &CString::new(font.family).ok()?)
414 .ok()?;
415 pattern
416 .add_integer(FC_WEIGHT, fc_weight(font.weight))
417 .ok()?;
418 if font.italic {
419 pattern.add_integer(FC_SLANT, FC_SLANT_ITALIC).ok()?;
420 }
421 if let Some(ch) = covering {
422 let mut chars = CharSet::new(fontconfig).ok()?;
423 chars.add_char(ch).ok()?;
424 pattern.add_charset(chars).ok()?;
425 }
426 let matched = pattern.font_match().ok()?;
427 let path = PathBuf::from(matched.filename().ok()?);
428 let index = matched.face_index().ok().map_or(0, face_number);
429 Some((path, index))
430}
431
432pub(crate) fn face_number(index: i32) -> u32 {
437 u32::try_from(index & 0xFFFF).unwrap_or(0)
439}
440
441pub(crate) fn fc_weight(weight: u16) -> i32 {
445 const POINTS: [(f32, f32); 12] = [
446 (100.0, 0.0),
447 (200.0, 40.0),
448 (300.0, 50.0),
449 (350.0, 55.0),
450 (380.0, 75.0),
451 (400.0, 80.0),
452 (500.0, 100.0),
453 (600.0, 180.0),
454 (700.0, 200.0),
455 (800.0, 205.0),
456 (900.0, 210.0),
457 (1000.0, 215.0),
458 ];
459 let weight = f32::from(weight).clamp(100.0, 1000.0);
460 let upper = POINTS
461 .iter()
462 .position(|&(css, _)| css >= weight)
463 .unwrap_or(POINTS.len() - 1)
464 .max(1);
465 let (css_low, fc_low) = POINTS[upper - 1];
466 let (css_high, fc_high) = POINTS[upper];
467 let fc = fc_low + (weight - css_low) / (css_high - css_low) * (fc_high - fc_low);
468 fc.round() as i32
469}
470
471#[derive(Clone, Copy, Debug, PartialEq)]
474pub(crate) struct TextStyle {
475 pub(crate) font: Font,
476 pub(crate) align: Option<TextAlign>,
477 pub(crate) line_height: Option<f32>,
478}
479
480impl TextStyle {
481 pub(crate) fn inherit(self, style: &Style) -> TextStyle {
483 TextStyle {
484 font: style.font.unwrap_or(self.font),
485 align: style.text_align.or(self.align),
486 line_height: style.line_height.or(self.line_height),
487 }
488 }
489}
490
491impl From<Font> for TextStyle {
492 fn from(font: Font) -> TextStyle {
493 TextStyle {
494 font,
495 align: None,
496 line_height: None,
497 }
498 }
499}
500
501fn span_font(span: &Span, font: Font) -> Font {
503 Font {
504 weight: if span.bold { 700 } else { font.weight },
505 italic: font.italic || span.italic,
506 ..font
507 }
508}
509
510fn attrs<'a>(font: &Font, family: Option<&'a str>) -> Attrs<'a> {
512 let mut attrs = Attrs::new().weight(Weight(font.weight));
513 if let Some(family) = family {
514 attrs = attrs.family(Family::Name(family));
515 }
516 if font.italic {
517 attrs = attrs.style(cosmic_text::Style::Italic);
518 }
519 if font.letter_spacing.is_finite() && font.letter_spacing != 0.0 {
522 attrs = attrs.letter_spacing((font.letter_spacing / font_size(font)).max(-0.5));
523 }
524 if !font.features.is_empty() {
525 let mut features = FontFeatures::new();
526 for feature in font.features {
527 features.set(FeatureTag::new(&feature.tag), feature.value);
528 }
529 attrs = attrs.font_features(features);
530 }
531 attrs
532}
533
534fn metrics(style: &TextStyle) -> Metrics {
538 let size = font_size(&style.font);
539 let multiple = style
540 .line_height
541 .filter(|multiple| multiple.is_finite() && *multiple > 0.0)
542 .unwrap_or(1.2);
543 Metrics::new(size, (size * multiple).round().max(1.0))
544}
545
546fn font_size(font: &Font) -> f32 {
547 if font.size.is_finite() && font.size >= 1.0 {
548 font.size
549 } else {
550 Font::DEFAULT.size
551 }
552}
553
554pub(crate) struct TextNode {
558 pub(crate) content: String,
560 pub(crate) spans: Vec<Span>,
565 span_starts: Vec<usize>,
567 line_starts: Vec<usize>,
569 pub(crate) elide: Elide,
570 pub(crate) max_lines: u32,
572 pub(crate) wrap: bool,
575 pub(crate) buffer: Buffer,
576 style: Option<TextStyle>,
578 fonts_added: u64,
580 stale: bool,
583 pub(crate) origin: Point,
585 pub(crate) selectable: bool,
587 pub(crate) cursor: usize,
590 pub(crate) anchor: Option<usize>,
591 pub(crate) on_link: Option<LinkHandler>,
593 pub(crate) hovered_link: Option<usize>,
596 pub(crate) focused_link: Option<usize>,
597 pub(crate) link_hover_color: Option<Color>,
599}
600
601impl TextNode {
602 pub(crate) fn new() -> TextNode {
603 TextNode {
604 content: String::new(),
605 spans: Vec::new(),
606 span_starts: Vec::new(),
607 line_starts: Vec::new(),
608 elide: Elide::None,
609 max_lines: 1,
610 wrap: true,
611 buffer: {
612 let mut buffer = Buffer::new_empty(metrics(&Font::DEFAULT.into()));
613 buffer.set_tab_width(4);
615 buffer
616 },
617 style: None,
618 fonts_added: 0,
619 stale: true,
620 origin: Point::default(),
621 selectable: false,
622 cursor: 0,
623 anchor: None,
624 on_link: None,
625 hovered_link: None,
626 focused_link: None,
627 link_hover_color: None,
628 }
629 }
630
631 pub(crate) fn set_content(&mut self, content: String) -> bool {
634 self.set(|text| &mut text.content, content)
635 }
636
637 pub(crate) fn set_spans(&mut self, spans: Vec<Span>) -> bool {
640 let content = spans.iter().map(|span| span.text.as_str()).collect();
641 self.span_starts = spans
642 .iter()
643 .scan(0, |start, span| {
644 let this = *start;
645 *start += span.text.len();
646 Some(this)
647 })
648 .collect();
649 let changed = self.set(|text| &mut text.spans, spans);
650 let new_text = self.set_content(content);
651 self.forget_selection_if(new_text) | changed
652 }
653
654 pub(crate) fn forget_selection_if(&mut self, changed: bool) -> bool {
657 if changed {
658 self.anchor = None;
659 self.cursor = 0;
660 }
661 changed
662 }
663
664 pub(crate) fn set_elide(&mut self, elide: Elide) -> bool {
665 self.set(|text| &mut text.elide, elide)
666 }
667
668 pub(crate) fn set_max_lines(&mut self, max_lines: u32) -> bool {
669 self.set(|text| &mut text.max_lines, max_lines.max(1))
670 }
671
672 pub(crate) fn set_wrap(&mut self, wrap: bool) -> bool {
673 self.set(|text| &mut text.wrap, wrap)
674 }
675
676 fn set<T: PartialEq>(&mut self, field: impl FnOnce(&mut TextNode) -> &mut T, value: T) -> bool {
677 let slot = field(self);
678 if *slot == value {
679 return false;
680 }
681 *slot = value;
682 self.stale = true;
683 true
684 }
685
686 fn fits_width(&self) -> bool {
689 self.elide != Elide::None || self.wraps()
690 }
691
692 pub(crate) fn wraps(&self) -> bool {
693 self.max_lines > 1 && self.wrap
694 }
695
696 pub(crate) fn aligned(&self) -> bool {
698 self.style.is_some_and(|style| style.align.is_some())
699 }
700
701 pub(crate) fn prepare(&mut self, style: impl Into<TextStyle>, text: &mut Fonts) -> bool {
706 let style = style.into();
707 if !self.stale && self.style == Some(style) && self.fonts_added == fonts_added() {
708 return false;
709 }
710 let fonts: Vec<Font> = std::iter::once(style.font)
712 .chain(self.spans.iter().map(|span| span_font(span, style.font)))
713 .collect();
714 let families: Vec<_> = fonts.iter().map(|font| text.family(font)).collect();
715 self.buffer.set_metrics(metrics(&style));
716 self.buffer.set_wrap(if self.wraps() {
718 Wrap::WordOrGlyph
719 } else {
720 Wrap::None
721 });
722 let lines = EllipsizeHeightLimit::Lines(self.max_lines as usize);
723 self.buffer.set_ellipsize(match self.elide {
724 Elide::None => Ellipsize::None,
725 Elide::Start => Ellipsize::Start(lines),
726 Elide::Middle => Ellipsize::Middle(lines),
727 Elide::End => Ellipsize::End(lines),
728 });
729 self.buffer.set_size(None, None);
730 self.shape(&fonts, &families, &style, text);
731 let missing = self.fallback_chars(&fonts, &families, text.font_system().db());
732 let mut gained = false;
733 for (font, chars) in missing {
734 gained |= text.load_fallbacks(&font, &chars);
735 }
736 if gained {
737 self.shape(&fonts, &families, &style, text);
738 }
739 self.line_starts = self
740 .buffer
741 .lines
742 .iter()
743 .scan(0, |start, line| {
744 let this = *start;
745 *start += line.text().len() + line.ending().as_str().len();
746 Some(this)
747 })
748 .collect();
749 self.style = Some(style);
750 self.fonts_added = fonts_added();
751 self.stale = false;
752 true
753 }
754
755 fn shape(
758 &mut self,
759 fonts: &[Font],
760 families: &[Option<Rc<str>>],
761 style: &TextStyle,
762 text: &mut Fonts,
763 ) {
764 let own = attrs(&fonts[0], families[0].as_deref());
765 if self.spans.is_empty() {
766 self
767 .buffer
768 .set_text(&self.content, &own, Shaping::Advanced, None);
769 } else {
770 let spans = self.spans.iter().enumerate().map(|(index, span)| {
771 let font = &fonts[index + 1];
772 let mut attrs = attrs(font, families[index + 1].as_deref()).metadata(index + 1);
773 if let Some(color) = span.color {
774 attrs = attrs.color(cosmic_text::Color::rgba(color.r, color.g, color.b, color.a));
775 }
776 (span.text.as_str(), attrs)
777 });
778 self
779 .buffer
780 .set_rich_text(spans, &own, Shaping::Advanced, None);
781 }
782 let align = style.align.and_then(|align| match align {
783 TextAlign::Start => None,
784 TextAlign::Center => Some(Align::Center),
785 TextAlign::End => Some(Align::End),
786 TextAlign::Justify => Some(Align::Justified),
787 });
788 for line in &mut self.buffer.lines {
789 line.set_align(align);
790 }
791 self.buffer.shape_until_scroll(text.font_system(), false);
792 }
793
794 fn fallback_chars(
801 &self,
802 fonts: &[Font],
803 families: &[Option<Rc<str>>],
804 db: &Database,
805 ) -> Vec<(Font, Vec<char>)> {
806 let in_family = |glyph: &LayoutGlyph| {
807 let family = families.get(glyph.metadata).cloned().flatten();
808 db.face(glyph.font_id).is_some_and(|face| {
809 face
810 .families
811 .iter()
812 .any(|(name, _)| Some(name.as_str()) == family.as_deref())
813 })
814 };
815 let mut missing: Vec<(Font, Vec<char>)> = Vec::new();
816 let mut seen = HashSet::new();
817 for run in self.buffer.layout_runs() {
818 let fallback = |glyph: &&LayoutGlyph| glyph.glyph_id == 0 || !in_family(glyph);
819 for glyph in run.glyphs.iter().filter(fallback) {
820 let font = fonts[glyph.metadata.min(fonts.len() - 1)];
821 for ch in run.text.get(glyph.start..glyph.end).unwrap_or("").chars() {
822 if !seen.insert((font.weight, font.italic, ch)) {
823 continue;
824 }
825 match missing
826 .iter_mut()
827 .find(|(other, _)| (other.weight, other.italic) == (font.weight, font.italic))
828 {
829 Some((_, chars)) => chars.push(ch),
830 None => missing.push((font, vec![ch])),
831 }
832 }
833 }
834 }
835 missing
836 }
837
838 pub(crate) fn measure(
843 &mut self,
844 fonts: &mut FontSystem,
845 known: taffy::Size<Option<f32>>,
846 available: taffy::Size<AvailableSpace>,
847 ) -> taffy::Size<f32> {
848 let width = if self.fits_width() {
849 known.width.or(match available.width {
850 AvailableSpace::Definite(width) => Some(width),
851 AvailableSpace::MinContent => Some(0.0),
852 AvailableSpace::MaxContent => None,
853 })
854 } else {
855 None
856 };
857 self.buffer.set_size(width, None);
858 self.buffer.shape_until_scroll(fonts, false);
859 taffy::Size {
860 width: known.width.unwrap_or_else(|| self.width().ceil()),
861 height: known.height.unwrap_or_else(|| self.height().ceil()),
862 }
863 }
864
865 pub(crate) fn finish(&mut self, content: Rect, fonts: &mut FontSystem) {
869 let width = (self.fits_width() || self.aligned()).then_some(content.width);
870 self.finish_at(content, width, fonts);
871 }
872
873 pub(crate) fn finish_at(&mut self, content: Rect, width: Option<f32>, fonts: &mut FontSystem) {
876 self.buffer.set_size(width, None);
877 self.buffer.shape_until_scroll(fonts, false);
878 let top = ((content.height - self.height()) / 2.0).round();
879 self.origin = Point::new(content.x, content.y + top);
880 }
881
882 pub(crate) fn ink_box(&self) -> Rect {
890 let metrics = self.buffer.metrics();
891 let em = metrics.font_size;
892 let squeezed = ((1.2 * em).round() - metrics.line_height).max(0.0) / 2.0;
893 let width = self.buffer.size().0.unwrap_or(0.0).max(self.width());
894 Rect::new(
895 self.origin.x - em,
896 self.origin.y - em / 2.0 - squeezed,
897 width.ceil() + 2.0 * em,
898 self.height() + em + 2.0 * squeezed,
899 )
900 }
901
902 pub(crate) fn glyph_span(&self, line: usize, glyph: &LayoutGlyph) -> Option<usize> {
907 let index = glyph.metadata.checked_sub(1)?;
908 let from = *self.span_starts.get(index)?;
909 let to = from + self.spans.get(index)?.text.len();
910 let line_start = *self.line_starts.get(line)?;
911 let (start, end) = (line_start + glyph.start, line_start + glyph.end);
912 (start < end && from <= start && end <= to).then_some(index)
913 }
914
915 pub(crate) fn link_at(&self, point: Point) -> Option<usize> {
920 if !self.links_on() {
921 return None;
922 }
923 let (x, y) = (point.x - self.origin.x, point.y - self.origin.y);
924 let run = self
925 .runs()
926 .find(|run| y >= run.line_top && y < run.line_top + run.line_height)?;
927 let glyph = run
928 .glyphs
929 .iter()
930 .find(|glyph| x >= glyph.x && x < glyph.x + glyph.w)?;
931 let index = self.glyph_span(run.line_i, glyph)?;
932 self.spans[index].link.as_ref()?;
933 Some(index)
934 }
935
936 fn links_on(&self) -> bool {
939 self
940 .on_link
941 .as_ref()
942 .is_some_and(|handler| !handler.disabled())
943 }
944
945 pub(crate) fn lit(&self, index: usize) -> bool {
948 self.links_on()
949 && (self.hovered_link == Some(index) || self.focused_link == Some(index))
950 && self
951 .spans
952 .get(index)
953 .is_some_and(|span| span.link.is_some())
954 }
955
956 pub(crate) fn link_stops(&self) -> Vec<usize> {
959 if !self.links_on() {
960 return Vec::new();
961 }
962 let mut stops: Vec<usize> = self
963 .runs()
964 .flat_map(|run| {
965 let spans = run.glyphs.iter();
966 let spans = spans.filter_map(|glyph| self.glyph_span(run.line_i, glyph));
967 spans.collect::<Vec<_>>()
968 })
969 .filter(|&index| self.spans[index].link.is_some())
970 .collect();
971 stops.sort_unstable();
972 stops.dedup();
973 stops
974 }
975
976 pub(crate) fn link_areas(&self, index: usize) -> Vec<Rect> {
980 let em = self.buffer.metrics().font_size;
981 self
982 .runs()
983 .filter_map(|run| {
984 let mine = run
985 .glyphs
986 .iter()
987 .filter(|glyph| self.glyph_span(run.line_i, glyph) == Some(index));
988 let (start, end) = mine.fold(None, |span: Option<(f32, f32)>, glyph| {
989 let (start, end) = span.unwrap_or((glyph.x, glyph.x + glyph.w));
990 Some((start.min(glyph.x), end.max(glyph.x + glyph.w)))
991 })?;
992 Some(Rect::new(
993 self.origin.x + start - em,
994 self.origin.y + run.line_top - em / 2.0,
995 end - start + 2.0 * em,
996 run.line_height + em,
997 ))
998 })
999 .collect()
1000 }
1001
1002 pub(crate) fn empty_line_place(&self, rtl: bool) -> f32 {
1007 let start = if rtl { 1.0 } else { 0.0 };
1008 match self.style.and_then(|style| style.align) {
1009 Some(TextAlign::Center) => 0.5,
1010 Some(TextAlign::End) => 1.0 - start,
1011 _ => start,
1012 }
1013 }
1014
1015 pub(crate) fn layout_width(&self) -> f32 {
1018 self.buffer.size().0.unwrap_or_else(|| self.width())
1019 }
1020
1021 pub(crate) fn runs(&self) -> impl Iterator<Item = TextRun<'_>> {
1025 self
1026 .buffer
1027 .layout_runs()
1028 .take(self.max_lines as usize)
1029 .map(|run| {
1030 let moved = 1.0 - self.empty_line_place(false);
1032 TextRun::shown(run, moved)
1033 })
1034 }
1035
1036 pub(crate) fn width(&self) -> f32 {
1037 self.runs().map(|run| run.line_w).fold(0.0, f32::max)
1038 }
1039
1040 fn height(&self) -> f32 {
1041 self.runs().map(|run| run.line_height).sum()
1042 }
1043}
1044
1045#[derive(Clone, Debug)]
1049pub struct TextRun<'a> {
1050 pub line_i: usize,
1052 pub text: &'a str,
1054 pub rtl: bool,
1056 pub glyphs: Cow<'a, [LayoutGlyph]>,
1058 pub line_y: f32,
1060 pub line_top: f32,
1062 pub line_height: f32,
1064 pub line_w: f32,
1066 pub(crate) shift: f32,
1068 pub(crate) first: usize,
1069}
1070
1071impl<'a> TextRun<'a> {
1072 fn shown(run: LayoutRun<'a>, moved: f32) -> TextRun<'a> {
1081 let elided = run.glyphs.iter().any(|glyph| glyph.start == glyph.end);
1084 let blank = |glyph: &&LayoutGlyph| {
1085 glyph.start > 0
1086 && glyph.start < glyph.end
1087 && run
1088 .text
1089 .get(glyph.start..glyph.end)
1090 .is_some_and(|text| text.chars().all(char::is_whitespace))
1091 };
1092 let dropped = match elided && !run.rtl {
1093 true => run.glyphs.iter().take_while(blank).count(),
1094 false => 0,
1095 };
1096 let (glyphs, width, shift, first) = if dropped == 0 {
1097 (Cow::Borrowed(run.glyphs), 0.0, 0.0, 0)
1098 } else {
1099 let width: f32 = run.glyphs[..dropped].iter().map(|glyph| glyph.w).sum();
1100 let shift = width * moved;
1101 let glyphs = run.glyphs[dropped..].iter().map(|glyph| LayoutGlyph {
1102 x: glyph.x - shift,
1103 ..glyph.clone()
1104 });
1105 let first = run.glyphs.get(dropped).map_or(0, |glyph| glyph.start);
1106 (Cow::Owned(glyphs.collect()), width, shift, first)
1107 };
1108 TextRun {
1109 first,
1110 line_i: run.line_i,
1111 text: run.text,
1112 rtl: run.rtl,
1113 glyphs,
1114 line_y: run.line_y,
1115 line_top: run.line_top,
1116 line_height: run.line_height,
1117 line_w: run.line_w - width,
1118 shift,
1119 }
1120 }
1121
1122 pub(crate) fn layout(&self) -> LayoutRun<'_> {
1125 LayoutRun {
1126 line_i: self.line_i,
1127 text: self.text,
1128 rtl: self.rtl,
1129 glyphs: &self.glyphs,
1130 decorations: &[],
1131 line_y: self.line_y,
1132 line_top: self.line_top,
1133 line_height: self.line_height,
1134 line_w: self.line_w,
1135 }
1136 }
1137}