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_width::UnicodeWidthChar;
12
13use crate::raster::{INTER, INTER_ITALIC, MONO, MONO_ITALIC, text_pixels};
14
15#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
17pub struct Font {
18 pub mono: bool,
19 pub bold: bool,
20 pub italic: bool,
21 pub size: u8,
23}
24
25impl Default for Font {
26 fn default() -> Self {
27 Self {
28 mono: false,
29 bold: false,
30 italic: false,
31 size: 100,
32 }
33 }
34}
35
36pub(crate) fn family(font: Font) -> Family<'static> {
37 if font.mono {
38 Family::Monospace
39 } else {
40 Family::SansSerif
41 }
42}
43
44pub(crate) fn attrs(font: Font) -> Attrs<'static> {
45 let mut attrs = Attrs::new().family(family(font));
46 if font.bold {
47 attrs = attrs.weight(Weight::SEMIBOLD);
48 }
49 if font.italic {
50 attrs = attrs.style(FontStyle::Italic);
51 }
52 attrs
53}
54
55pub trait Measure {
57 fn advances(&self, text: &str, font: Font) -> Rc<Vec<f32>>;
58
59 fn in_cells(&self) -> bool;
61
62 fn cell_pixels(&self) -> Option<(u32, u32)> {
64 None
65 }
66
67 fn width(&self, text: &str, font: Font) -> f32 {
68 self.advances(text, font).iter().sum()
69 }
70}
71
72pub struct CellMeasure;
74
75impl Measure for CellMeasure {
76 fn advances(&self, text: &str, _font: Font) -> Rc<Vec<f32>> {
77 Rc::new(
78 text.chars()
79 .map(|c| c.width().unwrap_or(0) as f32)
80 .collect(),
81 )
82 }
83
84 fn in_cells(&self) -> bool {
85 true
86 }
87}
88
89type Advances = Rc<Vec<f32>>;
91
92pub struct FontMeasure {
94 fonts: RefCell<FontSystem>,
95 cell: (usize, usize),
96 cache: RefCell<HashMap<(String, Font), Advances>>,
97}
98
99impl FontMeasure {
100 pub fn new(cell_width: usize, cell_height: usize) -> Self {
101 let mut db = fontdb::Database::new();
102 for data in [INTER, INTER_ITALIC, MONO, MONO_ITALIC] {
103 db.load_font_data(data.to_vec());
104 }
105 db.set_monospace_family("JetBrains Mono");
106 db.set_sans_serif_family("Inter Variable");
107 Self {
108 fonts: RefCell::new(FontSystem::new_with_locale_and_db("en-US".into(), db)),
109 cell: (cell_width, cell_height),
110 cache: RefCell::new(HashMap::new()),
111 }
112 }
113}
114
115impl Measure for FontMeasure {
116 fn advances(&self, text: &str, font: Font) -> Rc<Vec<f32>> {
117 let key = (text.to_string(), font);
118 if let Some(found) = self.cache.borrow().get(&key) {
119 return found.clone();
120 }
121 let px = text_pixels(self.cell.1, font);
122 let fonts = &mut *self.fonts.borrow_mut();
123 let mut buffer = Buffer::new(fonts, Metrics::new(px, px * 1.4));
124 buffer.set_size(None, None);
125 let style = attrs(font);
126 buffer.set_rich_text(
127 std::iter::once((text, style.clone())),
128 &style,
129 Shaping::Advanced,
130 None,
131 );
132 buffer.shape_until_scroll(fonts, false);
133 let mut by_byte = vec![0.0; text.len() + 1];
134 for run in buffer.layout_runs() {
135 for glyph in run.glyphs {
136 by_byte[glyph.start] += glyph.w;
137 }
138 }
139 let cell = self.cell.0 as f32;
140 let advances: Vec<f32> = text
141 .char_indices()
142 .map(|(at, _)| by_byte[at] / cell)
143 .collect();
144 let advances = Rc::new(advances);
145 let mut cache = self.cache.borrow_mut();
146 if cache.len() > 20_000 {
147 cache.clear();
148 }
149 cache.insert(key, advances.clone());
150 advances
151 }
152
153 fn in_cells(&self) -> bool {
154 false
155 }
156
157 fn cell_pixels(&self) -> Option<(u32, u32)> {
158 Some((self.cell.0 as u32, self.cell.1 as u32))
159 }
160}
161
162#[cfg(test)]
163mod tests {
164 use super::*;
165
166 #[test]
167 fn cells_count_columns() {
168 assert_eq!(CellMeasure.width("abc", Font::default()), 3.0);
169 }
170
171 #[test]
172 fn proportional_text_has_real_widths() {
173 let m = FontMeasure::new(17, 37);
174 let font = Font::default();
175 assert!(m.width("iiii", font) < m.width("WWWW", font));
176 assert_eq!(m.advances("héllo", font).len(), 5);
177 }
178
179 #[test]
180 fn mono_text_keeps_even_advances() {
181 let m = FontMeasure::new(17, 37);
182 let font = Font {
183 mono: true,
184 ..Font::default()
185 };
186 let advances = m.advances("iW", font);
187 assert!((advances[0] - advances[1]).abs() < 0.01);
188 }
189
190 #[test]
191 fn larger_text_is_wider() {
192 let m = FontMeasure::new(17, 37);
193 let big = Font {
194 size: 200,
195 ..Font::default()
196 };
197 let width = m.width("Title", big);
198 assert!((width - 2.0 * m.width("Title", Font::default())).abs() < 0.3);
199 }
200}