Skip to main content

cellix_render/
measure.rs

1//! How wide text really is. Carets, wrapping and clicks all need this, and it differs by
2//! tier: a text cell is one column per character, and a font isn't.
3
4use std::cell::RefCell;
5use std::collections::HashMap;
6use std::rc::Rc;
7
8use cosmic_text::{
9    Attrs, Buffer, Family, FontSystem, Metrics, Shaping, Style as FontStyle, Weight, fontdb,
10};
11use unicode_segmentation::UnicodeSegmentation;
12use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
13
14use crate::raster::{INTER, INTER_ITALIC, MONO, MONO_ITALIC, emoji_font, text_pixels};
15
16/// How a run of painted text is set.
17#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
18pub struct Font {
19    pub mono: bool,
20    pub bold: bool,
21    pub italic: bool,
22    /// Percent of the normal interface size.
23    pub size: u8,
24}
25
26impl Default for Font {
27    fn default() -> Self {
28        Self {
29            mono: false,
30            bold: false,
31            italic: false,
32            size: 100,
33        }
34    }
35}
36
37pub(crate) fn family(font: Font) -> Family<'static> {
38    if font.mono {
39        Family::Monospace
40    } else {
41        Family::SansSerif
42    }
43}
44
45pub(crate) fn attrs(font: Font) -> Attrs<'static> {
46    let mut attrs = Attrs::new().family(family(font));
47    if font.bold {
48        attrs = attrs.weight(Weight::SEMIBOLD);
49    }
50    if font.italic {
51        attrs = attrs.style(FontStyle::Italic);
52    }
53    attrs
54}
55
56/// Whether a letter is drawn as an emoji: it carries the mark that asks for it, or it's one
57/// of those that are emoji unless told otherwise. A text font may hold a plain heart or a
58/// smiling face, and would draw the emoji as that.
59pub(crate) fn emoji_letter(letter: &str) -> bool {
60    letter.contains('\u{fe0f}')
61        || letter.chars().next().is_some_and(|c| {
62            let code = c as u32;
63            (0x1f000..=0x1faff).contains(&code)
64                || ((0x2300..=0x2bff).contains(&code) && c.width() == Some(2))
65        })
66}
67
68/// The air after an emoji in a line of words, as a share of the text's size.
69pub const EMOJI_AIR: f32 = 0.14;
70
71/// A line of text as runs to set: its emoji in the emoji font, and the rest in its own.
72pub(crate) fn runs<'a>(
73    text: &'a str,
74    font: Font,
75    emoji: Option<&'a str>,
76) -> Vec<(&'a str, Attrs<'a>)> {
77    let plain = attrs(font);
78    let Some(family) = emoji.filter(|_| !text.is_ascii()) else {
79        return vec![(text, plain)];
80    };
81    // With a little air after each: two set together touch, and so does a caret after one.
82    let coloured = plain
83        .clone()
84        .family(Family::Name(family))
85        .letter_spacing(EMOJI_AIR);
86    let pick = |emoji: bool| {
87        if emoji {
88            coloured.clone()
89        } else {
90            plain.clone()
91        }
92    };
93    let mut out = Vec::new();
94    let (mut start, mut kind) = (0, None);
95    for (at, letter) in text.grapheme_indices(true) {
96        let is = emoji_letter(letter);
97        if let Some(was) = kind.filter(|was| *was != is) {
98            out.push((&text[start..at], pick(was)));
99            start = at;
100        }
101        kind = Some(is);
102    }
103    out.push((&text[start..], pick(kind == Some(true))));
104    out
105}
106
107/// Measures text, in cells, one advance per char.
108pub trait Measure {
109    fn advances(&self, text: &str, font: Font) -> Rc<Vec<f32>>;
110
111    /// True when text sits in whole cells, so cell positions are exact.
112    fn in_cells(&self) -> bool;
113
114    /// A cell's size in pixels, where there are pixels.
115    fn cell_pixels(&self) -> Option<(u32, u32)> {
116        None
117    }
118
119    /// Whether emoji come out as themselves here. A terminal draws its own; painted text
120    /// needs a font for them on the machine that paints it, which a server may not have.
121    fn shows_emoji(&self) -> bool {
122        true
123    }
124
125    fn width(&self, text: &str, font: Font) -> f32 {
126        self.advances(text, font).iter().sum()
127    }
128}
129
130/// The text-cell tier, and tests.
131pub struct CellMeasure;
132
133impl Measure for CellMeasure {
134    fn advances(&self, text: &str, _font: Font) -> Rc<Vec<f32>> {
135        // Plain text, which is nearly all of it, is a column a letter.
136        if text.is_ascii() {
137            let column = |byte: u8| f32::from(u8::from(!byte.is_ascii_control()));
138            return Rc::new(text.bytes().map(column).collect());
139        }
140        // By what reads as one letter, as the grid places them: an emoji made of several
141        // code points takes its two columns once, on its first.
142        let mut out = Vec::with_capacity(text.len());
143        for letter in text.graphemes(true) {
144            let count = letter.chars().count();
145            // A line's end is two controls in one letter, and takes no room.
146            if count == 1 || letter.chars().any(char::is_control) {
147                out.extend(letter.chars().map(|c| c.width().unwrap_or(0) as f32));
148            } else {
149                out.push(letter.width() as f32);
150                out.extend(std::iter::repeat_n(0.0, count - 1));
151            }
152        }
153        Rc::new(out)
154    }
155
156    fn in_cells(&self) -> bool {
157        true
158    }
159}
160
161/// One advance per char, in cells.
162type Advances = Rc<Vec<f32>>;
163
164/// The pixel tiers: the same fonts and sizes the rasterizer draws with.
165pub struct FontMeasure {
166    fonts: RefCell<FontSystem>,
167    /// The built-in fonts with the machine's emoji font beside them, and that font's name,
168    /// for text that holds emoji: the rasterizer draws those in it, so they're measured
169    /// in it. Made when such text first turns up.
170    with_emoji: RefCell<Option<(FontSystem, Option<String>)>>,
171    cell: (usize, usize),
172    cache: RefCell<HashMap<(String, Font), Advances>>,
173}
174
175fn built_in() -> fontdb::Database {
176    let mut db = fontdb::Database::new();
177    for data in [INTER, INTER_ITALIC, MONO, MONO_ITALIC] {
178        db.load_font_data(data.to_vec());
179    }
180    db.set_monospace_family("JetBrains Mono");
181    db.set_sans_serif_family("Inter Variable");
182    db
183}
184
185impl FontMeasure {
186    pub fn new(cell_width: usize, cell_height: usize) -> Self {
187        Self {
188            fonts: RefCell::new(FontSystem::new_with_locale_and_db(
189                "en-US".into(),
190                built_in(),
191            )),
192            with_emoji: RefCell::new(None),
193            cell: (cell_width, cell_height),
194            cache: RefCell::new(HashMap::new()),
195        }
196    }
197
198    /// Each byte's advance in pixels, set in `fonts` with its emoji in the `emoji` font.
199    fn shape(
200        &self,
201        fonts: &mut FontSystem,
202        emoji: Option<&str>,
203        text: &str,
204        font: Font,
205    ) -> Vec<f32> {
206        let px = text_pixels(self.cell.1, font);
207        let mut buffer = Buffer::new(fonts, Metrics::new(px, px * 1.4));
208        buffer.set_size(None, None);
209        buffer.set_rich_text(
210            runs(text, font, emoji),
211            &attrs(font),
212            Shaping::Advanced,
213            None,
214        );
215        buffer.shape_until_scroll(fonts, false);
216        let mut by_byte = vec![0.0; text.len() + 1];
217        for run in buffer.layout_runs() {
218            for glyph in run.glyphs {
219                by_byte[glyph.start] += glyph.w;
220            }
221        }
222        by_byte
223    }
224
225    /// The same for text that holds emoji, with them set in the machine's emoji font.
226    fn shape_with_emoji(&self, text: &str, font: Font) -> Vec<f32> {
227        let mut with_emoji = self.with_emoji.borrow_mut();
228        let (fonts, emoji) = with_emoji.get_or_insert_with(|| {
229            let mut db = built_in();
230            let family = emoji_font().map(|(family, source)| {
231                db.load_font_source(source.clone());
232                family.clone()
233            });
234            let fonts = FontSystem::new_with_locale_and_db("en-US".into(), db);
235            (fonts, family)
236        });
237        self.shape(fonts, emoji.as_deref(), text, font)
238    }
239}
240
241impl Measure for FontMeasure {
242    fn advances(&self, text: &str, font: Font) -> Rc<Vec<f32>> {
243        let key = (text.to_string(), font);
244        if let Some(found) = self.cache.borrow().get(&key) {
245            return found.clone();
246        }
247        // An emoji is drawn in the machine's emoji font, so that's what it's measured in.
248        let emoji = !text.is_ascii() && text.graphemes(true).any(emoji_letter);
249        let by_byte = if emoji {
250            self.shape_with_emoji(text, font)
251        } else {
252            self.shape(&mut self.fonts.borrow_mut(), None, text, font)
253        };
254        let cell = self.cell.0 as f32;
255        let advances: Vec<f32> = text
256            .char_indices()
257            .map(|(at, _)| by_byte[at] / cell)
258            .collect();
259        let advances = Rc::new(advances);
260        let mut cache = self.cache.borrow_mut();
261        if cache.len() > 20_000 {
262            cache.clear();
263        }
264        cache.insert(key, advances.clone());
265        advances
266    }
267
268    fn in_cells(&self) -> bool {
269        false
270    }
271
272    fn cell_pixels(&self) -> Option<(u32, u32)> {
273        Some((self.cell.0 as u32, self.cell.1 as u32))
274    }
275
276    fn shows_emoji(&self) -> bool {
277        emoji_font().is_some()
278    }
279}
280
281#[cfg(test)]
282mod tests {
283    use super::*;
284
285    #[test]
286    fn cells_count_columns() {
287        assert_eq!(CellMeasure.width("abc", Font::default()), 3.0);
288    }
289
290    /// An emoji takes the two columns the grid gives it, however many code points it's
291    /// made of, and an advance for each of them all the same.
292    #[test]
293    fn an_emoji_of_several_code_points_is_two_columns() {
294        let font = Font::default();
295        for emoji in ["πŸ‘", "❀\u{fe0f}", "πŸ‘πŸ½", "πŸ‘©\u{200d}πŸ’»", "πŸ‡ΉπŸ‡·"] {
296            assert_eq!(CellMeasure.width(emoji, font), 2.0, "{emoji}");
297            let advances = CellMeasure.advances(emoji, font);
298            assert_eq!(advances.len(), emoji.chars().count(), "{emoji}");
299        }
300        assert_eq!(CellMeasure.width("a❀\u{fe0f}b", font), 4.0);
301        assert_eq!(CellMeasure.width("e\u{301}\r\n", font), 1.0);
302    }
303
304    #[test]
305    fn proportional_text_has_real_widths() {
306        let m = FontMeasure::new(17, 37);
307        let font = Font::default();
308        assert!(m.width("iiii", font) < m.width("WWWW", font));
309        assert_eq!(m.advances("hΓ©llo", font).len(), 5);
310    }
311
312    #[test]
313    fn mono_text_keeps_even_advances() {
314        let m = FontMeasure::new(17, 37);
315        let font = Font {
316            mono: true,
317            ..Font::default()
318        };
319        let advances = m.advances("iW", font);
320        assert!((advances[0] - advances[1]).abs() < 0.01);
321    }
322
323    /// An emoji is measured in the font that draws it, where the machine has one: the
324    /// built-in fonts have none, and their blank is narrower than any emoji.
325    #[test]
326    fn an_emoji_is_measured_in_the_font_that_draws_it() {
327        let m = FontMeasure::new(17, 37);
328        let font = Font::default();
329        if !m.shows_emoji() {
330            return;
331        }
332        let advances = m.advances("aπŸ‘b", font);
333        assert_eq!(advances.len(), 3);
334        let letter = m.width("a", font);
335        assert!((advances[0] - letter).abs() < 0.01, "{advances:?}");
336        // About as wide as it is tall, which is more than a letter and less than three.
337        assert!(advances[1] > letter && advances[1] < 3.0, "{advances:?}");
338        // A heart the built-in font has a plain form of is still measured as the emoji.
339        let heart = m.width("❀\u{fe0f}", font);
340        assert!(
341            (heart - advances[1]).abs() < 0.2,
342            "{heart} beside {advances:?}"
343        );
344    }
345
346    #[test]
347    fn a_line_is_set_in_runs_with_its_emoji_apart() {
348        let font = Font::default();
349        let all = runs("ok ❀\u{fe0f}πŸ‘ then βœ…", font, Some("Some Emoji"));
350        let words: Vec<&str> = all.iter().map(|(text, _)| *text).collect();
351        assert_eq!(words, ["ok ", "❀\u{fe0f}πŸ‘", " then ", "βœ…"]);
352        assert_eq!(runs("plain", font, Some("Some Emoji")).len(), 1);
353        assert_eq!(runs("ok πŸ‘", font, None).len(), 1);
354        // A letter from another script, an arrow and a check mark aren't emoji.
355        for letter in ["δΈ­", "β†’", "βœ“", "Γ©"] {
356            assert!(!emoji_letter(letter), "{letter}");
357        }
358    }
359
360    #[test]
361    fn larger_text_is_wider() {
362        let m = FontMeasure::new(17, 37);
363        let big = Font {
364            size: 200,
365            ..Font::default()
366        };
367        let width = m.width("Title", big);
368        assert!((width - 2.0 * m.width("Title", Font::default())).abs() < 0.3);
369    }
370}