1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
use std::hash::{
BuildHasher,
Hasher,
RandomState,
};
use ratatui::{
buffer::Cell,
style::Modifier,
};
use rustybuzz::Face;
/// A Font which can be used for rendering.
#[derive(Clone)]
pub struct Font<'a> {
font: Face<'a>,
advance: f32,
id: u64,
}
impl<'a> Font<'a> {
/// Create a new Font from data. Returns [`None`] if the font cannot
/// be parsed.
pub fn new(data: &'a [u8]) -> Option<Self> {
let mut hasher = RandomState::new().build_hasher();
hasher.write(data);
Face::from_slice(data, 0).map(|font| {
let advance = font
.glyph_hor_advance(font.glyph_index('m').unwrap_or_default())
.unwrap_or_default() as f32;
Self {
font,
advance,
id: hasher.finish(),
}
})
}
}
impl Font<'_> {
pub(crate) fn id(&self) -> u64 {
self.id
}
pub(crate) fn font(&self) -> &Face {
&self.font
}
pub(crate) fn char_width(&self, height_px: u32) -> u32 {
let scale = height_px as f32 / self.font.height() as f32;
(self.advance * scale) as u32
}
}
/// A collection of fonts to use for rendering. Supports font fallback.
///
/// It is recommended, but not required, that all fonts have the same/very
/// similar aspect ratio, or you may get unexpected results during rendering due
/// to fallback.
pub struct Fonts<'a> {
char_width: u32,
char_height: u32,
last_resort: Font<'a>,
regular: Vec<Font<'a>>,
bold: Vec<Font<'a>>,
italic: Vec<Font<'a>>,
bold_italic: Vec<Font<'a>>,
}
impl<'a> Fonts<'a> {
/// Create a new, empty set of fonts. The provided font will be used as a
/// last-resort fallback if no other fonts can render a particular
/// character. Rendering will attempt to fake bold/italic styles using this
/// font where appropriate.
///
/// The provided size_px will be the rendered height in pixels of all fonts
/// in this collection.
pub fn new(font: Font<'a>, size_px: u32) -> Self {
Self {
char_width: font.char_width(size_px),
char_height: size_px,
last_resort: font,
regular: vec![],
bold: vec![],
italic: vec![],
bold_italic: vec![],
}
}
/// The height (in pixels) of all fonts.
#[inline]
pub fn height_px(&self) -> u32 {
self.char_height
}
/// The maximum width (in pixels) across all fonts.
#[inline]
pub fn width_px(&self) -> u32 {
self.char_width
}
/// Change the height of all fonts in this collection to the specified
/// height in pixels.
pub fn set_size_px(&mut self, height_px: u32) {
self.char_height = height_px;
self.char_width = std::iter::once(&self.last_resort)
.chain(self.regular.iter())
.chain(self.bold.iter())
.chain(self.italic.iter())
.chain(self.bold_italic.iter())
.map(|font| font.char_width(height_px))
.max()
.unwrap_or_default();
}
/// Add a new collection of fonts for regular styled text. These fonts will
/// come _after_ previously provided fonts in the fallback order.
pub fn add_regular_fonts(&mut self, fonts: impl IntoIterator<Item = Font<'a>>) {
self.char_width =
self.char_width
.max(Self::add_fonts(&mut self.regular, fonts, self.char_height));
}
/// Add a new collection of fonts for bold styled text. These fonts will
/// come _after_ previously provided fonts in the fallback order.
///
/// You do not have to provide these for bold text to be supported. If no
/// bold fonts are supplied, rendering will fallback to the regular fonts
/// with fake bolding.
pub fn add_bold_fonts(&mut self, fonts: impl IntoIterator<Item = Font<'a>>) {
self.char_width =
self.char_width
.max(Self::add_fonts(&mut self.bold, fonts, self.char_height));
}
/// Add a new collection of fonts for italic styled text. These fonts will
/// come _after_ previously provided fonts in the fallback order.
///
/// It is recommended, but not required, that you provide italic fonts if
/// your application intends to make use of italics. If no italic fonts
/// are supplied, rendering will fallback to the regular fonts with fake
/// italics.
pub fn add_italic_fonts(&mut self, fonts: impl IntoIterator<Item = Font<'a>>) {
self.char_width =
self.char_width
.max(Self::add_fonts(&mut self.italic, fonts, self.char_height));
}
/// Add a new collection of fonts for bold italic styled text. These fonts
/// will come _after_ previously provided fonts in the fallback order.
///
/// You do not have to provide these for bold text to be supported. If no
/// bold fonts are supplied, rendering will fallback to the italic fonts
/// with fake bolding.
pub fn add_bold_italic_fonts(&mut self, fonts: impl IntoIterator<Item = Font<'a>>) {
self.char_width = self.char_width.max(Self::add_fonts(
&mut self.bold_italic,
fonts,
self.char_height,
));
}
}
impl<'a> Fonts<'a> {
pub(crate) fn count(&self) -> usize {
1 + self.bold.len() + self.italic.len() + self.bold_italic.len() + self.regular.len()
}
pub(crate) fn font_for_cell(&self, cell: &Cell) -> (&Font, bool, bool) {
if cell.modifier.contains(Modifier::BOLD | Modifier::ITALIC) {
self.select_font(
cell.symbol(),
self.bold_italic
.iter()
.map(|f| (f, false, false))
.chain(self.italic.iter().map(|f| (f, true, false)))
.chain(self.bold.iter().map(|f| (f, false, true)))
.chain(self.regular.iter().map(|f| (f, true, true))),
true,
true,
)
} else if cell.modifier.contains(Modifier::BOLD) {
self.select_font(
cell.symbol(),
self.bold
.iter()
.map(|f| (f, false, false))
.chain(self.regular.iter().map(|f| (f, true, false))),
true,
false,
)
} else if cell.modifier.contains(Modifier::ITALIC) {
self.select_font(
cell.symbol(),
self.italic
.iter()
.map(|f| (f, false, false))
.chain(self.regular.iter().map(|f| (f, false, true))),
false,
true,
)
} else {
self.select_font(
cell.symbol(),
self.regular.iter().map(|f| (f, false, false)),
false,
false,
)
}
}
fn select_font<'fonts>(
&'fonts self,
cluster: &str,
fonts: impl IntoIterator<Item = (&'fonts Font<'a>, bool, bool)>,
last_resort_fake_bold: bool,
last_resort_fake_italic: bool,
) -> (&'fonts Font<'a>, bool, bool) {
let mut max = 0;
let mut font = None;
for (candidate, fake_bold, fake_italic) in fonts.into_iter().chain(std::iter::once((
&self.last_resort,
last_resort_fake_bold,
last_resort_fake_italic,
))) {
let (count, last_idx) =
cluster
.chars()
.enumerate()
.fold((0, 0), |(mut count, _), (idx, ch)| {
count += usize::from(candidate.font().glyph_index(ch).is_some());
(count, idx)
});
if count > max {
max = count;
font = Some((candidate, fake_bold, fake_italic));
}
if count == last_idx + 1 {
break;
}
}
*font.get_or_insert((
&self.last_resort,
last_resort_fake_bold,
last_resort_fake_italic,
))
}
fn add_fonts(
target: &mut Vec<Font<'a>>,
fonts: impl IntoIterator<Item = Font<'a>>,
char_height: u32,
) -> u32 {
let len = target.len();
target.extend(fonts);
target[len..]
.iter()
.map(|font| font.char_width(char_height))
.max()
.unwrap_or_default()
}
}