1use std::sync::Arc;
13
14use mln_style::hash::{HashMap, HashSet};
15use mln_style::i18n;
16
17use crate::text::FontFile;
18use crate::text::font_name::{self, FontName};
19use crate::text::font_stack::FontStack;
20use crate::text::glyph::FontFace;
21use crate::text::local_fonts::FontChooser;
22use crate::text::system_fonts::source::{self, Source};
23use crate::text::system_fonts::{Finder, Query, languages, system};
24
25#[derive(Clone, Copy, Debug, Default)]
28pub struct SystemFonts;
29
30impl FontChooser for SystemFonts {
31 fn choose(&self, font_stack: &FontStack, cluster: &[char]) -> Option<FontFace> {
32 let mut fonts = system().fonts.as_ref()?.lock();
33 Some(font_for(&mut fonts, font_stack, cluster)?.face.clone())
34 }
35}
36
37pub(crate) struct SystemFont {
39 file: FontFile,
40 face: FontFace,
41}
42
43impl SystemFont {
44 fn draws(&self, cluster: &[char]) -> bool {
45 cluster.iter().all(|&c| self.file.has_char(c))
46 }
47}
48
49pub(crate) struct Fonts {
51 pub(crate) finder: Finder,
52 files: source::Files,
53 named: HashMap<String, Option<Arc<SystemFont>>>,
55 picked: HashMap<(FontStack, u32), Vec<Arc<SystemFont>>>,
58 missing: HashSet<(FontStack, Vec<char>)>,
60}
61
62impl Fonts {
63 pub(crate) fn new(finder: Finder) -> Self {
65 Fonts {
66 finder,
67 files: source::Files::default(),
68 named: HashMap::default(),
69 picked: HashMap::default(),
70 missing: HashSet::default(),
71 }
72 }
73}
74
75fn font_for(fonts: &mut Fonts, font_stack: &FontStack, cluster: &[char]) -> Option<Arc<SystemFont>> {
78 let &c = cluster.first()?;
79 let names = names(font_stack);
80 let mut named = Vec::with_capacity(names.len());
81 for (name, parsed) in &names {
82 let font = fonts.named.entry((*name).to_owned()).or_insert_with(|| {
83 first_drawing(&mut fonts.files, named_fonts(&mut fonts.finder, name, parsed), &[' '], parsed.weight)
84 });
85 named.push(font.clone());
86 }
87 let key = (font_stack.clone(), class(c));
88 let picked = fonts.picked.get(&key).map_or(&[][..], Vec::as_slice);
89 if let Some(font) = first_with(&named, picked, |font| font.draws(cluster)) {
90 return Some(Arc::clone(font));
91 }
92 if !fonts.missing.contains(&(font_stack.clone(), cluster.to_vec())) {
93 let first = names.first().map_or(FontName { family: "", weight: 400, italic: false }, |(_, parsed)| *parsed);
94 let candidates = picked_fonts(&mut fonts.finder, &first, c);
95 if let Some(font) = first_drawing(&mut fonts.files, candidates, cluster, first.weight) {
96 fonts.picked.entry(key).or_default().push(Arc::clone(&font));
97 return Some(font);
98 }
99 fonts.missing.insert((font_stack.clone(), cluster.to_vec()));
100 }
101 if cluster.len() > 1 { font_for(fonts, font_stack, &[c]) } else { None }
104}
105
106fn first_with<'a, F>(named: &'a [Option<F>], picked: &'a [F], has: impl Fn(&F) -> bool) -> Option<&'a F> {
109 named.iter().flatten().chain(picked).find(|font| has(font))
110}
111
112fn first_drawing(
115 files: &mut source::Files,
116 candidates: Vec<(String, Source)>,
117 cluster: &[char],
118 weight: u16,
119) -> Option<Arc<SystemFont>> {
120 candidates.into_iter().find_map(|(_, source)| {
121 let data = files.data(&source)?;
122 let file = FontFile::new(data.clone())?;
123 let face = FontFace::device(&source.url(), weight, data);
124 let font = SystemFont { file, face };
125 font.draws(cluster).then(|| Arc::new(font))
126 })
127}
128
129fn names(font_stack: &FontStack) -> Vec<(&str, FontName<'_>)> {
131 font_stack
132 .iter()
133 .filter(|name| !name.trim().is_empty())
134 .map(|name| (name.as_str(), font_name::parse(name)))
135 .collect()
136}
137
138fn class(c: char) -> u32 {
143 let ideograph = i18n::allows_fixed_width_glyph_generation(c);
144 if ideograph { u32::MAX } else { u32::from(c) >> 8 }
145}
146
147pub(crate) fn named_fonts(finder: &mut Finder, name: &str, parsed: &FontName<'_>) -> Vec<(String, Source)> {
150 let query = Query {
153 name: Some(name),
154 family: Some(parsed.family),
155 probe: ' ',
156 languages: &[],
157 weight: parsed.weight,
158 italic: parsed.italic,
159 };
160 let mut candidates = drawn(finder.candidates(&query), ' ', parsed.weight);
161 candidates.retain(|(family, ..)| family.eq_ignore_ascii_case(parsed.family));
162 nearest(candidates, parsed.weight)
163}
164
165pub(crate) fn picked_fonts(finder: &mut Finder, first: &FontName<'_>, c: char) -> Vec<(String, Source)> {
169 let languages = if class(c) == u32::MAX { languages::for_ideographs(&system().preferred) } else { Vec::new() };
170 let query = Query {
171 name: None,
172 family: Some(first.family).filter(|family| !family.is_empty()),
173 probe: c,
174 languages: &languages,
175 weight: first.weight,
176 italic: first.italic,
177 };
178 nearest(drawn(finder.candidates(&query), c, first.weight), first.weight)
179}
180
181pub(crate) const MAX_CANDIDATES: usize = 16;
183
184fn drawn(candidates: Vec<(String, Source)>, c: char, weight: u16) -> Vec<(String, Source, u16)> {
187 candidates
188 .into_iter()
189 .take(MAX_CANDIDATES)
190 .filter_map(|(family, source)| {
191 let drawn = source.drawn_weight(c, weight)?;
192 Some((family, source, drawn))
193 })
194 .collect()
195}
196
197fn nearest(mut candidates: Vec<(String, Source, u16)>, weight: u16) -> Vec<(String, Source)> {
200 candidates.sort_by_key(|(_, _, drawn)| drawn.abs_diff(weight));
201 candidates.into_iter().map(|(family, source, _)| (family, source)).collect()
202}
203
204#[cfg(test)]
205mod tests {
206 use std::num::NonZeroU16;
210
211 use super::{SystemFonts, class, first_with, named_fonts, picked_fonts};
212 use crate::text::glyph::{Glyph, GlyphIDType};
213 use crate::text::local_fonts::FontChooser;
214 use crate::text::system_fonts::{Finder, system};
215 use crate::text::{Shaper, font_name};
216
217 fn stack(names: &[&str]) -> Vec<String> {
218 names.iter().map(|name| (*name).to_owned()).collect()
219 }
220
221 fn with_finder<R>(f: impl FnOnce(&mut Finder) -> R) -> Option<R> {
223 Some(f(&mut system().fonts.as_ref()?.lock().finder))
224 }
225
226 fn chosen_glyph(font_stack: &[&str], c: char) -> Option<Glyph> {
228 let face = SystemFonts.choose(&stack(font_stack), &[c])?;
229 let data = face.data.expect("a device face holds its file");
230 let shaper = Shaper::at_weight(GlyphIDType::face(NonZeroU16::MIN), data, f32::from(face.weight));
231 let id = shaper.glyph_of(c).unwrap_or_else(|| panic!("no glyph for {c} in {}", face.url));
232 Some(shaper.rasterize_glyph(id))
233 }
234
235 #[test]
236 fn a_picked_font_has_the_character() {
237 for c in ['a', 'ä', 'Ж', 'α', 'א', 'ب', '中', 'あ', '한', 'ሀ'] {
238 for name in ["", "Open Sans Regular", "Noto Sans Bold"] {
239 let found = with_finder(|finder| picked_fonts(finder, &font_name::parse(name), c).into_iter().next());
240 let found = found.flatten();
241 println!("{c} for {name:?}: {found:?}");
242 if let Some((_, source)) = found {
243 assert!(source.drawn_weight(c, 400).is_some(), "{c} for {name:?}");
244 }
245 }
246 }
247 }
248
249 #[test]
250 fn a_name_gets_its_family_if_the_system_has_it() {
251 with_finder(|finder| {
252 let Some((family, _)) = picked_fonts(finder, &font_name::parse(""), 'a').into_iter().next() else {
254 return;
255 };
256 let name = format!("{family} Bold");
257 let found = named_fonts(finder, &name, &font_name::parse(&name));
258 println!("{name}: {:?}", found.first());
259 assert_ne!(found.len(), 0);
260 assert!(found.iter().all(|(found, _)| found.eq_ignore_ascii_case(&family)));
261 let missing = "No Such Font Regular";
262 assert_eq!(named_fonts(finder, missing, &font_name::parse(missing)).len(), 0);
263 });
264 }
265
266 #[test]
269 fn the_stacks_fonts_come_first_in_order() {
270 let ascii = Some("ab");
271 let broad = Some("abé");
272 let picked = ["abéz"];
273 let has = |c: char| move |font: &&str| font.contains(c);
274 assert_eq!(first_with(&[ascii, broad], &picked, has('a')), Some(&"ab"));
275 assert_eq!(first_with(&[ascii, broad], &picked, has('é')), Some(&"abé"));
276 assert_eq!(first_with(&[None, broad], &picked, has('a')), Some(&"abé"));
277 assert_eq!(first_with(&[ascii, broad], &picked, has('z')), Some(&"abéz"));
278 assert_eq!(first_with(&[ascii, broad], &picked, has('q')), None);
279 }
280
281 #[test]
282 fn a_chosen_face_draws_its_character() {
283 for c in ['a', '中', '한'] {
284 let glyph = chosen_glyph(&["Open Sans Regular"], c);
285 println!("{c}: {:?}", glyph.as_ref().map(|glyph| glyph.metrics));
286 if let Some(glyph) = glyph {
287 assert!(glyph.metrics.advance > 0);
288 assert!(glyph.bitmap.data.iter().any(|&alpha| alpha > 0));
289 }
290 }
291 }
292
293 #[test]
296 fn a_bold_name_draws_bolder_where_the_system_has_a_bolder_font() {
297 for c in ['a', 'Ж', 'α', 'א', 'ب'] {
298 let picked = with_finder(|finder| picked_fonts(finder, &font_name::parse(""), c).into_iter().next());
299 let Some((family, _)) = picked.flatten() else { continue };
300 let ink = |name: &str| {
301 let glyph = chosen_glyph(&[name], c)?;
302 Some(glyph.bitmap.data.iter().map(|&alpha| u64::from(alpha)).sum::<u64>())
303 };
304 let drawn = |name: &str| {
305 let found = with_finder(|finder| named_fonts(finder, name, &font_name::parse(name)).into_iter().next());
306 let (_, source) = found.flatten()?;
307 Some((source.drawn_weight(c, font_name::parse(name).weight)?, source))
308 };
309 let (regular, bold) = (format!("{family} Regular"), format!("{family} Bold"));
310 let (Some((regular_weight, _)), Some((bold_weight, source))) = (drawn(®ular), drawn(&bold)) else {
311 continue;
312 };
313 println!("{c}: {regular_weight} {:?}, {bold_weight} {:?} from {source:?}", ink(®ular), ink(&bold));
314 if bold_weight > regular_weight {
315 assert!(ink(&bold) > ink(®ular), "{c} in {family}");
316 }
317 }
318 }
319
320 #[test]
321 fn cjk_characters_share_a_class() {
322 assert_eq!(class('中'), class('あ'));
323 assert_eq!(class('中'), class('한'));
324 assert_eq!(class('a'), class('ä'));
325 assert_ne!(class('a'), class('Ж'));
326 }
327}