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, CacheKey, CacheKeyFlags, Command, Ellipsize, EllipsizeHeightLimit, Family,
25 FeatureTag, FontFeatures, FontSystem, LayoutGlyph, LayoutRun, Metrics, Shaping, SwashCache,
26 Weight, Wrap,
27};
28use fontconfig::{CharSet, FC_FAMILY, FC_SLANT, FC_SLANT_ITALIC, FC_WEIGHT, Fontconfig, Pattern};
29use taffy::AvailableSpace;
30
31use crate::geometry::{Point, Rect};
32use crate::input::LinkHandler;
33use crate::rich::Span;
34use crate::style::{Color, Font, Style, TextAlign};
35use crate::widgets::Elide;
36
37#[derive(Clone, Default)]
49pub struct TextSystem(Rc<RefCell<Fonts>>);
50
51impl TextSystem {
52 pub fn new() -> TextSystem {
54 TextSystem::default()
55 }
56
57 pub fn font_system(&self) -> RefMut<'_, FontSystem> {
60 RefMut::map(self.fonts(), |fonts| &mut fonts.fonts)
61 }
62
63 pub(crate) fn fonts(&self) -> RefMut<'_, Fonts> {
65 self
66 .0
67 .try_borrow_mut()
68 .expect("nothing that holds the fonts runs user code, which may measure text")
69 }
70}
71
72thread_local! {
73 static FONTS_ADDED: Cell<u64> = const { Cell::new(0) };
76}
77
78pub(crate) fn fonts_added() -> u64 {
79 FONTS_ADDED.get()
80}
81
82#[derive(Clone, Copy, Debug, Default, PartialEq)]
85pub struct TextMetrics {
86 pub width: f32,
88 pub height: f32,
90 pub ascent: f32,
92 pub descent: f32,
94 pub line_height: f32,
96 pub ink: Rect,
105}
106
107pub(crate) const INK_GLYPHS: usize = 4096;
110
111fn outline_extremes(commands: &[Command], mut add: impl FnMut(f32, f32)) {
114 let mut last = (0.0, 0.0);
115 for command in commands {
116 last = match *command {
117 Command::MoveTo(p) | Command::LineTo(p) => curve_extremes(&[last, (p.x, p.y)], &mut add),
118 Command::QuadTo(c, p) => curve_extremes(&[last, (c.x, c.y), (p.x, p.y)], &mut add),
119 Command::CurveTo(c1, c2, p) => {
120 curve_extremes(&[last, (c1.x, c1.y), (c2.x, c2.y), (p.x, p.y)], &mut add)
121 }
122 Command::Close => continue,
123 };
124 }
125}
126
127pub(crate) fn curve_extremes(points: &[(f32, f32)], add: &mut impl FnMut(f32, f32)) -> (f32, f32) {
132 let end = points[points.len() - 1];
133 add(end.0, end.1);
134 let axis = |point: &(f32, f32), y: bool| if y { point.1 } else { point.0 };
135 let at = |t: f32, y: bool| -> f32 {
136 let u = 1.0 - t;
137 match points {
138 [a, b, c] => u * u * axis(a, y) + 2.0 * u * t * axis(b, y) + t * t * axis(c, y),
139 [a, b, c, d] => {
140 u * u * u * axis(a, y)
141 + 3.0 * u * u * t * axis(b, y)
142 + 3.0 * u * t * t * axis(c, y)
143 + t * t * t * axis(d, y)
144 }
145 _ => axis(&end, y),
146 }
147 };
148 for y in [false, true] {
149 let mut values = [0.0; 4];
150 for (value, point) in values.iter_mut().zip(points) {
151 *value = axis(point, y);
152 }
153 for t in turns(&values[..points.len()]).into_iter().flatten() {
154 add(at(t, false), at(t, true));
155 }
156 }
157 end
158}
159
160fn turns(values: &[f32]) -> [Option<f32>; 2] {
163 let inside = |t: f32| (t > 0.0 && t < 1.0).then_some(t);
164 let (q, r, s) = match *values {
166 [a, b, c] => (0.0, a - 2.0 * b + c, b - a),
167 [a, b, c, d] => (-a + 3.0 * b - 3.0 * c + d, 2.0 * (a - 2.0 * b + c), b - a),
168 _ => return [None, None],
169 };
170 if q.abs() < 1e-6 {
171 return [(r.abs() >= 1e-6).then(|| -s / r).and_then(inside), None];
172 }
173 let discriminant = r * r - 4.0 * q * s;
174 if discriminant < 0.0 {
175 return [None, None];
176 }
177 let root = discriminant.sqrt();
178 [
179 inside((-r + root) / (2.0 * q)),
180 inside((-r - root) / (2.0 * q)),
181 ]
182}
183
184pub(crate) struct Fonts {
186 fonts: FontSystem,
187 fontconfig: Lookup,
188 families: HashMap<(&'static str, u16, bool), Option<Rc<str>>>,
191 pub(crate) loaded: HashMap<(PathBuf, u32), Option<Rc<str>>>,
193 files: HashSet<PathBuf>,
195 fallback_tried: HashSet<(char, &'static str, u16, bool)>,
198 bundled: HashMap<ID, (u16, u16)>,
201 pub(crate) ink: HashMap<CacheKey, Option<Rect>>,
205 #[cfg(test)]
207 pub(crate) glyphs_built: (usize, usize),
208}
209
210enum Lookup {
212 NotStarted,
213 Ready(Fontconfig),
214 Failed,
215}
216
217impl Fonts {
218 pub(crate) fn new() -> Fonts {
220 let fonts = FontSystem::new_with_locale_and_db("en-US".to_owned(), Database::new());
223 Fonts {
224 fonts,
225 fontconfig: Lookup::NotStarted,
226 families: HashMap::new(),
227 loaded: HashMap::new(),
228 files: HashSet::new(),
229 fallback_tried: HashSet::new(),
230 bundled: HashMap::new(),
231 ink: HashMap::new(),
232 #[cfg(test)]
233 glyphs_built: (0, 0),
234 }
235 }
236
237 pub(crate) fn font_system(&mut self) -> &mut FontSystem {
239 &mut self.fonts
240 }
241
242 #[cfg(test)]
244 pub(crate) fn fontconfig_started(&self) -> bool {
245 !matches!(self.fontconfig, Lookup::NotStarted)
246 }
247
248 fn fontconfig(&mut self) -> Option<&Fontconfig> {
249 if let Lookup::NotStarted = self.fontconfig {
250 self.fontconfig = match Fontconfig::new() {
251 Some(fontconfig) => Lookup::Ready(fontconfig),
252 None => {
253 tracing::error!("fontconfig failed to start, so no fonts can be loaded");
254 Lookup::Failed
255 }
256 };
257 }
258 match &self.fontconfig {
259 Lookup::Ready(fontconfig) => Some(fontconfig),
260 _ => None,
261 }
262 }
263
264 pub(crate) fn family(&mut self, font: &Font) -> Option<Rc<str>> {
269 let key = (font.family, font.weight, font.italic);
270 if let Some(name) = self.families.get(&key) {
271 return name.clone();
272 }
273 if let Some(name) = self.bundled(font) {
274 self.families.insert(key, Some(Rc::clone(&name)));
275 return Some(name);
276 }
277 let matched = self
278 .fontconfig()
279 .and_then(|fontconfig| match_font(fontconfig, font, None));
280 let name = matched.and_then(|file| self.load(file));
281 match &name {
282 Some(name) => tracing::debug!(requested = font.family, family = %name, "font loaded"),
283 None => tracing::warn!(
284 requested = font.family,
285 "no font found for this family, so its text shows nothing"
286 ),
287 }
288 self.families.insert(key, name.clone());
289 name
290 }
291
292 fn bundled(&self, font: &Font) -> Option<Rc<str>> {
296 let db = self.fonts.db();
297 self
298 .bundled
299 .iter()
300 .filter(|(_, (low, high))| (*low..=*high).contains(&font.weight))
301 .filter_map(|(&id, _)| db.face(id))
302 .filter(|face| (face.style != fontdb::Style::Normal) == font.italic)
303 .flat_map(|face| &face.families)
304 .find(|(name, _language)| name.eq_ignore_ascii_case(font.family))
305 .map(|(name, _language)| Rc::from(name.as_str()))
306 }
307
308 pub(crate) fn add(&mut self, bytes: &'static [u8]) {
312 let source = Source::Binary(Arc::new(bytes));
314 let mut probe = Database::new();
316 probe.load_font_source(source.clone());
317 let faces: Vec<_> = probe
318 .faces()
319 .map(|face| (face, weights(&probe, face)))
320 .collect();
321 if faces.is_empty() {
322 tracing::warn!(
323 bytes = bytes.len(),
324 "a bundled font has no face that could be read, so it is ignored"
325 );
326 return;
327 }
328 let names: Vec<&str> = faces
329 .iter()
330 .flat_map(|(face, _)| face.families.iter().map(|(name, _)| name.as_str()))
331 .collect();
332 tracing::debug!(?names, "font added");
333 let same_family = |a: &FaceInfo, b: &FaceInfo| {
334 a.families.iter().any(|(name, _)| {
335 b.families
336 .iter()
337 .any(|(other, _)| name.eq_ignore_ascii_case(other))
338 })
339 };
340 let replaced: Vec<_> = self
344 .fonts
345 .db()
346 .faces()
347 .filter(|old| {
348 faces.iter().any(|(new, (low, high))| {
349 new.style == old.style && (*low..=*high).contains(&old.weight.0) && same_family(new, old)
350 })
351 })
352 .filter_map(|old| {
353 let family = old
354 .families
355 .first()
356 .map(|(name, _)| Rc::from(name.as_str()));
357 Some((
358 old.id,
359 (source_path(&old.source)?.clone(), old.index),
360 family,
361 ))
362 })
363 .collect();
364 let db = self.fonts.db_mut();
365 for (id, face, family) in replaced {
366 db.remove_face(id);
367 self.loaded.entry(face).or_insert(family);
370 }
371 let ids = db.load_font_source(source);
373 for (id, (_, weights)) in ids.into_iter().zip(&faces) {
374 self.bundled.insert(id, *weights);
375 }
376 self
377 .families
378 .retain(|(family, _, _), _| !names.iter().any(|name| name.eq_ignore_ascii_case(family)));
379 self.fallback_tried.clear();
381 self.ink.clear();
382 FONTS_ADDED.set(FONTS_ADDED.get() + 1);
383 }
384
385 pub(crate) fn measure(&mut self, content: &str, font: Font) -> TextMetrics {
387 let mut node = TextNode::new();
388 node.set_content(content.to_owned());
389 node.set_max_lines(u32::MAX);
390 node.prepare(font, self);
391 let Metrics {
392 font_size,
393 line_height,
394 } = node.buffer.metrics();
395 let weight = Weight(font.weight);
396 let face = self.family(&font).and_then(|name| {
397 self.fonts.db().query(&Query {
398 families: &[Family::Name(&name)],
399 weight,
400 style: if font.italic {
401 fontdb::Style::Italic
402 } else {
403 fontdb::Style::Normal
404 },
405 ..Query::default()
406 })
407 });
408 let (ascent, descent) =
409 face
410 .and_then(|id| self.fonts.get_font(id, weight))
411 .map_or((0.0, 0.0), |face| {
412 let metrics = face.metrics();
413 let scale = font_size / f32::from(metrics.units_per_em);
414 (metrics.ascent * scale, -metrics.descent * scale)
415 });
416 TextMetrics {
417 width: node.width(),
418 height: node.height(),
419 ascent,
420 descent,
421 line_height,
422 ink: self.ink(&node),
423 }
424 }
425
426 fn ink(&mut self, node: &TextNode) -> Rect {
429 let mut scaler = None;
431 let mut ink = [
433 f32::INFINITY,
434 f32::INFINITY,
435 f32::NEG_INFINITY,
436 f32::NEG_INFINITY,
437 ];
438 for run in node.runs() {
439 for glyph in run.glyphs.iter() {
440 let (key, _, _) = CacheKey::new(
441 glyph.font_id,
442 glyph.glyph_id,
443 glyph.font_size,
444 (0.0, 0.0),
445 glyph.font_weight,
446 glyph.cache_key_flags | CacheKeyFlags::DISABLE_HINTING,
447 );
448 let found = match self.ink.get(&key) {
449 Some(found) => *found,
450 None => {
451 let found = self.glyph_ink(scaler.get_or_insert_with(SwashCache::new), key);
452 if self.ink.len() >= INK_GLYPHS {
453 self.ink.clear();
454 }
455 self.ink.insert(key, found);
456 found
457 }
458 };
459 let Some(found) = found else {
460 continue;
461 };
462 let x = glyph.x + glyph.font_size * glyph.x_offset;
463 let y = run.line_y + glyph.y - glyph.font_size * glyph.y_offset;
464 ink = [
465 ink[0].min(x + found.x),
466 ink[1].min(y + found.y),
467 ink[2].max(x + found.right()),
468 ink[3].max(y + found.bottom()),
469 ];
470 }
471 }
472 match ink[0] <= ink[2] {
473 true => Rect::new(ink[0], ink[1], ink[2] - ink[0], ink[3] - ink[1]),
474 false => Rect::default(),
475 }
476 }
477
478 fn glyph_ink(&mut self, scaler: &mut SwashCache, key: CacheKey) -> Option<Rect> {
482 let outline = scaler.get_outline_commands_uncached(&mut self.fonts, key);
485 let Some(commands) = outline.filter(|commands| !commands.is_empty()) else {
486 #[cfg(test)]
487 {
488 self.glyphs_built.1 += 1;
489 }
490 let placement = scaler.get_image_uncached(&mut self.fonts, key)?.placement;
491 let (width, height) = (placement.width as f32, placement.height as f32);
492 return (width > 0.0 && height > 0.0)
493 .then(|| Rect::new(placement.left as f32, -placement.top as f32, width, height));
494 };
495 #[cfg(test)]
496 {
497 self.glyphs_built.0 += 1;
498 }
499 let mut ink = [
500 f32::INFINITY,
501 f32::INFINITY,
502 f32::NEG_INFINITY,
503 f32::NEG_INFINITY,
504 ];
505 outline_extremes(&commands, |x, y| {
507 ink = [ink[0].min(x), ink[1].min(-y), ink[2].max(x), ink[3].max(-y)];
508 });
509 (ink[0] <= ink[2]).then(|| Rect::new(ink[0], ink[1], ink[2] - ink[0], ink[3] - ink[1]))
510 }
511
512 fn load_fallbacks(&mut self, font: &Font, missing: &[char]) -> bool {
516 let faces = self.fonts.db().len();
517 for &ch in missing {
518 if !self
519 .fallback_tried
520 .insert((ch, font.family, font.weight, font.italic))
521 {
522 continue;
523 }
524 let Some(file) = self
525 .fontconfig()
526 .and_then(|fontconfig| match_font(fontconfig, font, Some(ch)))
527 else {
528 continue;
529 };
530 self.load(file);
531 }
532 self.fonts.db().len() > faces
533 }
534
535 pub(crate) fn load(&mut self, (path, index): (PathBuf, u32)) -> Option<Rc<str>> {
538 let key = (path, index);
539 if let Some(name) = self.loaded.get(&key) {
540 return name.clone();
541 }
542 let (path, index) = &key;
543 if !self.files.contains(path) {
544 self.files.insert(path.clone());
545 if let Err(error) = self.fonts.db_mut().load_font_file(path) {
546 tracing::warn!(path = %path.display(), %error, "couldn't read a font file");
547 }
548 }
549 let name = self
550 .fonts
551 .db()
552 .faces()
553 .find(|face| face.index == *index && source_path(&face.source) == Some(path))
554 .and_then(|face| face.families.first())
555 .map(|(name, _language)| Rc::from(name.as_str()));
556 self.loaded.insert(key, name.clone());
557 name
558 }
559}
560
561impl Default for Fonts {
562 fn default() -> Self {
563 Self::new()
564 }
565}
566
567fn weights(db: &Database, face: &FaceInfo) -> (u16, u16) {
570 let wght = u32::from_be_bytes(*b"wght");
571 let axis = cosmic_text::Font::new(db, face.id, face.weight).and_then(|font| {
572 let axis = font
573 .as_swash()
574 .variations()
575 .find(|axis| axis.tag() == wght)?;
576 Some((axis.min_value() as u16, axis.max_value() as u16))
578 });
579 axis.unwrap_or((face.weight.0, face.weight.0))
580}
581
582fn source_path(source: &Source) -> Option<&PathBuf> {
583 match source {
584 Source::File(path) | Source::SharedFile(path, _) => Some(path),
585 Source::Binary(_) => None,
586 }
587}
588
589fn match_font(
592 fontconfig: &Fontconfig,
593 font: &Font,
594 covering: Option<char>,
595) -> Option<(PathBuf, u32)> {
596 let mut pattern = Pattern::new(fontconfig).ok()?;
597 pattern
598 .add_string(FC_FAMILY, &CString::new(font.family).ok()?)
599 .ok()?;
600 pattern
601 .add_integer(FC_WEIGHT, fc_weight(font.weight))
602 .ok()?;
603 if font.italic {
604 pattern.add_integer(FC_SLANT, FC_SLANT_ITALIC).ok()?;
605 }
606 if let Some(ch) = covering {
607 let mut chars = CharSet::new(fontconfig).ok()?;
608 chars.add_char(ch).ok()?;
609 pattern.add_charset(chars).ok()?;
610 }
611 let matched = pattern.font_match().ok()?;
612 let path = PathBuf::from(matched.filename().ok()?);
613 let index = matched.face_index().ok().map_or(0, face_number);
614 Some((path, index))
615}
616
617pub(crate) fn face_number(index: i32) -> u32 {
622 u32::try_from(index & 0xFFFF).unwrap_or(0)
624}
625
626pub(crate) fn fc_weight(weight: u16) -> i32 {
630 const POINTS: [(f32, f32); 12] = [
631 (100.0, 0.0),
632 (200.0, 40.0),
633 (300.0, 50.0),
634 (350.0, 55.0),
635 (380.0, 75.0),
636 (400.0, 80.0),
637 (500.0, 100.0),
638 (600.0, 180.0),
639 (700.0, 200.0),
640 (800.0, 205.0),
641 (900.0, 210.0),
642 (1000.0, 215.0),
643 ];
644 let weight = f32::from(weight).clamp(100.0, 1000.0);
645 let upper = POINTS
646 .iter()
647 .position(|&(css, _)| css >= weight)
648 .unwrap_or(POINTS.len() - 1)
649 .max(1);
650 let (css_low, fc_low) = POINTS[upper - 1];
651 let (css_high, fc_high) = POINTS[upper];
652 let fc = fc_low + (weight - css_low) / (css_high - css_low) * (fc_high - fc_low);
653 fc.round() as i32
654}
655
656#[derive(Clone, Copy, Debug, PartialEq)]
659pub(crate) struct TextStyle {
660 pub(crate) font: Font,
661 pub(crate) align: Option<TextAlign>,
662 pub(crate) line_height: Option<f32>,
663}
664
665impl TextStyle {
666 pub(crate) fn inherit(self, style: &Style) -> TextStyle {
668 TextStyle {
669 font: style.font.unwrap_or(self.font),
670 align: style.text_align.or(self.align),
671 line_height: style.line_height.or(self.line_height),
672 }
673 }
674}
675
676impl From<Font> for TextStyle {
677 fn from(font: Font) -> TextStyle {
678 TextStyle {
679 font,
680 align: None,
681 line_height: None,
682 }
683 }
684}
685
686fn span_font(span: &Span, font: Font) -> Font {
688 Font {
689 weight: if span.bold { 700 } else { font.weight },
690 italic: font.italic || span.italic,
691 ..font
692 }
693}
694
695fn attrs<'a>(font: &Font, family: Option<&'a str>) -> Attrs<'a> {
697 let mut attrs = Attrs::new().weight(Weight(font.weight));
698 if let Some(family) = family {
699 attrs = attrs.family(Family::Name(family));
700 }
701 if font.italic {
702 attrs = attrs.style(cosmic_text::Style::Italic);
703 }
704 if font.letter_spacing.is_finite() && font.letter_spacing != 0.0 {
707 attrs = attrs.letter_spacing((font.letter_spacing / font_size(font)).max(-0.5));
708 }
709 if !font.features.is_empty() {
710 let mut features = FontFeatures::new();
711 for feature in font.features {
712 features.set(FeatureTag::new(&feature.tag), feature.value);
713 }
714 attrs = attrs.font_features(features);
715 }
716 attrs
717}
718
719fn metrics(style: &TextStyle) -> Metrics {
723 let size = font_size(&style.font);
724 let multiple = style
725 .line_height
726 .filter(|multiple| multiple.is_finite() && *multiple > 0.0)
727 .unwrap_or(1.2);
728 Metrics::new(size, (size * multiple).round().max(1.0))
729}
730
731fn font_size(font: &Font) -> f32 {
732 if font.size.is_finite() && font.size >= 1.0 {
733 font.size
734 } else {
735 Font::DEFAULT.size
736 }
737}
738
739pub(crate) struct TextNode {
743 pub(crate) content: String,
745 pub(crate) spans: Vec<Span>,
750 span_starts: Vec<usize>,
752 line_starts: Vec<usize>,
754 pub(crate) elide: Elide,
755 pub(crate) max_lines: u32,
757 pub(crate) wrap: bool,
760 pub(crate) buffer: Buffer,
761 style: Option<TextStyle>,
763 fonts_added: u64,
765 stale: bool,
768 pub(crate) origin: Point,
770 pub(crate) selectable: bool,
772 pub(crate) cursor: usize,
775 pub(crate) anchor: Option<usize>,
776 pub(crate) on_link: Option<LinkHandler>,
778 pub(crate) hovered_link: Option<usize>,
781 pub(crate) focused_link: Option<usize>,
782 pub(crate) link_hover_color: Option<Color>,
784}
785
786impl TextNode {
787 pub(crate) fn new() -> TextNode {
788 TextNode {
789 content: String::new(),
790 spans: Vec::new(),
791 span_starts: Vec::new(),
792 line_starts: Vec::new(),
793 elide: Elide::None,
794 max_lines: 1,
795 wrap: true,
796 buffer: {
797 let mut buffer = Buffer::new_empty(metrics(&Font::DEFAULT.into()));
798 buffer.set_tab_width(4);
800 buffer
801 },
802 style: None,
803 fonts_added: 0,
804 stale: true,
805 origin: Point::default(),
806 selectable: false,
807 cursor: 0,
808 anchor: None,
809 on_link: None,
810 hovered_link: None,
811 focused_link: None,
812 link_hover_color: None,
813 }
814 }
815
816 pub(crate) fn set_content(&mut self, content: String) -> bool {
819 self.set(|text| &mut text.content, content)
820 }
821
822 pub(crate) fn set_spans(&mut self, spans: Vec<Span>) -> bool {
825 let content = spans.iter().map(|span| span.text.as_str()).collect();
826 self.span_starts = spans
827 .iter()
828 .scan(0, |start, span| {
829 let this = *start;
830 *start += span.text.len();
831 Some(this)
832 })
833 .collect();
834 let changed = self.set(|text| &mut text.spans, spans);
835 let new_text = self.set_content(content);
836 self.forget_selection_if(new_text) | changed
837 }
838
839 pub(crate) fn forget_selection_if(&mut self, changed: bool) -> bool {
842 if changed {
843 self.anchor = None;
844 self.cursor = 0;
845 }
846 changed
847 }
848
849 pub(crate) fn set_elide(&mut self, elide: Elide) -> bool {
850 self.set(|text| &mut text.elide, elide)
851 }
852
853 pub(crate) fn set_max_lines(&mut self, max_lines: u32) -> bool {
854 self.set(|text| &mut text.max_lines, max_lines.max(1))
855 }
856
857 pub(crate) fn set_wrap(&mut self, wrap: bool) -> bool {
858 self.set(|text| &mut text.wrap, wrap)
859 }
860
861 fn set<T: PartialEq>(&mut self, field: impl FnOnce(&mut TextNode) -> &mut T, value: T) -> bool {
862 let slot = field(self);
863 if *slot == value {
864 return false;
865 }
866 *slot = value;
867 self.stale = true;
868 true
869 }
870
871 fn fits_width(&self) -> bool {
874 self.elide != Elide::None || self.wraps()
875 }
876
877 pub(crate) fn wraps(&self) -> bool {
878 self.max_lines > 1 && self.wrap
879 }
880
881 pub(crate) fn aligned(&self) -> bool {
883 self.style.is_some_and(|style| style.align.is_some())
884 }
885
886 pub(crate) fn prepare(&mut self, style: impl Into<TextStyle>, text: &mut Fonts) -> bool {
891 let style = style.into();
892 if !self.stale && self.style == Some(style) && self.fonts_added == fonts_added() {
893 return false;
894 }
895 let fonts: Vec<Font> = std::iter::once(style.font)
897 .chain(self.spans.iter().map(|span| span_font(span, style.font)))
898 .collect();
899 let families: Vec<_> = fonts.iter().map(|font| text.family(font)).collect();
900 self.buffer.set_metrics(metrics(&style));
901 self.buffer.set_wrap(if self.wraps() {
903 Wrap::WordOrGlyph
904 } else {
905 Wrap::None
906 });
907 let lines = EllipsizeHeightLimit::Lines(self.max_lines as usize);
908 self.buffer.set_ellipsize(match self.elide {
909 Elide::None => Ellipsize::None,
910 Elide::Start => Ellipsize::Start(lines),
911 Elide::Middle => Ellipsize::Middle(lines),
912 Elide::End => Ellipsize::End(lines),
913 });
914 self.buffer.set_size(None, None);
915 self.shape(&fonts, &families, &style, text);
916 let missing = self.fallback_chars(&fonts, &families, text.font_system().db());
917 let mut gained = false;
918 for (font, chars) in missing {
919 gained |= text.load_fallbacks(&font, &chars);
920 }
921 if gained {
922 self.shape(&fonts, &families, &style, text);
923 }
924 self.line_starts = self
925 .buffer
926 .lines
927 .iter()
928 .scan(0, |start, line| {
929 let this = *start;
930 *start += line.text().len() + line.ending().as_str().len();
931 Some(this)
932 })
933 .collect();
934 self.style = Some(style);
935 self.fonts_added = fonts_added();
936 self.stale = false;
937 true
938 }
939
940 fn shape(
943 &mut self,
944 fonts: &[Font],
945 families: &[Option<Rc<str>>],
946 style: &TextStyle,
947 text: &mut Fonts,
948 ) {
949 let own = attrs(&fonts[0], families[0].as_deref());
950 if self.spans.is_empty() {
951 self
952 .buffer
953 .set_text(&self.content, &own, Shaping::Advanced, None);
954 } else {
955 let spans = self.spans.iter().enumerate().map(|(index, span)| {
956 let font = &fonts[index + 1];
957 let mut attrs = attrs(font, families[index + 1].as_deref()).metadata(index + 1);
958 if let Some(color) = span.color {
959 attrs = attrs.color(cosmic_text::Color::rgba(color.r, color.g, color.b, color.a));
960 }
961 (span.text.as_str(), attrs)
962 });
963 self
964 .buffer
965 .set_rich_text(spans, &own, Shaping::Advanced, None);
966 }
967 let align = style.align.and_then(|align| match align {
968 TextAlign::Start => None,
969 TextAlign::Center => Some(Align::Center),
970 TextAlign::End => Some(Align::End),
971 TextAlign::Justify => Some(Align::Justified),
972 });
973 for line in &mut self.buffer.lines {
974 line.set_align(align);
975 }
976 self.buffer.shape_until_scroll(text.font_system(), false);
977 }
978
979 fn fallback_chars(
986 &self,
987 fonts: &[Font],
988 families: &[Option<Rc<str>>],
989 db: &Database,
990 ) -> Vec<(Font, Vec<char>)> {
991 let in_family = |glyph: &LayoutGlyph| {
992 let family = families.get(glyph.metadata).cloned().flatten();
993 db.face(glyph.font_id).is_some_and(|face| {
994 face
995 .families
996 .iter()
997 .any(|(name, _)| Some(name.as_str()) == family.as_deref())
998 })
999 };
1000 let mut missing: Vec<(Font, Vec<char>)> = Vec::new();
1001 let mut seen = HashSet::new();
1002 for run in self.buffer.layout_runs() {
1003 let fallback = |glyph: &&LayoutGlyph| glyph.glyph_id == 0 || !in_family(glyph);
1004 for glyph in run.glyphs.iter().filter(fallback) {
1005 let font = fonts[glyph.metadata.min(fonts.len() - 1)];
1006 for ch in run.text.get(glyph.start..glyph.end).unwrap_or("").chars() {
1007 if !seen.insert((font.weight, font.italic, ch)) {
1008 continue;
1009 }
1010 match missing
1011 .iter_mut()
1012 .find(|(other, _)| (other.weight, other.italic) == (font.weight, font.italic))
1013 {
1014 Some((_, chars)) => chars.push(ch),
1015 None => missing.push((font, vec![ch])),
1016 }
1017 }
1018 }
1019 }
1020 missing
1021 }
1022
1023 pub(crate) fn measure(
1028 &mut self,
1029 fonts: &mut FontSystem,
1030 known: taffy::Size<Option<f32>>,
1031 available: taffy::Size<AvailableSpace>,
1032 ) -> taffy::Size<f32> {
1033 let width = if self.fits_width() {
1034 known.width.or(match available.width {
1035 AvailableSpace::Definite(width) => Some(width),
1036 AvailableSpace::MinContent => Some(0.0),
1037 AvailableSpace::MaxContent => None,
1038 })
1039 } else {
1040 None
1041 };
1042 self.buffer.set_size(width, None);
1043 self.buffer.shape_until_scroll(fonts, false);
1044 taffy::Size {
1045 width: known.width.unwrap_or_else(|| self.width().ceil()),
1046 height: known.height.unwrap_or_else(|| self.height().ceil()),
1047 }
1048 }
1049
1050 pub(crate) fn finish(&mut self, content: Rect, fonts: &mut FontSystem) {
1054 let width = (self.fits_width() || self.aligned()).then_some(content.width);
1055 self.finish_at(content, width, fonts);
1056 }
1057
1058 pub(crate) fn finish_at(&mut self, content: Rect, width: Option<f32>, fonts: &mut FontSystem) {
1061 self.buffer.set_size(width, None);
1062 self.buffer.shape_until_scroll(fonts, false);
1063 let top = ((content.height - self.height()) / 2.0).round();
1064 self.origin = Point::new(content.x, content.y + top);
1065 }
1066
1067 pub(crate) fn ink_box(&self) -> Rect {
1075 let metrics = self.buffer.metrics();
1076 let em = metrics.font_size;
1077 let squeezed = ((1.2 * em).round() - metrics.line_height).max(0.0) / 2.0;
1078 let width = self.buffer.size().0.unwrap_or(0.0).max(self.width());
1079 Rect::new(
1080 self.origin.x - em,
1081 self.origin.y - em / 2.0 - squeezed,
1082 width.ceil() + 2.0 * em,
1083 self.height() + em + 2.0 * squeezed,
1084 )
1085 }
1086
1087 pub(crate) fn glyph_span(&self, line: usize, glyph: &LayoutGlyph) -> Option<usize> {
1092 let index = glyph.metadata.checked_sub(1)?;
1093 let from = *self.span_starts.get(index)?;
1094 let to = from + self.spans.get(index)?.text.len();
1095 let line_start = *self.line_starts.get(line)?;
1096 let (start, end) = (line_start + glyph.start, line_start + glyph.end);
1097 (start < end && from <= start && end <= to).then_some(index)
1098 }
1099
1100 pub(crate) fn link_at(&self, point: Point) -> Option<usize> {
1105 if !self.links_on() {
1106 return None;
1107 }
1108 let (x, y) = (point.x - self.origin.x, point.y - self.origin.y);
1109 let run = self
1110 .runs()
1111 .find(|run| y >= run.line_top && y < run.line_top + run.line_height)?;
1112 let glyph = run
1113 .glyphs
1114 .iter()
1115 .find(|glyph| x >= glyph.x && x < glyph.x + glyph.w)?;
1116 let index = self.glyph_span(run.line_i, glyph)?;
1117 self.spans[index].link.as_ref()?;
1118 Some(index)
1119 }
1120
1121 fn links_on(&self) -> bool {
1124 self
1125 .on_link
1126 .as_ref()
1127 .is_some_and(|handler| !handler.disabled())
1128 }
1129
1130 pub(crate) fn lit(&self, index: usize) -> bool {
1133 self.links_on()
1134 && (self.hovered_link == Some(index) || self.focused_link == Some(index))
1135 && self
1136 .spans
1137 .get(index)
1138 .is_some_and(|span| span.link.is_some())
1139 }
1140
1141 pub(crate) fn link_stops(&self) -> Vec<usize> {
1144 if !self.links_on() {
1145 return Vec::new();
1146 }
1147 let mut stops: Vec<usize> = self
1148 .runs()
1149 .flat_map(|run| {
1150 let spans = run.glyphs.iter();
1151 let spans = spans.filter_map(|glyph| self.glyph_span(run.line_i, glyph));
1152 spans.collect::<Vec<_>>()
1153 })
1154 .filter(|&index| self.spans[index].link.is_some())
1155 .collect();
1156 stops.sort_unstable();
1157 stops.dedup();
1158 stops
1159 }
1160
1161 pub(crate) fn link_areas(&self, index: usize) -> Vec<Rect> {
1165 let em = self.buffer.metrics().font_size;
1166 self
1167 .runs()
1168 .filter_map(|run| {
1169 let mine = run
1170 .glyphs
1171 .iter()
1172 .filter(|glyph| self.glyph_span(run.line_i, glyph) == Some(index));
1173 let (start, end) = mine.fold(None, |span: Option<(f32, f32)>, glyph| {
1174 let (start, end) = span.unwrap_or((glyph.x, glyph.x + glyph.w));
1175 Some((start.min(glyph.x), end.max(glyph.x + glyph.w)))
1176 })?;
1177 Some(Rect::new(
1178 self.origin.x + start - em,
1179 self.origin.y + run.line_top - em / 2.0,
1180 end - start + 2.0 * em,
1181 run.line_height + em,
1182 ))
1183 })
1184 .collect()
1185 }
1186
1187 pub(crate) fn empty_line_place(&self, rtl: bool) -> f32 {
1192 let start = if rtl { 1.0 } else { 0.0 };
1193 match self.style.and_then(|style| style.align) {
1194 Some(TextAlign::Center) => 0.5,
1195 Some(TextAlign::End) => 1.0 - start,
1196 _ => start,
1197 }
1198 }
1199
1200 pub(crate) fn layout_width(&self) -> f32 {
1203 self.buffer.size().0.unwrap_or_else(|| self.width())
1204 }
1205
1206 pub(crate) fn runs(&self) -> impl Iterator<Item = TextRun<'_>> {
1210 self
1211 .buffer
1212 .layout_runs()
1213 .take(self.max_lines as usize)
1214 .map(|run| {
1215 let moved = 1.0 - self.empty_line_place(false);
1217 TextRun::shown(run, moved)
1218 })
1219 }
1220
1221 pub(crate) fn width(&self) -> f32 {
1222 self.runs().map(|run| run.line_w).fold(0.0, f32::max)
1223 }
1224
1225 fn height(&self) -> f32 {
1226 self.runs().map(|run| run.line_height).sum()
1227 }
1228}
1229
1230#[derive(Clone, Debug)]
1234pub struct TextRun<'a> {
1235 pub line_i: usize,
1237 pub text: &'a str,
1239 pub rtl: bool,
1241 pub glyphs: Cow<'a, [LayoutGlyph]>,
1243 pub line_y: f32,
1245 pub line_top: f32,
1247 pub line_height: f32,
1249 pub line_w: f32,
1251 pub(crate) shift: f32,
1253 pub(crate) first: usize,
1254}
1255
1256impl<'a> TextRun<'a> {
1257 fn shown(run: LayoutRun<'a>, moved: f32) -> TextRun<'a> {
1266 let elided = run.glyphs.iter().any(|glyph| glyph.start == glyph.end);
1269 let blank = |glyph: &&LayoutGlyph| {
1270 glyph.start > 0
1271 && glyph.start < glyph.end
1272 && run
1273 .text
1274 .get(glyph.start..glyph.end)
1275 .is_some_and(|text| text.chars().all(char::is_whitespace))
1276 };
1277 let dropped = match elided && !run.rtl {
1278 true => run.glyphs.iter().take_while(blank).count(),
1279 false => 0,
1280 };
1281 let (glyphs, width, shift, first) = if dropped == 0 {
1282 (Cow::Borrowed(run.glyphs), 0.0, 0.0, 0)
1283 } else {
1284 let width: f32 = run.glyphs[..dropped].iter().map(|glyph| glyph.w).sum();
1285 let shift = width * moved;
1286 let glyphs = run.glyphs[dropped..].iter().map(|glyph| LayoutGlyph {
1287 x: glyph.x - shift,
1288 ..glyph.clone()
1289 });
1290 let first = run.glyphs.get(dropped).map_or(0, |glyph| glyph.start);
1291 (Cow::Owned(glyphs.collect()), width, shift, first)
1292 };
1293 TextRun {
1294 first,
1295 line_i: run.line_i,
1296 text: run.text,
1297 rtl: run.rtl,
1298 glyphs,
1299 line_y: run.line_y,
1300 line_top: run.line_top,
1301 line_height: run.line_height,
1302 line_w: run.line_w - width,
1303 shift,
1304 }
1305 }
1306
1307 pub(crate) fn layout(&self) -> LayoutRun<'_> {
1310 LayoutRun {
1311 line_i: self.line_i,
1312 text: self.text,
1313 rtl: self.rtl,
1314 glyphs: &self.glyphs,
1315 decorations: &[],
1316 line_y: self.line_y,
1317 line_top: self.line_top,
1318 line_height: self.line_height,
1319 line_w: self.line_w,
1320 }
1321 }
1322}