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, 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/// The fonts every window measures and draws text with.
38///
39/// There is one per process, and cloning it gives another handle to the
40/// same fonts. The platform passes it to
41/// [`Window::layout`](crate::Window::layout), the renderer rasterizes
42/// glyphs with its [`font_system`](Self::font_system), and the root [`Cx`]
43/// gets it as a service for [`Cx::measure_text`] and [`Cx::add_font`].
44///
45/// [`Cx`]: crate::Cx
46/// [`Cx::measure_text`]: crate::Cx::measure_text
47/// [`Cx::add_font`]: crate::Cx::add_font
48#[derive(Clone, Default)]
49pub struct TextSystem(Rc<RefCell<Fonts>>);
50
51impl TextSystem {
52  /// An empty font database. Nothing is loaded until text is laid out.
53  pub fn new() -> TextSystem {
54    TextSystem::default()
55  }
56
57  /// cosmic-text's font system, for rasterizing glyphs. Release it before
58  /// laying a window out.
59  pub fn font_system(&self) -> RefMut<'_, FontSystem> {
60    RefMut::map(self.fonts(), |fonts| &mut fonts.fonts)
61  }
62
63  /// The fonts, borrowed.
64  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  /// How many fonts were added. Text shaped before the last one shapes
74  /// again, and windows laid out before it lay out again.
75  static FONTS_ADDED: Cell<u64> = const { Cell::new(0) };
76}
77
78pub(crate) fn fonts_added() -> u64 {
79  FONTS_ADDED.get()
80}
81
82/// The size of text shaped with one font, from
83/// [`Cx::measure_text`](crate::Cx::measure_text), in logical pixels.
84#[derive(Clone, Copy, Debug, Default, PartialEq)]
85pub struct TextMetrics {
86  /// The advance of the widest line.
87  pub width: f32,
88  /// The line boxes: one line height per line.
89  pub height: f32,
90  /// How far the font rises above the baseline at this size.
91  pub ascent: f32,
92  /// How far the font reaches below the baseline at this size, positive.
93  pub descent: f32,
94  /// The height of one line, as a `Text` with this font has.
95  pub line_height: f32,
96  /// The tight box around the ink the glyphs draw, from the text's
97  /// top-left, as Qt's `tightBoundingRect`: `x` is negative when a glyph
98  /// hangs left of where the text starts, and the box can be wider than
99  /// [`width`](Self::width) when ink reaches past the last advance, as a
100  /// Nerd Font icon in a monospace cell does. Read from the unhinted
101  /// outlines, unrounded; a color bitmap glyph, such as an emoji, gives
102  /// its pixels' box. Empty text, or only blanks, gives an empty rect at
103  /// 0, 0.
104  pub ink: Rect,
105}
106
107/// How many glyphs' ink boxes [`Fonts`] keeps, at about 50 bytes each;
108/// past it the cache starts again.
109pub(crate) const INK_GLYPHS: usize = 4096;
110
111/// Calls `add` with every point where the outline `commands` reach
112/// furthest along either axis.
113fn 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
127/// Calls `add` with the end of the line, quadratic or cubic Bézier
128/// through `points`, and with each point between its ends where it turns
129/// back on an axis. A curve's control points may lie outside it, so they
130/// aren't the box. Returns the end.
131pub(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
160/// Where between 0 and 1 a quadratic or cubic Bézier with these values
161/// on one axis has a zero derivative.
162fn turns(values: &[f32]) -> [Option<f32>; 2] {
163  let inside = |t: f32| (t > 0.0 && t < 1.0).then_some(t);
164  // The derivative, over 2 or 3, is q t² + r t + s.
165  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
184/// What a [`TextSystem`] holds.
185pub(crate) struct Fonts {
186  fonts: FontSystem,
187  fontconfig: Lookup,
188  /// The family name each requested family, weight and slant resolved
189  /// to, as the font database knows it. `None` if nothing was found.
190  families: HashMap<(&'static str, u16, bool), Option<Rc<str>>>,
191  /// The family name of each face asked for, by file and face number.
192  pub(crate) loaded: HashMap<(PathBuf, u32), Option<Rc<str>>>,
193  /// Files read into the database. Reading one loads all its faces.
194  files: HashSet<PathBuf>,
195  /// Characters a fallback font was already looked up for, by the family,
196  /// weight and slant asked for: fontconfig's answer depends on all three.
197  fallback_tried: HashSet<(char, &'static str, u16, bool)>,
198  /// The weights each bundled face draws, lowest and highest: one, or a
199  /// variable font's whole weight axis.
200  bundled: HashMap<ID, (u16, u16)>,
201  /// Each glyph's ink box from its origin, by its unhinted cache key at
202  /// a whole pixel, or `None` if it draws nothing. At most
203  /// [`INK_GLYPHS`]; a face ID can be reused once a font is added.
204  pub(crate) ink: HashMap<CacheKey, Option<Rect>>,
205  /// How many outlines and bitmaps ink boxes were worked out from.
206  #[cfg(test)]
207  pub(crate) glyphs_built: (usize, usize),
208}
209
210/// fontconfig, started on first use because that costs about 15 ms.
211enum Lookup {
212  NotStarted,
213  Ready(Fontconfig),
214  Failed,
215}
216
217impl Fonts {
218  /// An empty font database.
219  pub(crate) fn new() -> Fonts {
220    // cosmic-text needs a locale. Reading the system's would take another
221    // crate, and it only affects which script-specific fallbacks it tries.
222    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  /// cosmic-text's font system.
238  pub(crate) fn font_system(&mut self) -> &mut FontSystem {
239    &mut self.fonts
240  }
241
242  /// Whether fontconfig was started.
243  #[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  /// The name to ask cosmic-text for to get `font`'s family, weight and
265  /// slant: a bundled family of that name, or else the file fontconfig
266  /// matches, loaded the first time. `None`, logged once, if no font
267  /// could be loaded.
268  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  /// The database's name for `font`'s family if a bundled face of it
293  /// draws its weight and slant: italic or oblique for italic text,
294  /// upright for the rest.
295  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  /// Reads every face in `bytes` into the database, without copying them.
309  /// Families they provide are resolved again, and all text shapes again.
310  /// Bytes with no face are logged and ignored.
311  pub(crate) fn add(&mut self, bytes: &'static [u8]) {
312    // fontdb keeps a font's bytes behind an `Arc`, whatever the thread.
313    let source = Source::Binary(Arc::new(bytes));
314    // Read on its own first, for the families, styles and weights it has.
315    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    // A face loaded from a file that a bundled one replaces, of the same
341    // family, style and weight, gives way: cosmic-text takes the first face
342    // of a name, and the bundled ones fill their places.
343    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      // Its file stays read, so it isn't read again; asked for, it gives
368      // its family's name, which now finds the bundled face.
369      self.loaded.entry(face).or_insert(family);
370    }
371    // fontdb reads the faces in the same order the probe did.
372    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    // A character a removed face drew is looked up again if it is missing.
380    self.fallback_tried.clear();
381    self.ink.clear();
382    FONTS_ADDED.set(FONTS_ADDED.get() + 1);
383  }
384
385  /// Shapes `content` as a `Text` with `font` shapes it, every line shown.
386  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  /// The tight box around the ink of the glyphs `node` shows, from its
427  /// top-left, or an empty rect at 0, 0 if they draw none.
428  fn ink(&mut self, node: &TextNode) -> Rect {
429    // Made only when a glyph isn't cached yet.
430    let mut scaler = None;
431    // Left, top, right and bottom.
432    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  /// The ink box of the glyph `key` names, from its origin, y down: its
479  /// outline's, or a bitmap's pixels' if it has no outline. `None` for a
480  /// blank.
481  fn glyph_ink(&mut self, scaler: &mut SwashCache, key: CacheKey) -> Option<Rect> {
482    // An empty outline may still draw, as a COLR glyph's layers do, so it
483    // goes to the bitmap path too.
484    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    // Outlines rise up from the baseline.
506    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  /// Loads fontconfig's best font for each character in `missing` that
513  /// no loaded font has, preferring `font`'s family. Returns whether the
514  /// database gained a face, so the text should be shaped again.
515  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  /// Reads a font file into the database once, and returns the family name
536  /// of its face `index`.
537  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
567/// The weights a face draws, lowest and highest: its weight axis if it is a
568/// variable font, else its one weight.
569fn 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    // Weights are 1 to 1000, so the conversions can't overflow.
577    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
589/// Asks fontconfig for the font file and face index that best match
590/// `font`'s family, weight and slant, and that have `covering` if given.
591fn 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
617/// The face number fontdb uses for a fontconfig face index. fontconfig puts
618/// a variable font's named instance, such as Bold, in the upper 16 bits;
619/// fontdb numbers only the faces in the file, and cosmic-text sets the
620/// weight axis itself.
621pub(crate) fn face_number(index: i32) -> u32 {
622  // The mask leaves 0 to 65535, so the conversion can't fail.
623  u32::try_from(index & 0xFFFF).unwrap_or(0)
624}
625
626/// Converts a CSS weight (100 to 1000) to fontconfig's scale, which puts
627/// regular at 80 and bold at 200. The points are fontconfig's own
628/// OpenType table; weights between them are interpolated.
629pub(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/// What a text takes from its own style and its ancestors': the font,
657/// which lays it out, and how its lines sit.
658#[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  /// This inherited style with what `style` sets laid over it.
667  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
686/// The font a span is shaped in: the text's, bold or italic if it says.
687fn 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
695/// What cosmic-text shapes `font` with, in `family` if one was found.
696fn 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  // cosmic-text counts letter spacing in ems. Taking back at most half
705  // an em keeps glyphs within the em the ink box allows left of the text.
706  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
719/// The font size, falling back to the default for a size cosmic-text can't
720/// use, and the line height in whole pixels, at least 1: 1.2 times the
721/// size unless the style sets a usable multiple.
722fn 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
739/// The text of one [`Text`](crate::Text) widget, shaped and laid out by
740/// cosmic-text. Layout measures with this buffer and the renderer draws from
741/// it, so the measured and drawn sizes are the same.
742pub(crate) struct TextNode {
743  /// The text shown; a rich text's spans, joined.
744  pub(crate) content: String,
745  /// A rich text's spans. Each glyph's metadata is its span's index plus
746  /// one, or 0 for plain text. cosmic-text shapes the ellipsis with the
747  /// first span's attributes, metadata included, so a glyph counts as a
748  /// span's only through [`glyph_span`](Self::glyph_span).
749  pub(crate) spans: Vec<Span>,
750  /// Where each span starts in `content`, in bytes.
751  span_starts: Vec<usize>,
752  /// Where each of the buffer's lines starts in `content`, in bytes.
753  line_starts: Vec<usize>,
754  pub(crate) elide: Elide,
755  /// At least 1.
756  pub(crate) max_lines: u32,
757  /// More than one line wraps at words; off, each line is as long as it
758  /// is. A text area's setting.
759  pub(crate) wrap: bool,
760  pub(crate) buffer: Buffer,
761  /// The style the buffer was shaped with; `None` until the first layout.
762  style: Option<TextStyle>,
763  /// [`fonts_added`] when the buffer was shaped.
764  fonts_added: u64,
765  /// The content, `elide` or `max_lines` changed since the buffer was
766  /// shaped.
767  stale: bool,
768  /// The top-left corner of the first line, set by layout.
769  pub(crate) origin: Point,
770  /// Takes the pointer and selects, as `Text::selectable` says.
771  pub(crate) selectable: bool,
772  /// Where a selection ends and starts, in bytes of `content`, while the
773  /// text is selectable.
774  pub(crate) cursor: usize,
775  pub(crate) anchor: Option<usize>,
776  /// What a click on a link span runs, from `Text::on_link`.
777  pub(crate) on_link: Option<LinkHandler>,
778  /// The link span the pointer is over, and the one the keyboard focus
779  /// is on while the window has the keyboard. Both draw lit.
780  pub(crate) hovered_link: Option<usize>,
781  pub(crate) focused_link: Option<usize>,
782  /// The color a lit link is drawn in, from `Text::link_hover_color`.
783  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        // Four spaces, as most editors; cosmic-text's default is eight.
799        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  // Each setter returns whether the value changed, which needs a layout.
817
818  pub(crate) fn set_content(&mut self, content: String) -> bool {
819    self.set(|text| &mut text.content, content)
820  }
821
822  /// Sets a rich text's spans. Only a change of the text they join drops
823  /// the selection; a change of style alone keeps it.
824  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  /// Drops the selection and puts the caret at the start if `changed`,
840  /// since the old one's bytes may not be in the new text; returns it.
841  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  /// Whether the text's width depends on the space it gets: it wraps or
872  /// is elided. Plain one-line text is always as wide as it is.
873  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  /// Whether the style the text was shaped with aligns it.
882  pub(crate) fn aligned(&self) -> bool {
883    self.style.is_some_and(|style| style.align.is_some())
884  }
885
886  /// Shapes the text again if its content, settings or style changed,
887  /// loading fallback fonts for characters the font lacks, or if a font
888  /// was added since. Returns whether it did, so layout must measure it
889  /// again.
890  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    // The text's own font, then each span's.
896    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    // Words wrap; one too long for a line breaks inside it.
902    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  /// Shapes the text with `fonts` and `families`: the text's own first,
941  /// then each span's.
942  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  /// Characters that need a fallback font, by the font they were asked
980  /// in: those that came out as the missing-glyph box, and those drawn
981  /// from a face outside that font's family. The second kind may have
982  /// come from a fallback loaded for another weight or family, so
983  /// fontconfig is asked again for this one. Spans differ only in weight
984  /// and slant, so there are at most a few fonts, however many spans.
985  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  /// The size taffy asks for: as wide as the text, or as `available`
1024  /// allows for text that wraps or ends in an ellipsis, and one line
1025  /// height per line shown. Sizes are rounded up to whole pixels so that
1026  /// rounding the layout never cuts the text short.
1027  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  /// Lays the text out in its final `content` box and centers it
1051  /// vertically there. Text with an alignment takes the box's width, so
1052  /// its lines sit in it.
1053  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  /// [`finish`](Self::finish), laying the lines out across `width`, or
1059  /// each as long as it is.
1060  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  /// The area the glyphs may cover: the lines' box, which can stick out
1068  /// of a widget too small for it, grown by an em left and right and half
1069  /// an em above and below, plus half of what a line height under the
1070  /// default took. Ink reaches past the line box: stacked accents rise
1071  /// above it, and a combining mark at the start hangs left of the text
1072  /// by nearly the width of the base it lacks. Aligned lines sit across
1073  /// the width the text was laid out in.
1074  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  /// The index of the span `glyph`, on the buffer's line `line`, is part
1088  /// of: the one its metadata names, if all its bytes are in that span.
1089  /// The ellipsis holds no bytes, and a ligature across two spans isn't
1090  /// either's, so both take the text's own style.
1091  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  /// The index of the link span whose glyph box holds `point`, in the
1101  /// coordinates `origin` is in, if the text has an `on_link` that hasn't
1102  /// panicked. A panicked one leaves its links plain text, as a drop
1103  /// target whose `on_drop` panicked takes nothing more.
1104  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  /// Whether the text has an `on_link` that hasn't panicked, so its
1122  /// links are more than plain text.
1123  fn links_on(&self) -> bool {
1124    self
1125      .on_link
1126      .as_ref()
1127      .is_some_and(|handler| !handler.disabled())
1128  }
1129
1130  /// Whether link span `index` draws lit: still a link, under the
1131  /// pointer or holding the focus.
1132  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  /// The link spans Tab stops on, in text order: each with a glyph
1142  /// shown, while the text has an `on_link` that hasn't panicked.
1143  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  /// Where link span `index` may paint, a box for each line it is on, in
1162  /// the coordinates `origin` is in: its glyphs' boxes grown for ink as
1163  /// [`ink_box`](Self::ink_box) grows the lines.
1164  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  /// Where an empty line sits across the width the text was laid out
1188  /// in, from 0 at the left to 1 at the right, as its alignment and
1189  /// direction (`rtl`) put a line that has glyphs. cosmic-text places
1190  /// every empty line at 0.
1191  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  /// The width the text was laid out in: its box's, or its widest
1201  /// line's.
1202  pub(crate) fn layout_width(&self) -> f32 {
1203    self.buffer.size().0.unwrap_or_else(|| self.width())
1204  }
1205
1206  /// The lines shown, at most `max_lines`. Everything that reads the
1207  /// lines goes through here, so drawing, hit testing, selection and
1208  /// links agree.
1209  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        // Without blanks dropped, the left edge stays where it is.
1216        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/// A line of text as shown: cosmic-text's layout run, less the blank
1231/// that cosmic-text 0.19 starts an elided line with when the line before
1232/// it wrapped at a space.
1233#[derive(Clone, Debug)]
1234pub struct TextRun<'a> {
1235  /// The index of the buffer line it is part of.
1236  pub line_i: usize,
1237  /// That buffer line's text, which glyphs index into.
1238  pub text: &'a str,
1239  /// Whether the paragraph runs right to left.
1240  pub rtl: bool,
1241  /// The glyphs to draw, left to right, from the text's origin.
1242  pub glyphs: Cow<'a, [LayoutGlyph]>,
1243  /// From the text's top to the baseline.
1244  pub line_y: f32,
1245  /// From the text's top to the line's top.
1246  pub line_top: f32,
1247  /// The line's height.
1248  pub line_height: f32,
1249  /// The line's width.
1250  pub line_w: f32,
1251  /// How far left the glyphs were moved, and the first byte shown.
1252  pub(crate) shift: f32,
1253  pub(crate) first: usize,
1254}
1255
1256impl<'a> TextRun<'a> {
1257  /// `run` with the blanks dropped that open an elided left-to-right line
1258  /// cut out of a longer one, the glyphs after them moved left by
1259  /// `moved` times what they took: 1 for a line placed from the left, a
1260  /// half for a centered one and 0 for one placed from the right.
1261  ///
1262  /// shortcut: works around cosmic-text 0.19's word wrap, which starts
1263  /// the elided line at the blank before the word that wrapped; drop it
1264  /// once an upgrade fixes that.
1265  fn shown(run: LayoutRun<'a>, moved: f32) -> TextRun<'a> {
1266    // The ellipsis holds no bytes; a line that starts inside its buffer
1267    // line was wrapped.
1268    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  /// The line as a cosmic-text layout run, for its selection and caret
1308  /// helpers. Decoration spans aren't drawn, so it has none.
1309  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}