1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
19pub struct Font {
20 pub mono: bool,
21 pub bold: bool,
22 pub italic: bool,
23 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 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
65pub(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
77pub const EMOJI_AIR: f32 = 0.14;
79
80pub(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 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
116pub trait Measure {
118 fn advances(&self, text: &str, font: Font) -> Rc<Vec<f32>>;
119
120 fn in_cells(&self) -> bool;
122
123 fn cell_pixels(&self) -> Option<(u32, u32)> {
125 None
126 }
127
128 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 fn row_air(&self) -> f32 {
141 1.0
142 }
143}
144
145pub struct CellMeasure;
147
148impl Measure for CellMeasure {
149 fn advances(&self, text: &str, _font: Font) -> Rc<Vec<f32>> {
150 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 let mut out = Vec::with_capacity(text.len());
158 for letter in text.graphemes(true) {
159 let count = letter.chars().count();
160 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
176type Advances = Rc<Vec<f32>>;
178
179pub struct FontMeasure {
181 fonts: RefCell<FontSystem>,
182 with_emoji: RefCell<Option<(FontSystem, Option<String>)>>,
186 cell: (usize, usize),
187 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 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 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 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 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 #[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 #[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 assert!(advances[1] > letter && advances[1] < 3.0, "{advances:?}");
367 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 for letter in ["δΈ", "β", "β", "Γ©"] {
391 assert!(!emoji_letter(letter), "{letter}");
392 }
393 }
394
395 #[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}