1use crate::{Attrs, Font, FontMatchAttrs, HashMap, ShapeBuffer};
2use alloc::boxed::Box;
3use alloc::collections::BTreeSet;
4use alloc::string::String;
5use alloc::sync::Arc;
6use alloc::vec::Vec;
7use core::fmt;
8use core::ops::{Deref, DerefMut};
9
10pub use fontdb;
12pub use rustybuzz;
13
14use super::fallback::{Fallback, Fallbacks, MonospaceFallbackInfo, PlatformFallback};
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
17pub struct FontMatchKey {
18 pub(crate) font_weight_diff: u16,
19 pub(crate) font_weight: u16,
20 pub(crate) id: fontdb::ID,
21}
22
23struct FontCachedCodepointSupportInfo {
24 supported: Vec<u32>,
25 not_supported: Vec<u32>,
26}
27
28impl FontCachedCodepointSupportInfo {
29 const SUPPORTED_MAX_SZ: usize = 512;
30 const NOT_SUPPORTED_MAX_SZ: usize = 1024;
31
32 fn new() -> Self {
33 Self {
34 supported: Vec::with_capacity(Self::SUPPORTED_MAX_SZ),
35 not_supported: Vec::with_capacity(Self::NOT_SUPPORTED_MAX_SZ),
36 }
37 }
38
39 #[inline(always)]
40 fn unknown_has_codepoint(
41 &mut self,
42 font_codepoints: &[u32],
43 codepoint: u32,
44 supported_insert_pos: usize,
45 not_supported_insert_pos: usize,
46 ) -> bool {
47 let ret = font_codepoints.contains(&codepoint);
48 if ret {
49 if supported_insert_pos != Self::SUPPORTED_MAX_SZ {
51 self.supported.insert(supported_insert_pos, codepoint);
52 self.supported.truncate(Self::SUPPORTED_MAX_SZ);
53 }
54 } else {
55 if not_supported_insert_pos != Self::NOT_SUPPORTED_MAX_SZ {
57 self.not_supported
58 .insert(not_supported_insert_pos, codepoint);
59 self.not_supported.truncate(Self::NOT_SUPPORTED_MAX_SZ);
60 }
61 }
62 ret
63 }
64
65 #[inline(always)]
66 fn has_codepoint(&mut self, font_codepoints: &[u32], codepoint: u32) -> bool {
67 match self.supported.binary_search(&codepoint) {
68 Ok(_) => true,
69 Err(supported_insert_pos) => match self.not_supported.binary_search(&codepoint) {
70 Ok(_) => false,
71 Err(not_supported_insert_pos) => self.unknown_has_codepoint(
72 font_codepoints,
73 codepoint,
74 supported_insert_pos,
75 not_supported_insert_pos,
76 ),
77 },
78 }
79 }
80}
81
82pub struct FontSystem {
84 locale: String,
86
87 db: fontdb::Database,
89
90 font_cache: HashMap<fontdb::ID, Option<Arc<Font>>>,
92
93 monospace_font_ids: Vec<fontdb::ID>,
95
96 per_script_monospace_font_ids: HashMap<[u8; 4], Vec<fontdb::ID>>,
100
101 font_codepoint_support_info_cache: HashMap<fontdb::ID, FontCachedCodepointSupportInfo>,
103
104 font_matches_cache: HashMap<FontMatchAttrs, Arc<Vec<FontMatchKey>>>,
106
107 pub(crate) shape_buffer: ShapeBuffer,
109
110 pub(crate) monospace_fallbacks_buffer: BTreeSet<MonospaceFallbackInfo>,
112
113 #[cfg(feature = "shape-run-cache")]
115 pub shape_run_cache: crate::ShapeRunCache,
116
117 pub(crate) dyn_fallback: Box<dyn Fallback>,
119
120 pub(crate) fallbacks: Fallbacks,
122}
123
124impl fmt::Debug for FontSystem {
125 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126 f.debug_struct("FontSystem")
127 .field("locale", &self.locale)
128 .field("db", &self.db)
129 .finish()
130 }
131}
132
133impl FontSystem {
134 const FONT_MATCHES_CACHE_SIZE_LIMIT: usize = 256;
135 pub fn new() -> Self {
143 Self::new_with_fonts(core::iter::empty())
144 }
145
146 pub fn new_with_fonts(fonts: impl IntoIterator<Item = fontdb::Source>) -> Self {
148 let locale = Self::get_locale();
149 log::debug!("Locale: {}", locale);
150
151 let mut db = fontdb::Database::new();
152
153 Self::load_fonts(&mut db, fonts.into_iter());
154
155 db.set_monospace_family("Noto Sans Mono");
157 db.set_sans_serif_family("Open Sans");
158 db.set_serif_family("DejaVu Serif");
159
160 Self::new_with_locale_and_db_and_fallback(locale, db, PlatformFallback)
161 }
162
163 pub fn new_with_locale_and_db_and_fallback(
165 locale: String,
166 db: fontdb::Database,
167 impl_fallback: impl Fallback + 'static,
168 ) -> Self {
169 let mut monospace_font_ids = db
170 .faces()
171 .filter(|face_info| {
172 face_info.monospaced && !face_info.post_script_name.contains("Emoji")
173 })
174 .map(|face_info| face_info.id)
175 .collect::<Vec<_>>();
176 monospace_font_ids.sort();
177
178 let mut per_script_monospace_font_ids: HashMap<[u8; 4], BTreeSet<fontdb::ID>> =
179 HashMap::default();
180
181 if cfg!(feature = "monospace_fallback") {
182 monospace_font_ids.iter().for_each(|&id| {
183 db.with_face_data(id, |font_data, face_index| {
184 let _ = ttf_parser::Face::parse(font_data, face_index).map(|face| {
185 face.tables()
186 .gpos
187 .into_iter()
188 .chain(face.tables().gsub)
189 .flat_map(|table| table.scripts)
190 .inspect(|script| {
191 per_script_monospace_font_ids
192 .entry(script.tag.to_bytes())
193 .or_default()
194 .insert(id);
195 })
196 });
197 });
198 });
199 }
200
201 let per_script_monospace_font_ids = per_script_monospace_font_ids
202 .into_iter()
203 .map(|(k, v)| (k, Vec::from_iter(v)))
204 .collect();
205
206 let fallbacks = Fallbacks::new(&impl_fallback, &[], &locale);
207
208 Self {
209 locale,
210 db,
211 monospace_font_ids,
212 per_script_monospace_font_ids,
213 font_cache: Default::default(),
214 font_matches_cache: Default::default(),
215 font_codepoint_support_info_cache: Default::default(),
216 monospace_fallbacks_buffer: BTreeSet::default(),
217 #[cfg(feature = "shape-run-cache")]
218 shape_run_cache: crate::ShapeRunCache::default(),
219 shape_buffer: ShapeBuffer::default(),
220 dyn_fallback: Box::new(impl_fallback),
221 fallbacks,
222 }
223 }
224
225 pub fn new_with_locale_and_db(locale: String, db: fontdb::Database) -> Self {
227 Self::new_with_locale_and_db_and_fallback(locale, db, PlatformFallback)
228 }
229
230 pub fn locale(&self) -> &str {
232 &self.locale
233 }
234
235 pub fn db(&self) -> &fontdb::Database {
237 &self.db
238 }
239
240 pub fn db_mut(&mut self) -> &mut fontdb::Database {
242 self.font_matches_cache.clear();
243 &mut self.db
244 }
245
246 pub fn into_locale_and_db(self) -> (String, fontdb::Database) {
248 (self.locale, self.db)
249 }
250
251 pub fn get_font(&mut self, id: fontdb::ID) -> Option<Arc<Font>> {
253 self.font_cache
254 .entry(id)
255 .or_insert_with(|| {
256 #[cfg(feature = "std")]
257 unsafe {
258 self.db.make_shared_face_data(id);
259 }
260 match Font::new(&self.db, id) {
261 Some(font) => Some(Arc::new(font)),
262 None => {
263 log::warn!(
264 "failed to load font '{}'",
265 self.db.face(id)?.post_script_name
266 );
267 None
268 }
269 }
270 })
271 .clone()
272 }
273
274 pub fn is_monospace(&self, id: fontdb::ID) -> bool {
275 self.monospace_font_ids.binary_search(&id).is_ok()
276 }
277
278 pub fn get_monospace_ids_for_scripts(
279 &self,
280 scripts: impl Iterator<Item = [u8; 4]>,
281 ) -> Vec<fontdb::ID> {
282 let mut ret = scripts
283 .filter_map(|script| self.per_script_monospace_font_ids.get(&script))
284 .flat_map(|ids| ids.iter().copied())
285 .collect::<Vec<_>>();
286 ret.sort();
287 ret.dedup();
288 ret
289 }
290
291 #[inline(always)]
292 pub fn get_font_supported_codepoints_in_word(
293 &mut self,
294 id: fontdb::ID,
295 word: &str,
296 ) -> Option<usize> {
297 self.get_font(id).map(|font| {
298 let code_points = font.unicode_codepoints();
299 let cache = self
300 .font_codepoint_support_info_cache
301 .entry(id)
302 .or_insert_with(FontCachedCodepointSupportInfo::new);
303 word.chars()
304 .filter(|ch| cache.has_codepoint(code_points, u32::from(*ch)))
305 .count()
306 })
307 }
308
309 pub fn get_font_matches(&mut self, attrs: &Attrs<'_>) -> Arc<Vec<FontMatchKey>> {
310 if self.font_matches_cache.len() >= Self::FONT_MATCHES_CACHE_SIZE_LIMIT {
312 log::trace!("clear font mache cache");
313 self.font_matches_cache.clear();
314 }
315
316 self.font_matches_cache
317 .entry(attrs.into())
319 .or_insert_with(|| {
320 #[cfg(all(feature = "std", not(target_arch = "wasm32")))]
321 let now = std::time::Instant::now();
322
323 let mut font_match_keys = self
324 .db
325 .faces()
326 .filter(|face| attrs.matches(face))
327 .map(|face| FontMatchKey {
328 font_weight_diff: attrs.weight.0.abs_diff(face.weight.0),
329 font_weight: face.weight.0,
330 id: face.id,
331 })
332 .collect::<Vec<_>>();
333
334 font_match_keys.sort();
336
337 #[cfg(all(feature = "std", not(target_arch = "wasm32")))]
338 {
339 let elapsed = now.elapsed();
340 log::debug!("font matches for {:?} in {:?}", attrs, elapsed);
341 }
342
343 Arc::new(font_match_keys)
344 })
345 .clone()
346 }
347
348 #[cfg(feature = "std")]
349 fn get_locale() -> String {
350 sys_locale::get_locale().unwrap_or_else(|| {
351 log::warn!("failed to get system locale, falling back to en-US");
352 String::from("en-US")
353 })
354 }
355
356 #[cfg(not(feature = "std"))]
357 fn get_locale() -> String {
358 String::from("en-US")
359 }
360
361 #[cfg(feature = "std")]
362 fn load_fonts(db: &mut fontdb::Database, fonts: impl Iterator<Item = fontdb::Source>) {
363 #[cfg(not(target_arch = "wasm32"))]
364 let now = std::time::Instant::now();
365
366 db.load_system_fonts();
367
368 for source in fonts {
369 db.load_font_source(source);
370 }
371
372 #[cfg(not(target_arch = "wasm32"))]
373 log::debug!(
374 "Parsed {} font faces in {}ms.",
375 db.len(),
376 now.elapsed().as_millis()
377 );
378 }
379
380 #[cfg(not(feature = "std"))]
381 fn load_fonts(db: &mut fontdb::Database, fonts: impl Iterator<Item = fontdb::Source>) {
382 for source in fonts {
383 db.load_font_source(source);
384 }
385 }
386}
387
388#[derive(Debug)]
390pub struct BorrowedWithFontSystem<'a, T> {
391 pub(crate) inner: &'a mut T,
392 pub(crate) font_system: &'a mut FontSystem,
393}
394
395impl<T> Deref for BorrowedWithFontSystem<'_, T> {
396 type Target = T;
397
398 fn deref(&self) -> &Self::Target {
399 self.inner
400 }
401}
402
403impl<T> DerefMut for BorrowedWithFontSystem<'_, T> {
404 fn deref_mut(&mut self) -> &mut Self::Target {
405 self.inner
406 }
407}