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