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    /// The row height words take their size from, as the rasterizer's is.
173    type_row: usize,
174    cache: RefCell<HashMap<(String, Font), Advances>>,
175}
176
177fn built_in() -> fontdb::Database {
178    let mut db = fontdb::Database::new();
179    for data in [INTER, INTER_ITALIC, MONO, MONO_ITALIC] {
180        db.load_font_data(data.to_vec());
181    }
182    db.set_monospace_family("JetBrains Mono");
183    db.set_sans_serif_family("Inter Variable");
184    db
185}
186
187impl FontMeasure {
188    pub fn new(cell_width: usize, cell_height: usize) -> Self {
189        Self {
190            fonts: RefCell::new(FontSystem::new_with_locale_and_db(
191                "en-US".into(),
192                built_in(),
193            )),
194            with_emoji: RefCell::new(None),
195            cell: (cell_width, cell_height),
196            type_row: cell_height,
197            cache: RefCell::new(HashMap::new()),
198        }
199    }
200
201    /// Measures words at the size they have on a row of `rows` pixels, as the rasterizer
202    /// draws them where Cellix's rows are taller than the terminal's line.
203    pub fn with_type_row(mut self, rows: usize) -> Self {
204        self.type_row = rows.clamp(1, self.cell.1);
205        self
206    }
207
208    /// Each byte's advance in pixels, set in `fonts` with its emoji in the `emoji` font.
209    fn shape(
210        &self,
211        fonts: &mut FontSystem,
212        emoji: Option<&str>,
213        text: &str,
214        font: Font,
215    ) -> Vec<f32> {
216        let px = text_pixels(self.type_row, font);
217        let mut buffer = Buffer::new(fonts, Metrics::new(px, px * 1.4));
218        buffer.set_size(None, None);
219        buffer.set_rich_text(
220            runs(text, font, emoji),
221            &attrs(font),
222            Shaping::Advanced,
223            None,
224        );
225        buffer.shape_until_scroll(fonts, false);
226        let mut by_byte = vec![0.0; text.len() + 1];
227        for run in buffer.layout_runs() {
228            for glyph in run.glyphs {
229                by_byte[glyph.start] += glyph.w;
230            }
231        }
232        by_byte
233    }
234
235    /// The same for text that holds emoji, with them set in the machine's emoji font.
236    fn shape_with_emoji(&self, text: &str, font: Font) -> Vec<f32> {
237        let mut with_emoji = self.with_emoji.borrow_mut();
238        let (fonts, emoji) = with_emoji.get_or_insert_with(|| {
239            let mut db = built_in();
240            let family = emoji_font().map(|(family, source)| {
241                db.load_font_source(source.clone());
242                family.clone()
243            });
244            let fonts = FontSystem::new_with_locale_and_db("en-US".into(), db);
245            (fonts, family)
246        });
247        self.shape(fonts, emoji.as_deref(), text, font)
248    }
249}
250
251impl Measure for FontMeasure {
252    fn advances(&self, text: &str, font: Font) -> Rc<Vec<f32>> {
253        let key = (text.to_string(), font);
254        if let Some(found) = self.cache.borrow().get(&key) {
255            return found.clone();
256        }
257        // An emoji is drawn in the machine's emoji font, so that's what it's measured in.
258        let emoji = !text.is_ascii() && text.graphemes(true).any(emoji_letter);
259        let by_byte = if emoji {
260            self.shape_with_emoji(text, font)
261        } else {
262            self.shape(&mut self.fonts.borrow_mut(), None, text, font)
263        };
264        let cell = self.cell.0 as f32;
265        let advances: Vec<f32> = text
266            .char_indices()
267            .map(|(at, _)| by_byte[at] / cell)
268            .collect();
269        let advances = Rc::new(advances);
270        let mut cache = self.cache.borrow_mut();
271        if cache.len() > 20_000 {
272            cache.clear();
273        }
274        cache.insert(key, advances.clone());
275        advances
276    }
277
278    fn in_cells(&self) -> bool {
279        false
280    }
281
282    fn cell_pixels(&self) -> Option<(u32, u32)> {
283        Some((self.cell.0 as u32, self.cell.1 as u32))
284    }
285
286    fn shows_emoji(&self) -> bool {
287        emoji_font().is_some()
288    }
289}
290
291#[cfg(test)]
292mod tests {
293    use super::*;
294
295    #[test]
296    fn cells_count_columns() {
297        assert_eq!(CellMeasure.width("abc", Font::default()), 3.0);
298    }
299
300    /// An emoji takes the two columns the grid gives it, however many code points it's
301    /// made of, and an advance for each of them all the same.
302    #[test]
303    fn an_emoji_of_several_code_points_is_two_columns() {
304        let font = Font::default();
305        for emoji in ["πŸ‘", "❀\u{fe0f}", "πŸ‘πŸ½", "πŸ‘©\u{200d}πŸ’»", "πŸ‡ΉπŸ‡·"] {
306            assert_eq!(CellMeasure.width(emoji, font), 2.0, "{emoji}");
307            let advances = CellMeasure.advances(emoji, font);
308            assert_eq!(advances.len(), emoji.chars().count(), "{emoji}");
309        }
310        assert_eq!(CellMeasure.width("a❀\u{fe0f}b", font), 4.0);
311        assert_eq!(CellMeasure.width("e\u{301}\r\n", font), 1.0);
312    }
313
314    #[test]
315    fn proportional_text_has_real_widths() {
316        let m = FontMeasure::new(17, 37);
317        let font = Font::default();
318        assert!(m.width("iiii", font) < m.width("WWWW", font));
319        assert_eq!(m.advances("hΓ©llo", font).len(), 5);
320    }
321
322    #[test]
323    fn mono_text_keeps_even_advances() {
324        let m = FontMeasure::new(17, 37);
325        let font = Font {
326            mono: true,
327            ..Font::default()
328        };
329        let advances = m.advances("iW", font);
330        assert!((advances[0] - advances[1]).abs() < 0.01);
331    }
332
333    /// An emoji is measured in the font that draws it, where the machine has one: the
334    /// built-in fonts have none, and their blank is narrower than any emoji.
335    #[test]
336    fn an_emoji_is_measured_in_the_font_that_draws_it() {
337        let m = FontMeasure::new(17, 37);
338        let font = Font::default();
339        if !m.shows_emoji() {
340            return;
341        }
342        let advances = m.advances("aπŸ‘b", font);
343        assert_eq!(advances.len(), 3);
344        let letter = m.width("a", font);
345        assert!((advances[0] - letter).abs() < 0.01, "{advances:?}");
346        // About as wide as it is tall, which is more than a letter and less than three.
347        assert!(advances[1] > letter && advances[1] < 3.0, "{advances:?}");
348        // A heart the built-in font has a plain form of is still measured as the emoji: as
349        // wide as the thumb, or wider by the air kept after an emoji and no more. It's two
350        // characters, the heart and what makes it an emoji, and a font that shapes the second
351        // apart gives it that air again, as Apple's does; Twemoji and Noto shape them as one.
352        // A plain heart would be half a column narrower than the thumb.
353        let heart = m.width("❀\u{fe0f}", font);
354        let air = EMOJI_AIR * crate::raster::INTERFACE_SIZE * 37.0 / 17.0;
355        let wider = heart - advances[1];
356        assert!(
357            (-0.02..air + 0.02).contains(&wider),
358            "{heart} beside {advances:?} and {air} of air"
359        );
360    }
361
362    #[test]
363    fn a_line_is_set_in_runs_with_its_emoji_apart() {
364        let font = Font::default();
365        let all = runs("ok ❀\u{fe0f}πŸ‘ then βœ…", font, Some("Some Emoji"));
366        let words: Vec<&str> = all.iter().map(|(text, _)| *text).collect();
367        assert_eq!(words, ["ok ", "❀\u{fe0f}πŸ‘", " then ", "βœ…"]);
368        assert_eq!(runs("plain", font, Some("Some Emoji")).len(), 1);
369        assert_eq!(runs("ok πŸ‘", font, None).len(), 1);
370        // A letter from another script, an arrow and a check mark aren't emoji.
371        for letter in ["δΈ­", "β†’", "βœ“", "Γ©"] {
372            assert!(!emoji_letter(letter), "{letter}");
373        }
374    }
375
376    #[test]
377    fn larger_text_is_wider() {
378        let m = FontMeasure::new(17, 37);
379        let big = Font {
380            size: 200,
381            ..Font::default()
382        };
383        let width = m.width("Title", big);
384        assert!((width - 2.0 * m.width("Title", Font::default())).abs() < 0.3);
385    }
386}