use std::borrow::Cow;
use std::cell::{Cell, RefCell, RefMut};
use std::collections::{HashMap, HashSet};
use std::ffi::CString;
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;
use cosmic_text::fontdb::{self, Database, FaceInfo, ID, Query, Source};
use cosmic_text::{
Align, Attrs, Buffer, Ellipsize, EllipsizeHeightLimit, Family, FeatureTag, FontFeatures,
FontSystem, LayoutGlyph, LayoutRun, Metrics, Shaping, Weight, Wrap,
};
use fontconfig::{CharSet, FC_FAMILY, FC_SLANT, FC_SLANT_ITALIC, FC_WEIGHT, Fontconfig, Pattern};
use taffy::AvailableSpace;
use crate::geometry::{Point, Rect};
use crate::input::LinkHandler;
use crate::rich::Span;
use crate::style::{Color, Font, Style, TextAlign};
use crate::widgets::Elide;
#[derive(Clone, Default)]
pub struct TextSystem(Rc<RefCell<Fonts>>);
impl TextSystem {
pub fn new() -> TextSystem {
TextSystem::default()
}
pub fn font_system(&self) -> RefMut<'_, FontSystem> {
RefMut::map(self.fonts(), |fonts| &mut fonts.fonts)
}
pub(crate) fn fonts(&self) -> RefMut<'_, Fonts> {
self
.0
.try_borrow_mut()
.expect("nothing that holds the fonts runs user code, which may measure text")
}
}
thread_local! {
static FONTS_ADDED: Cell<u64> = const { Cell::new(0) };
}
pub(crate) fn fonts_added() -> u64 {
FONTS_ADDED.get()
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct TextMetrics {
pub width: f32,
pub height: f32,
pub ascent: f32,
pub descent: f32,
pub line_height: f32,
}
pub(crate) struct Fonts {
fonts: FontSystem,
fontconfig: Lookup,
families: HashMap<(&'static str, u16, bool), Option<Rc<str>>>,
pub(crate) loaded: HashMap<(PathBuf, u32), Option<Rc<str>>>,
files: HashSet<PathBuf>,
fallback_tried: HashSet<(char, &'static str, u16, bool)>,
bundled: HashMap<ID, (u16, u16)>,
}
enum Lookup {
NotStarted,
Ready(Fontconfig),
Failed,
}
impl Fonts {
pub(crate) fn new() -> Fonts {
let fonts = FontSystem::new_with_locale_and_db("en-US".to_owned(), Database::new());
Fonts {
fonts,
fontconfig: Lookup::NotStarted,
families: HashMap::new(),
loaded: HashMap::new(),
files: HashSet::new(),
fallback_tried: HashSet::new(),
bundled: HashMap::new(),
}
}
pub(crate) fn font_system(&mut self) -> &mut FontSystem {
&mut self.fonts
}
#[cfg(test)]
pub(crate) fn fontconfig_started(&self) -> bool {
!matches!(self.fontconfig, Lookup::NotStarted)
}
fn fontconfig(&mut self) -> Option<&Fontconfig> {
if let Lookup::NotStarted = self.fontconfig {
self.fontconfig = match Fontconfig::new() {
Some(fontconfig) => Lookup::Ready(fontconfig),
None => {
tracing::error!("fontconfig failed to start, so no fonts can be loaded");
Lookup::Failed
}
};
}
match &self.fontconfig {
Lookup::Ready(fontconfig) => Some(fontconfig),
_ => None,
}
}
pub(crate) fn family(&mut self, font: &Font) -> Option<Rc<str>> {
let key = (font.family, font.weight, font.italic);
if let Some(name) = self.families.get(&key) {
return name.clone();
}
if let Some(name) = self.bundled(font) {
self.families.insert(key, Some(Rc::clone(&name)));
return Some(name);
}
let matched = self
.fontconfig()
.and_then(|fontconfig| match_font(fontconfig, font, None));
let name = matched.and_then(|file| self.load(file));
match &name {
Some(name) => tracing::debug!(requested = font.family, family = %name, "font loaded"),
None => tracing::warn!(
requested = font.family,
"no font found for this family, so its text shows nothing"
),
}
self.families.insert(key, name.clone());
name
}
fn bundled(&self, font: &Font) -> Option<Rc<str>> {
let db = self.fonts.db();
self
.bundled
.iter()
.filter(|(_, (low, high))| (*low..=*high).contains(&font.weight))
.filter_map(|(&id, _)| db.face(id))
.filter(|face| (face.style != fontdb::Style::Normal) == font.italic)
.flat_map(|face| &face.families)
.find(|(name, _language)| name.eq_ignore_ascii_case(font.family))
.map(|(name, _language)| Rc::from(name.as_str()))
}
pub(crate) fn add(&mut self, bytes: &'static [u8]) {
let source = Source::Binary(Arc::new(bytes));
let mut probe = Database::new();
probe.load_font_source(source.clone());
let faces: Vec<_> = probe
.faces()
.map(|face| (face, weights(&probe, face)))
.collect();
if faces.is_empty() {
tracing::warn!(
bytes = bytes.len(),
"a bundled font has no face that could be read, so it is ignored"
);
return;
}
let names: Vec<&str> = faces
.iter()
.flat_map(|(face, _)| face.families.iter().map(|(name, _)| name.as_str()))
.collect();
tracing::debug!(?names, "font added");
let same_family = |a: &FaceInfo, b: &FaceInfo| {
a.families.iter().any(|(name, _)| {
b.families
.iter()
.any(|(other, _)| name.eq_ignore_ascii_case(other))
})
};
let replaced: Vec<_> = self
.fonts
.db()
.faces()
.filter(|old| {
faces.iter().any(|(new, (low, high))| {
new.style == old.style && (*low..=*high).contains(&old.weight.0) && same_family(new, old)
})
})
.filter_map(|old| {
let family = old
.families
.first()
.map(|(name, _)| Rc::from(name.as_str()));
Some((
old.id,
(source_path(&old.source)?.clone(), old.index),
family,
))
})
.collect();
let db = self.fonts.db_mut();
for (id, face, family) in replaced {
db.remove_face(id);
self.loaded.entry(face).or_insert(family);
}
let ids = db.load_font_source(source);
for (id, (_, weights)) in ids.into_iter().zip(&faces) {
self.bundled.insert(id, *weights);
}
self
.families
.retain(|(family, _, _), _| !names.iter().any(|name| name.eq_ignore_ascii_case(family)));
self.fallback_tried.clear();
FONTS_ADDED.set(FONTS_ADDED.get() + 1);
}
pub(crate) fn measure(&mut self, content: &str, font: Font) -> TextMetrics {
let mut node = TextNode::new();
node.set_content(content.to_owned());
node.set_max_lines(u32::MAX);
node.prepare(font, self);
let Metrics {
font_size,
line_height,
} = node.buffer.metrics();
let weight = Weight(font.weight);
let face = self.family(&font).and_then(|name| {
self.fonts.db().query(&Query {
families: &[Family::Name(&name)],
weight,
style: if font.italic {
fontdb::Style::Italic
} else {
fontdb::Style::Normal
},
..Query::default()
})
});
let (ascent, descent) =
face
.and_then(|id| self.fonts.get_font(id, weight))
.map_or((0.0, 0.0), |face| {
let metrics = face.metrics();
let scale = font_size / f32::from(metrics.units_per_em);
(metrics.ascent * scale, -metrics.descent * scale)
});
TextMetrics {
width: node.width(),
height: node.height(),
ascent,
descent,
line_height,
}
}
fn load_fallbacks(&mut self, font: &Font, missing: &[char]) -> bool {
let faces = self.fonts.db().len();
for &ch in missing {
if !self
.fallback_tried
.insert((ch, font.family, font.weight, font.italic))
{
continue;
}
let Some(file) = self
.fontconfig()
.and_then(|fontconfig| match_font(fontconfig, font, Some(ch)))
else {
continue;
};
self.load(file);
}
self.fonts.db().len() > faces
}
pub(crate) fn load(&mut self, (path, index): (PathBuf, u32)) -> Option<Rc<str>> {
let key = (path, index);
if let Some(name) = self.loaded.get(&key) {
return name.clone();
}
let (path, index) = &key;
if !self.files.contains(path) {
self.files.insert(path.clone());
if let Err(error) = self.fonts.db_mut().load_font_file(path) {
tracing::warn!(path = %path.display(), %error, "couldn't read a font file");
}
}
let name = self
.fonts
.db()
.faces()
.find(|face| face.index == *index && source_path(&face.source) == Some(path))
.and_then(|face| face.families.first())
.map(|(name, _language)| Rc::from(name.as_str()));
self.loaded.insert(key, name.clone());
name
}
}
impl Default for Fonts {
fn default() -> Self {
Self::new()
}
}
fn weights(db: &Database, face: &FaceInfo) -> (u16, u16) {
let wght = u32::from_be_bytes(*b"wght");
let axis = cosmic_text::Font::new(db, face.id, face.weight).and_then(|font| {
let axis = font
.as_swash()
.variations()
.find(|axis| axis.tag() == wght)?;
Some((axis.min_value() as u16, axis.max_value() as u16))
});
axis.unwrap_or((face.weight.0, face.weight.0))
}
fn source_path(source: &Source) -> Option<&PathBuf> {
match source {
Source::File(path) | Source::SharedFile(path, _) => Some(path),
Source::Binary(_) => None,
}
}
fn match_font(
fontconfig: &Fontconfig,
font: &Font,
covering: Option<char>,
) -> Option<(PathBuf, u32)> {
let mut pattern = Pattern::new(fontconfig).ok()?;
pattern
.add_string(FC_FAMILY, &CString::new(font.family).ok()?)
.ok()?;
pattern
.add_integer(FC_WEIGHT, fc_weight(font.weight))
.ok()?;
if font.italic {
pattern.add_integer(FC_SLANT, FC_SLANT_ITALIC).ok()?;
}
if let Some(ch) = covering {
let mut chars = CharSet::new(fontconfig).ok()?;
chars.add_char(ch).ok()?;
pattern.add_charset(chars).ok()?;
}
let matched = pattern.font_match().ok()?;
let path = PathBuf::from(matched.filename().ok()?);
let index = matched.face_index().ok().map_or(0, face_number);
Some((path, index))
}
pub(crate) fn face_number(index: i32) -> u32 {
u32::try_from(index & 0xFFFF).unwrap_or(0)
}
pub(crate) fn fc_weight(weight: u16) -> i32 {
const POINTS: [(f32, f32); 12] = [
(100.0, 0.0),
(200.0, 40.0),
(300.0, 50.0),
(350.0, 55.0),
(380.0, 75.0),
(400.0, 80.0),
(500.0, 100.0),
(600.0, 180.0),
(700.0, 200.0),
(800.0, 205.0),
(900.0, 210.0),
(1000.0, 215.0),
];
let weight = f32::from(weight).clamp(100.0, 1000.0);
let upper = POINTS
.iter()
.position(|&(css, _)| css >= weight)
.unwrap_or(POINTS.len() - 1)
.max(1);
let (css_low, fc_low) = POINTS[upper - 1];
let (css_high, fc_high) = POINTS[upper];
let fc = fc_low + (weight - css_low) / (css_high - css_low) * (fc_high - fc_low);
fc.round() as i32
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct TextStyle {
pub(crate) font: Font,
pub(crate) align: Option<TextAlign>,
pub(crate) line_height: Option<f32>,
}
impl TextStyle {
pub(crate) fn inherit(self, style: &Style) -> TextStyle {
TextStyle {
font: style.font.unwrap_or(self.font),
align: style.text_align.or(self.align),
line_height: style.line_height.or(self.line_height),
}
}
}
impl From<Font> for TextStyle {
fn from(font: Font) -> TextStyle {
TextStyle {
font,
align: None,
line_height: None,
}
}
}
fn span_font(span: &Span, font: Font) -> Font {
Font {
weight: if span.bold { 700 } else { font.weight },
italic: font.italic || span.italic,
..font
}
}
fn attrs<'a>(font: &Font, family: Option<&'a str>) -> Attrs<'a> {
let mut attrs = Attrs::new().weight(Weight(font.weight));
if let Some(family) = family {
attrs = attrs.family(Family::Name(family));
}
if font.italic {
attrs = attrs.style(cosmic_text::Style::Italic);
}
if font.letter_spacing.is_finite() && font.letter_spacing != 0.0 {
attrs = attrs.letter_spacing((font.letter_spacing / font_size(font)).max(-0.5));
}
if !font.features.is_empty() {
let mut features = FontFeatures::new();
for feature in font.features {
features.set(FeatureTag::new(&feature.tag), feature.value);
}
attrs = attrs.font_features(features);
}
attrs
}
fn metrics(style: &TextStyle) -> Metrics {
let size = font_size(&style.font);
let multiple = style
.line_height
.filter(|multiple| multiple.is_finite() && *multiple > 0.0)
.unwrap_or(1.2);
Metrics::new(size, (size * multiple).round().max(1.0))
}
fn font_size(font: &Font) -> f32 {
if font.size.is_finite() && font.size >= 1.0 {
font.size
} else {
Font::DEFAULT.size
}
}
pub(crate) struct TextNode {
pub(crate) content: String,
pub(crate) spans: Vec<Span>,
span_starts: Vec<usize>,
line_starts: Vec<usize>,
pub(crate) elide: Elide,
pub(crate) max_lines: u32,
pub(crate) wrap: bool,
pub(crate) buffer: Buffer,
style: Option<TextStyle>,
fonts_added: u64,
stale: bool,
pub(crate) origin: Point,
pub(crate) selectable: bool,
pub(crate) cursor: usize,
pub(crate) anchor: Option<usize>,
pub(crate) on_link: Option<LinkHandler>,
pub(crate) hovered_link: Option<usize>,
pub(crate) focused_link: Option<usize>,
pub(crate) link_hover_color: Option<Color>,
}
impl TextNode {
pub(crate) fn new() -> TextNode {
TextNode {
content: String::new(),
spans: Vec::new(),
span_starts: Vec::new(),
line_starts: Vec::new(),
elide: Elide::None,
max_lines: 1,
wrap: true,
buffer: {
let mut buffer = Buffer::new_empty(metrics(&Font::DEFAULT.into()));
buffer.set_tab_width(4);
buffer
},
style: None,
fonts_added: 0,
stale: true,
origin: Point::default(),
selectable: false,
cursor: 0,
anchor: None,
on_link: None,
hovered_link: None,
focused_link: None,
link_hover_color: None,
}
}
pub(crate) fn set_content(&mut self, content: String) -> bool {
self.set(|text| &mut text.content, content)
}
pub(crate) fn set_spans(&mut self, spans: Vec<Span>) -> bool {
let content = spans.iter().map(|span| span.text.as_str()).collect();
self.span_starts = spans
.iter()
.scan(0, |start, span| {
let this = *start;
*start += span.text.len();
Some(this)
})
.collect();
let changed = self.set(|text| &mut text.spans, spans);
let new_text = self.set_content(content);
self.forget_selection_if(new_text) | changed
}
pub(crate) fn forget_selection_if(&mut self, changed: bool) -> bool {
if changed {
self.anchor = None;
self.cursor = 0;
}
changed
}
pub(crate) fn set_elide(&mut self, elide: Elide) -> bool {
self.set(|text| &mut text.elide, elide)
}
pub(crate) fn set_max_lines(&mut self, max_lines: u32) -> bool {
self.set(|text| &mut text.max_lines, max_lines.max(1))
}
pub(crate) fn set_wrap(&mut self, wrap: bool) -> bool {
self.set(|text| &mut text.wrap, wrap)
}
fn set<T: PartialEq>(&mut self, field: impl FnOnce(&mut TextNode) -> &mut T, value: T) -> bool {
let slot = field(self);
if *slot == value {
return false;
}
*slot = value;
self.stale = true;
true
}
fn fits_width(&self) -> bool {
self.elide != Elide::None || self.wraps()
}
pub(crate) fn wraps(&self) -> bool {
self.max_lines > 1 && self.wrap
}
pub(crate) fn aligned(&self) -> bool {
self.style.is_some_and(|style| style.align.is_some())
}
pub(crate) fn prepare(&mut self, style: impl Into<TextStyle>, text: &mut Fonts) -> bool {
let style = style.into();
if !self.stale && self.style == Some(style) && self.fonts_added == fonts_added() {
return false;
}
let fonts: Vec<Font> = std::iter::once(style.font)
.chain(self.spans.iter().map(|span| span_font(span, style.font)))
.collect();
let families: Vec<_> = fonts.iter().map(|font| text.family(font)).collect();
self.buffer.set_metrics(metrics(&style));
self.buffer.set_wrap(if self.wraps() {
Wrap::WordOrGlyph
} else {
Wrap::None
});
let lines = EllipsizeHeightLimit::Lines(self.max_lines as usize);
self.buffer.set_ellipsize(match self.elide {
Elide::None => Ellipsize::None,
Elide::Start => Ellipsize::Start(lines),
Elide::Middle => Ellipsize::Middle(lines),
Elide::End => Ellipsize::End(lines),
});
self.buffer.set_size(None, None);
self.shape(&fonts, &families, &style, text);
let missing = self.fallback_chars(&fonts, &families, text.font_system().db());
let mut gained = false;
for (font, chars) in missing {
gained |= text.load_fallbacks(&font, &chars);
}
if gained {
self.shape(&fonts, &families, &style, text);
}
self.line_starts = self
.buffer
.lines
.iter()
.scan(0, |start, line| {
let this = *start;
*start += line.text().len() + line.ending().as_str().len();
Some(this)
})
.collect();
self.style = Some(style);
self.fonts_added = fonts_added();
self.stale = false;
true
}
fn shape(
&mut self,
fonts: &[Font],
families: &[Option<Rc<str>>],
style: &TextStyle,
text: &mut Fonts,
) {
let own = attrs(&fonts[0], families[0].as_deref());
if self.spans.is_empty() {
self
.buffer
.set_text(&self.content, &own, Shaping::Advanced, None);
} else {
let spans = self.spans.iter().enumerate().map(|(index, span)| {
let font = &fonts[index + 1];
let mut attrs = attrs(font, families[index + 1].as_deref()).metadata(index + 1);
if let Some(color) = span.color {
attrs = attrs.color(cosmic_text::Color::rgba(color.r, color.g, color.b, color.a));
}
(span.text.as_str(), attrs)
});
self
.buffer
.set_rich_text(spans, &own, Shaping::Advanced, None);
}
let align = style.align.and_then(|align| match align {
TextAlign::Start => None,
TextAlign::Center => Some(Align::Center),
TextAlign::End => Some(Align::End),
TextAlign::Justify => Some(Align::Justified),
});
for line in &mut self.buffer.lines {
line.set_align(align);
}
self.buffer.shape_until_scroll(text.font_system(), false);
}
fn fallback_chars(
&self,
fonts: &[Font],
families: &[Option<Rc<str>>],
db: &Database,
) -> Vec<(Font, Vec<char>)> {
let in_family = |glyph: &LayoutGlyph| {
let family = families.get(glyph.metadata).cloned().flatten();
db.face(glyph.font_id).is_some_and(|face| {
face
.families
.iter()
.any(|(name, _)| Some(name.as_str()) == family.as_deref())
})
};
let mut missing: Vec<(Font, Vec<char>)> = Vec::new();
let mut seen = HashSet::new();
for run in self.buffer.layout_runs() {
let fallback = |glyph: &&LayoutGlyph| glyph.glyph_id == 0 || !in_family(glyph);
for glyph in run.glyphs.iter().filter(fallback) {
let font = fonts[glyph.metadata.min(fonts.len() - 1)];
for ch in run.text.get(glyph.start..glyph.end).unwrap_or("").chars() {
if !seen.insert((font.weight, font.italic, ch)) {
continue;
}
match missing
.iter_mut()
.find(|(other, _)| (other.weight, other.italic) == (font.weight, font.italic))
{
Some((_, chars)) => chars.push(ch),
None => missing.push((font, vec![ch])),
}
}
}
}
missing
}
pub(crate) fn measure(
&mut self,
fonts: &mut FontSystem,
known: taffy::Size<Option<f32>>,
available: taffy::Size<AvailableSpace>,
) -> taffy::Size<f32> {
let width = if self.fits_width() {
known.width.or(match available.width {
AvailableSpace::Definite(width) => Some(width),
AvailableSpace::MinContent => Some(0.0),
AvailableSpace::MaxContent => None,
})
} else {
None
};
self.buffer.set_size(width, None);
self.buffer.shape_until_scroll(fonts, false);
taffy::Size {
width: known.width.unwrap_or_else(|| self.width().ceil()),
height: known.height.unwrap_or_else(|| self.height().ceil()),
}
}
pub(crate) fn finish(&mut self, content: Rect, fonts: &mut FontSystem) {
let width = (self.fits_width() || self.aligned()).then_some(content.width);
self.finish_at(content, width, fonts);
}
pub(crate) fn finish_at(&mut self, content: Rect, width: Option<f32>, fonts: &mut FontSystem) {
self.buffer.set_size(width, None);
self.buffer.shape_until_scroll(fonts, false);
let top = ((content.height - self.height()) / 2.0).round();
self.origin = Point::new(content.x, content.y + top);
}
pub(crate) fn ink_box(&self) -> Rect {
let metrics = self.buffer.metrics();
let em = metrics.font_size;
let squeezed = ((1.2 * em).round() - metrics.line_height).max(0.0) / 2.0;
let width = self.buffer.size().0.unwrap_or(0.0).max(self.width());
Rect::new(
self.origin.x - em,
self.origin.y - em / 2.0 - squeezed,
width.ceil() + 2.0 * em,
self.height() + em + 2.0 * squeezed,
)
}
pub(crate) fn glyph_span(&self, line: usize, glyph: &LayoutGlyph) -> Option<usize> {
let index = glyph.metadata.checked_sub(1)?;
let from = *self.span_starts.get(index)?;
let to = from + self.spans.get(index)?.text.len();
let line_start = *self.line_starts.get(line)?;
let (start, end) = (line_start + glyph.start, line_start + glyph.end);
(start < end && from <= start && end <= to).then_some(index)
}
pub(crate) fn link_at(&self, point: Point) -> Option<usize> {
if !self.links_on() {
return None;
}
let (x, y) = (point.x - self.origin.x, point.y - self.origin.y);
let run = self
.runs()
.find(|run| y >= run.line_top && y < run.line_top + run.line_height)?;
let glyph = run
.glyphs
.iter()
.find(|glyph| x >= glyph.x && x < glyph.x + glyph.w)?;
let index = self.glyph_span(run.line_i, glyph)?;
self.spans[index].link.as_ref()?;
Some(index)
}
fn links_on(&self) -> bool {
self
.on_link
.as_ref()
.is_some_and(|handler| !handler.disabled())
}
pub(crate) fn lit(&self, index: usize) -> bool {
self.links_on()
&& (self.hovered_link == Some(index) || self.focused_link == Some(index))
&& self
.spans
.get(index)
.is_some_and(|span| span.link.is_some())
}
pub(crate) fn link_stops(&self) -> Vec<usize> {
if !self.links_on() {
return Vec::new();
}
let mut stops: Vec<usize> = self
.runs()
.flat_map(|run| {
let spans = run.glyphs.iter();
let spans = spans.filter_map(|glyph| self.glyph_span(run.line_i, glyph));
spans.collect::<Vec<_>>()
})
.filter(|&index| self.spans[index].link.is_some())
.collect();
stops.sort_unstable();
stops.dedup();
stops
}
pub(crate) fn link_areas(&self, index: usize) -> Vec<Rect> {
let em = self.buffer.metrics().font_size;
self
.runs()
.filter_map(|run| {
let mine = run
.glyphs
.iter()
.filter(|glyph| self.glyph_span(run.line_i, glyph) == Some(index));
let (start, end) = mine.fold(None, |span: Option<(f32, f32)>, glyph| {
let (start, end) = span.unwrap_or((glyph.x, glyph.x + glyph.w));
Some((start.min(glyph.x), end.max(glyph.x + glyph.w)))
})?;
Some(Rect::new(
self.origin.x + start - em,
self.origin.y + run.line_top - em / 2.0,
end - start + 2.0 * em,
run.line_height + em,
))
})
.collect()
}
pub(crate) fn empty_line_place(&self, rtl: bool) -> f32 {
let start = if rtl { 1.0 } else { 0.0 };
match self.style.and_then(|style| style.align) {
Some(TextAlign::Center) => 0.5,
Some(TextAlign::End) => 1.0 - start,
_ => start,
}
}
pub(crate) fn layout_width(&self) -> f32 {
self.buffer.size().0.unwrap_or_else(|| self.width())
}
pub(crate) fn runs(&self) -> impl Iterator<Item = TextRun<'_>> {
self
.buffer
.layout_runs()
.take(self.max_lines as usize)
.map(|run| {
let moved = 1.0 - self.empty_line_place(false);
TextRun::shown(run, moved)
})
}
pub(crate) fn width(&self) -> f32 {
self.runs().map(|run| run.line_w).fold(0.0, f32::max)
}
fn height(&self) -> f32 {
self.runs().map(|run| run.line_height).sum()
}
}
#[derive(Clone, Debug)]
pub struct TextRun<'a> {
pub line_i: usize,
pub text: &'a str,
pub rtl: bool,
pub glyphs: Cow<'a, [LayoutGlyph]>,
pub line_y: f32,
pub line_top: f32,
pub line_height: f32,
pub line_w: f32,
pub(crate) shift: f32,
pub(crate) first: usize,
}
impl<'a> TextRun<'a> {
fn shown(run: LayoutRun<'a>, moved: f32) -> TextRun<'a> {
let elided = run.glyphs.iter().any(|glyph| glyph.start == glyph.end);
let blank = |glyph: &&LayoutGlyph| {
glyph.start > 0
&& glyph.start < glyph.end
&& run
.text
.get(glyph.start..glyph.end)
.is_some_and(|text| text.chars().all(char::is_whitespace))
};
let dropped = match elided && !run.rtl {
true => run.glyphs.iter().take_while(blank).count(),
false => 0,
};
let (glyphs, width, shift, first) = if dropped == 0 {
(Cow::Borrowed(run.glyphs), 0.0, 0.0, 0)
} else {
let width: f32 = run.glyphs[..dropped].iter().map(|glyph| glyph.w).sum();
let shift = width * moved;
let glyphs = run.glyphs[dropped..].iter().map(|glyph| LayoutGlyph {
x: glyph.x - shift,
..glyph.clone()
});
let first = run.glyphs.get(dropped).map_or(0, |glyph| glyph.start);
(Cow::Owned(glyphs.collect()), width, shift, first)
};
TextRun {
first,
line_i: run.line_i,
text: run.text,
rtl: run.rtl,
glyphs,
line_y: run.line_y,
line_top: run.line_top,
line_height: run.line_height,
line_w: run.line_w - width,
shift,
}
}
pub(crate) fn layout(&self) -> LayoutRun<'_> {
LayoutRun {
line_i: self.line_i,
text: self.text,
rtl: self.rtl,
glyphs: &self.glyphs,
decorations: &[],
line_y: self.line_y,
line_top: self.line_top,
line_height: self.line_height,
line_w: self.line_w,
}
}
}