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