1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
18pub struct Font {
19 pub mono: bool,
20 pub bold: bool,
21 pub italic: bool,
22 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
56pub(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
68pub const EMOJI_AIR: f32 = 0.14;
70
71pub(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 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
107pub trait Measure {
109 fn advances(&self, text: &str, font: Font) -> Rc<Vec<f32>>;
110
111 fn in_cells(&self) -> bool;
113
114 fn cell_pixels(&self) -> Option<(u32, u32)> {
116 None
117 }
118
119 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
130pub struct CellMeasure;
132
133impl Measure for CellMeasure {
134 fn advances(&self, text: &str, _font: Font) -> Rc<Vec<f32>> {
135 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 let mut out = Vec::with_capacity(text.len());
143 for letter in text.graphemes(true) {
144 let count = letter.chars().count();
145 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
161type Advances = Rc<Vec<f32>>;
163
164pub struct FontMeasure {
166 fonts: RefCell<FontSystem>,
167 with_emoji: RefCell<Option<(FontSystem, Option<String>)>>,
171 cell: (usize, usize),
172 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 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 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 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 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 #[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 #[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 assert!(advances[1] > letter && advances[1] < 3.0, "{advances:?}");
348 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 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}