Skip to main content

crabshell_ui/
text.rs

1//! Text: finding fonts through fontconfig, and the cosmic-text buffer each
2//! [`Text`](crate::Text) widget is measured with and drawn from.
3//!
4//! Scanning every installed font would cost tens of milliseconds at startup,
5//! so the font database starts empty. Each family a style names is resolved
6//! through fontconfig and only the file it matched is loaded. When a text
7//! uses a character none of the loaded fonts has, fontconfig names a font
8//! that has it, that file is loaded too, and the text is shaped again.
9//!
10//! A font a config bundles with [`Cx::add_font`](crate::Cx::add_font) is
11//! read from its bytes, and a family it provides is used before fontconfig
12//! is asked, so a config whose fonts are all bundled never starts it.
13
14use 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/// The fonts every window measures and draws text with.
37///
38/// There is one per process, and cloning it gives another handle to the
39/// same fonts. The platform passes it to
40/// [`Window::layout`](crate::Window::layout), the renderer rasterizes
41/// glyphs with its [`font_system`](Self::font_system), and the root [`Cx`]
42/// gets it as a service for [`Cx::measure_text`] and [`Cx::add_font`].
43///
44/// [`Cx`]: crate::Cx
45/// [`Cx::measure_text`]: crate::Cx::measure_text
46/// [`Cx::add_font`]: crate::Cx::add_font
47#[derive(Clone, Default)]
48pub struct TextSystem(Rc<RefCell<Fonts>>);
49
50impl TextSystem {
51  /// An empty font database. Nothing is loaded until text is laid out.
52  pub fn new() -> TextSystem {
53    TextSystem::default()
54  }
55
56  /// cosmic-text's font system, for rasterizing glyphs. Release it before
57  /// laying a window out.
58  pub fn font_system(&self) -> RefMut<'_, FontSystem> {
59    RefMut::map(self.fonts(), |fonts| &mut fonts.fonts)
60  }
61
62  /// The fonts, borrowed.
63  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  /// How many fonts were added. Text shaped before the last one shapes
73  /// again, and windows laid out before it lay out again.
74  static FONTS_ADDED: Cell<u64> = const { Cell::new(0) };
75}
76
77pub(crate) fn fonts_added() -> u64 {
78  FONTS_ADDED.get()
79}
80
81/// The size of text shaped with one font, from
82/// [`Cx::measure_text`](crate::Cx::measure_text), in logical pixels.
83#[derive(Clone, Copy, Debug, Default, PartialEq)]
84pub struct TextMetrics {
85  /// The advance of the widest line.
86  pub width: f32,
87  /// The line boxes: one line height per line.
88  pub height: f32,
89  /// How far the font rises above the baseline at this size.
90  pub ascent: f32,
91  /// How far the font reaches below the baseline at this size, positive.
92  pub descent: f32,
93  /// The height of one line, as a `Text` with this font has.
94  pub line_height: f32,
95}
96
97/// What a [`TextSystem`] holds.
98pub(crate) struct Fonts {
99  fonts: FontSystem,
100  fontconfig: Lookup,
101  /// The family name each requested family, weight and slant resolved
102  /// to, as the font database knows it. `None` if nothing was found.
103  families: HashMap<(&'static str, u16, bool), Option<Rc<str>>>,
104  /// The family name of each face asked for, by file and face number.
105  pub(crate) loaded: HashMap<(PathBuf, u32), Option<Rc<str>>>,
106  /// Files read into the database. Reading one loads all its faces.
107  files: HashSet<PathBuf>,
108  /// Characters a fallback font was already looked up for, by the family,
109  /// weight and slant asked for: fontconfig's answer depends on all three.
110  fallback_tried: HashSet<(char, &'static str, u16, bool)>,
111  /// The weights each bundled face draws, lowest and highest: one, or a
112  /// variable font's whole weight axis.
113  bundled: HashMap<ID, (u16, u16)>,
114}
115
116/// fontconfig, started on first use because that costs about 15 ms.
117enum Lookup {
118  NotStarted,
119  Ready(Fontconfig),
120  Failed,
121}
122
123impl Fonts {
124  /// An empty font database.
125  pub(crate) fn new() -> Fonts {
126    // cosmic-text needs a locale. Reading the system's would take another
127    // crate, and it only affects which script-specific fallbacks it tries.
128    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  /// cosmic-text's font system.
141  pub(crate) fn font_system(&mut self) -> &mut FontSystem {
142    &mut self.fonts
143  }
144
145  /// Whether fontconfig was started.
146  #[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  /// The name to ask cosmic-text for to get `font`'s family, weight and
168  /// slant: a bundled family of that name, or else the file fontconfig
169  /// matches, loaded the first time. `None`, logged once, if no font
170  /// could be loaded.
171  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  /// The database's name for `font`'s family if a bundled face of it
196  /// draws its weight and slant: italic or oblique for italic text,
197  /// upright for the rest.
198  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  /// Reads every face in `bytes` into the database, without copying them.
212  /// Families they provide are resolved again, and all text shapes again.
213  /// Bytes with no face are logged and ignored.
214  pub(crate) fn add(&mut self, bytes: &'static [u8]) {
215    // fontdb keeps a font's bytes behind an `Arc`, whatever the thread.
216    let source = Source::Binary(Arc::new(bytes));
217    // Read on its own first, for the families, styles and weights it has.
218    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    // A face loaded from a file that a bundled one replaces, of the same
244    // family, style and weight, gives way: cosmic-text takes the first face
245    // of a name, and the bundled ones fill their places.
246    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      // Its file stays read, so it isn't read again; asked for, it gives
271      // its family's name, which now finds the bundled face.
272      self.loaded.entry(face).or_insert(family);
273    }
274    // fontdb reads the faces in the same order the probe did.
275    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    // A character a removed face drew is looked up again if it is missing.
283    self.fallback_tried.clear();
284    FONTS_ADDED.set(FONTS_ADDED.get() + 1);
285  }
286
287  /// Shapes `content` as a `Text` with `font` shapes it, every line shown.
288  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  /// Loads fontconfig's best font for each character in `missing` that
328  /// no loaded font has, preferring `font`'s family. Returns whether the
329  /// database gained a face, so the text should be shaped again.
330  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  /// Reads a font file into the database once, and returns the family name
351  /// of its face `index`.
352  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
382/// The weights a face draws, lowest and highest: its weight axis if it is a
383/// variable font, else its one weight.
384fn 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    // Weights are 1 to 1000, so the conversions can't overflow.
392    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
404/// Asks fontconfig for the font file and face index that best match
405/// `font`'s family, weight and slant, and that have `covering` if given.
406fn 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
432/// The face number fontdb uses for a fontconfig face index. fontconfig puts
433/// a variable font's named instance, such as Bold, in the upper 16 bits;
434/// fontdb numbers only the faces in the file, and cosmic-text sets the
435/// weight axis itself.
436pub(crate) fn face_number(index: i32) -> u32 {
437  // The mask leaves 0 to 65535, so the conversion can't fail.
438  u32::try_from(index & 0xFFFF).unwrap_or(0)
439}
440
441/// Converts a CSS weight (100 to 1000) to fontconfig's scale, which puts
442/// regular at 80 and bold at 200. The points are fontconfig's own
443/// OpenType table; weights between them are interpolated.
444pub(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/// What a text takes from its own style and its ancestors': the font,
472/// which lays it out, and how its lines sit.
473#[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  /// This inherited style with what `style` sets laid over it.
482  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
501/// The font a span is shaped in: the text's, bold or italic if it says.
502fn 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
510/// What cosmic-text shapes `font` with, in `family` if one was found.
511fn 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  // cosmic-text counts letter spacing in ems. Taking back at most half
520  // an em keeps glyphs within the em the ink box allows left of the text.
521  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
534/// The font size, falling back to the default for a size cosmic-text can't
535/// use, and the line height in whole pixels, at least 1: 1.2 times the
536/// size unless the style sets a usable multiple.
537fn 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
554/// The text of one [`Text`](crate::Text) widget, shaped and laid out by
555/// cosmic-text. Layout measures with this buffer and the renderer draws from
556/// it, so the measured and drawn sizes are the same.
557pub(crate) struct TextNode {
558  /// The text shown; a rich text's spans, joined.
559  pub(crate) content: String,
560  /// A rich text's spans. Each glyph's metadata is its span's index plus
561  /// one, or 0 for plain text. cosmic-text shapes the ellipsis with the
562  /// first span's attributes, metadata included, so a glyph counts as a
563  /// span's only through [`glyph_span`](Self::glyph_span).
564  pub(crate) spans: Vec<Span>,
565  /// Where each span starts in `content`, in bytes.
566  span_starts: Vec<usize>,
567  /// Where each of the buffer's lines starts in `content`, in bytes.
568  line_starts: Vec<usize>,
569  pub(crate) elide: Elide,
570  /// At least 1.
571  pub(crate) max_lines: u32,
572  /// More than one line wraps at words; off, each line is as long as it
573  /// is. A text area's setting.
574  pub(crate) wrap: bool,
575  pub(crate) buffer: Buffer,
576  /// The style the buffer was shaped with; `None` until the first layout.
577  style: Option<TextStyle>,
578  /// [`fonts_added`] when the buffer was shaped.
579  fonts_added: u64,
580  /// The content, `elide` or `max_lines` changed since the buffer was
581  /// shaped.
582  stale: bool,
583  /// The top-left corner of the first line, set by layout.
584  pub(crate) origin: Point,
585  /// Takes the pointer and selects, as `Text::selectable` says.
586  pub(crate) selectable: bool,
587  /// Where a selection ends and starts, in bytes of `content`, while the
588  /// text is selectable.
589  pub(crate) cursor: usize,
590  pub(crate) anchor: Option<usize>,
591  /// What a click on a link span runs, from `Text::on_link`.
592  pub(crate) on_link: Option<LinkHandler>,
593  /// The link span the pointer is over, and the one the keyboard focus
594  /// is on while the window has the keyboard. Both draw lit.
595  pub(crate) hovered_link: Option<usize>,
596  pub(crate) focused_link: Option<usize>,
597  /// The color a lit link is drawn in, from `Text::link_hover_color`.
598  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        // Four spaces, as most editors; cosmic-text's default is eight.
614        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  // Each setter returns whether the value changed, which needs a layout.
632
633  pub(crate) fn set_content(&mut self, content: String) -> bool {
634    self.set(|text| &mut text.content, content)
635  }
636
637  /// Sets a rich text's spans. Only a change of the text they join drops
638  /// the selection; a change of style alone keeps it.
639  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  /// Drops the selection and puts the caret at the start if `changed`,
655  /// since the old one's bytes may not be in the new text; returns it.
656  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  /// Whether the text's width depends on the space it gets: it wraps or
687  /// is elided. Plain one-line text is always as wide as it is.
688  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  /// Whether the style the text was shaped with aligns it.
697  pub(crate) fn aligned(&self) -> bool {
698    self.style.is_some_and(|style| style.align.is_some())
699  }
700
701  /// Shapes the text again if its content, settings or style changed,
702  /// loading fallback fonts for characters the font lacks, or if a font
703  /// was added since. Returns whether it did, so layout must measure it
704  /// again.
705  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    // The text's own font, then each span's.
711    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    // Words wrap; one too long for a line breaks inside it.
717    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  /// Shapes the text with `fonts` and `families`: the text's own first,
756  /// then each span's.
757  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  /// Characters that need a fallback font, by the font they were asked
795  /// in: those that came out as the missing-glyph box, and those drawn
796  /// from a face outside that font's family. The second kind may have
797  /// come from a fallback loaded for another weight or family, so
798  /// fontconfig is asked again for this one. Spans differ only in weight
799  /// and slant, so there are at most a few fonts, however many spans.
800  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  /// The size taffy asks for: as wide as the text, or as `available`
839  /// allows for text that wraps or ends in an ellipsis, and one line
840  /// height per line shown. Sizes are rounded up to whole pixels so that
841  /// rounding the layout never cuts the text short.
842  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  /// Lays the text out in its final `content` box and centers it
866  /// vertically there. Text with an alignment takes the box's width, so
867  /// its lines sit in it.
868  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  /// [`finish`](Self::finish), laying the lines out across `width`, or
874  /// each as long as it is.
875  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  /// The area the glyphs may cover: the lines' box, which can stick out
883  /// of a widget too small for it, grown by an em left and right and half
884  /// an em above and below, plus half of what a line height under the
885  /// default took. Ink reaches past the line box: stacked accents rise
886  /// above it, and a combining mark at the start hangs left of the text
887  /// by nearly the width of the base it lacks. Aligned lines sit across
888  /// the width the text was laid out in.
889  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  /// The index of the span `glyph`, on the buffer's line `line`, is part
903  /// of: the one its metadata names, if all its bytes are in that span.
904  /// The ellipsis holds no bytes, and a ligature across two spans isn't
905  /// either's, so both take the text's own style.
906  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  /// The index of the link span whose glyph box holds `point`, in the
916  /// coordinates `origin` is in, if the text has an `on_link` that hasn't
917  /// panicked. A panicked one leaves its links plain text, as a drop
918  /// target whose `on_drop` panicked takes nothing more.
919  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  /// Whether the text has an `on_link` that hasn't panicked, so its
937  /// links are more than plain text.
938  fn links_on(&self) -> bool {
939    self
940      .on_link
941      .as_ref()
942      .is_some_and(|handler| !handler.disabled())
943  }
944
945  /// Whether link span `index` draws lit: still a link, under the
946  /// pointer or holding the focus.
947  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  /// The link spans Tab stops on, in text order: each with a glyph
957  /// shown, while the text has an `on_link` that hasn't panicked.
958  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  /// Where link span `index` may paint, a box for each line it is on, in
977  /// the coordinates `origin` is in: its glyphs' boxes grown for ink as
978  /// [`ink_box`](Self::ink_box) grows the lines.
979  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  /// Where an empty line sits across the width the text was laid out
1003  /// in, from 0 at the left to 1 at the right, as its alignment and
1004  /// direction (`rtl`) put a line that has glyphs. cosmic-text places
1005  /// every empty line at 0.
1006  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  /// The width the text was laid out in: its box's, or its widest
1016  /// line's.
1017  pub(crate) fn layout_width(&self) -> f32 {
1018    self.buffer.size().0.unwrap_or_else(|| self.width())
1019  }
1020
1021  /// The lines shown, at most `max_lines`. Everything that reads the
1022  /// lines goes through here, so drawing, hit testing, selection and
1023  /// links agree.
1024  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        // Without blanks dropped, the left edge stays where it is.
1031        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/// A line of text as shown: cosmic-text's layout run, less the blank
1046/// that cosmic-text 0.19 starts an elided line with when the line before
1047/// it wrapped at a space.
1048#[derive(Clone, Debug)]
1049pub struct TextRun<'a> {
1050  /// The index of the buffer line it is part of.
1051  pub line_i: usize,
1052  /// That buffer line's text, which glyphs index into.
1053  pub text: &'a str,
1054  /// Whether the paragraph runs right to left.
1055  pub rtl: bool,
1056  /// The glyphs to draw, left to right, from the text's origin.
1057  pub glyphs: Cow<'a, [LayoutGlyph]>,
1058  /// From the text's top to the baseline.
1059  pub line_y: f32,
1060  /// From the text's top to the line's top.
1061  pub line_top: f32,
1062  /// The line's height.
1063  pub line_height: f32,
1064  /// The line's width.
1065  pub line_w: f32,
1066  /// How far left the glyphs were moved, and the first byte shown.
1067  pub(crate) shift: f32,
1068  pub(crate) first: usize,
1069}
1070
1071impl<'a> TextRun<'a> {
1072  /// `run` with the blanks dropped that open an elided left-to-right line
1073  /// cut out of a longer one, the glyphs after them moved left by
1074  /// `moved` times what they took: 1 for a line placed from the left, a
1075  /// half for a centered one and 0 for one placed from the right.
1076  ///
1077  /// shortcut: works around cosmic-text 0.19's word wrap, which starts
1078  /// the elided line at the blank before the word that wrapped; drop it
1079  /// once an upgrade fixes that.
1080  fn shown(run: LayoutRun<'a>, moved: f32) -> TextRun<'a> {
1081    // The ellipsis holds no bytes; a line that starts inside its buffer
1082    // line was wrapped.
1083    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  /// The line as a cosmic-text layout run, for its selection and caret
1123  /// helpers. Decoration spans aren't drawn, so it has none.
1124  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}