1use crate::font::color::{GlyphPaint, glyph_paint};
2use crate::font::registry::FontRegistry;
3use crate::font::script_fallback::{ScriptContext, preferred_families};
4use crate::types::FontFaceId;
5
6#[non_exhaustive]
8pub struct ResolvedFont {
9 pub font_face_id: FontFaceId,
10 pub size_px: f32,
11 pub face_index: u32,
12 pub swash_cache_key: swash::CacheKey,
13 pub scale_factor: f32,
18 pub weight: u16,
23 pub italic: bool,
27}
28
29#[allow(clippy::too_many_arguments)]
37pub fn resolve_font(
38 registry: &FontRegistry,
39 font_family: Option<&str>,
40 font_weight: Option<u32>,
41 font_bold: Option<bool>,
42 font_italic: Option<bool>,
43 font_point_size: Option<u32>,
44 scale_factor: f32,
45 font_scale: f32,
46) -> Option<ResolvedFont> {
47 let weight = resolve_weight(font_weight, font_bold);
48 let italic = font_italic.unwrap_or(false);
49 let size_px = font_point_size
54 .map(|s| s as f32)
55 .unwrap_or(registry.default_size_px())
56 * font_scale;
57
58 if let Some(family) = font_family {
60 if let Some(face_id) = registry.query_font(family, weight, italic) {
61 let entry = registry.get(face_id)?;
62 return Some(ResolvedFont {
63 font_face_id: face_id,
64 size_px,
65 face_index: entry.face_index,
66 swash_cache_key: entry.swash_cache_key,
67 scale_factor,
68 weight,
69 italic,
70 });
71 }
72 warn_unknown_family(family);
80 }
81
82 let default_id = registry.default_font()?;
85 if (weight != 400 || italic)
86 && let Some(variant_id) = registry.query_variant(default_id, weight, italic)
87 {
88 let variant_entry = registry.get(variant_id)?;
89 return Some(ResolvedFont {
90 font_face_id: variant_id,
91 size_px,
92 face_index: variant_entry.face_index,
93 swash_cache_key: variant_entry.swash_cache_key,
94 scale_factor,
95 weight,
96 italic,
97 });
98 }
99 let entry = registry.get(default_id)?;
100 Some(ResolvedFont {
101 font_face_id: default_id,
102 size_px,
103 face_index: entry.face_index,
104 swash_cache_key: entry.swash_cache_key,
105 scale_factor,
106 weight,
107 italic,
108 })
109}
110
111fn warn_unknown_family(family: &str) {
114 use std::collections::HashSet;
115 use std::sync::{LazyLock, Mutex};
116 static WARNED: LazyLock<Mutex<HashSet<String>>> = LazyLock::new(|| Mutex::new(HashSet::new()));
117 if let Ok(mut warned) = WARNED.lock()
118 && warned.insert(family.to_string())
119 {
120 eprintln!(
121 "text-typeset: font family {family:?} is not registered; falling back \
122 to the default font. Register it (e.g. via the host application's font \
123 registrar) before shaping."
124 );
125 }
126}
127
128pub fn font_has_glyph(registry: &FontRegistry, face_id: FontFaceId, ch: char) -> bool {
132 let entry = match registry.get(face_id) {
133 Some(e) => e,
134 None => return false,
135 };
136 let font_ref = match swash::FontRef::from_index(entry.bytes(), entry.face_index as usize) {
137 Some(f) => f,
138 None => return false,
139 };
140 font_ref.charmap().map(ch) != 0
141}
142
143pub fn find_fallback_font(
149 registry: &FontRegistry,
150 ch: char,
151 exclude: FontFaceId,
152) -> Option<FontFaceId> {
153 let weight = registry
154 .get(exclude)
155 .and_then(|entry| registry.fontdb_weight(entry.fontdb_id))
156 .unwrap_or(400);
157 let style = FaceStyle::of_face(registry, exclude, weight);
158 let mut text = [0; 4];
159 let preferred = preferred_families(
160 ch,
161 &ScriptContext::new(ch.encode_utf8(&mut text), None),
162 0,
163 registry.default_language(),
164 registry.fallback_platform(),
165 );
166 find_fallback_face(
167 registry,
168 ch,
169 Presentation::Text,
170 style,
171 &[exclude],
172 preferred,
173 )
174 .map(|(face, _)| face)
175}
176
177#[derive(Debug, Clone, Copy, PartialEq)]
180pub(crate) struct FaceStyle {
181 pub(crate) weight: u16,
182 pub(crate) style: fontdb::Style,
183 pub(crate) stretch: fontdb::Stretch,
184}
185
186impl FaceStyle {
187 pub(crate) fn of_face(registry: &FontRegistry, face_id: FontFaceId, weight: u16) -> Self {
191 let (style, stretch) = registry
192 .face_style(face_id)
193 .unwrap_or((fontdb::Style::Normal, fontdb::Stretch::Normal));
194 Self {
195 weight,
196 style,
197 stretch,
198 }
199 }
200}
201
202#[derive(Debug, Clone, Copy, PartialEq, Eq)]
204pub(crate) enum Presentation {
205 Text,
209 Emoji,
212}
213
214impl Presentation {
215 fn rank(self, paint: GlyphPaint) -> u8 {
218 match (self, paint) {
219 (Presentation::Text, GlyphPaint::Plain) | (Presentation::Emoji, GlyphPaint::Color) => 0,
220 (Presentation::Text, GlyphPaint::Color) | (Presentation::Emoji, GlyphPaint::Plain) => 1,
221 }
222 }
223}
224
225pub(crate) fn find_fallback_face(
252 registry: &FontRegistry,
253 ch: char,
254 presentation: Presentation,
255 style: FaceStyle,
256 exclude: &[FontFaceId],
257 preferred: &[&str],
258) -> Option<(FontFaceId, GlyphPaint)> {
259 #[derive(Clone, Copy, PartialEq)]
260 enum Pass {
261 EmojiNamed,
262 Explicit,
263 System,
264 }
265 let passes: &[Pass] = match presentation {
266 Presentation::Text => &[Pass::Explicit, Pass::System],
267 Presentation::Emoji => &[Pass::EmojiNamed, Pass::Explicit, Pass::System],
268 };
269
270 let glyph_paint_of = |face_id: FontFaceId| {
271 let entry = registry.get(face_id)?;
272 if !entry.color_tables().drawable() {
274 return None;
275 }
276 let glyph = swash::FontRef::from_index(entry.bytes(), entry.face_index as usize)?
277 .charmap()
278 .map(ch);
279 (glyph != 0).then(|| glyph_paint(entry, glyph))
280 };
281 let matching = |(face_id, paint): (FontFaceId, GlyphPaint)| {
282 registry
283 .family_face_matching(face_id, style.weight, style.style, style.stretch)
284 .filter(|&better| better != face_id && !exclude.contains(&better))
285 .and_then(|better| {
286 let better_paint = glyph_paint_of(better)?;
287 (presentation.rank(better_paint) <= presentation.rank(paint))
288 .then_some((better, better_paint))
289 })
290 .unwrap_or((face_id, paint))
291 };
292
293 let mut second: Option<(FontFaceId, GlyphPaint)> = None;
295 for &pass in passes {
296 if pass == Pass::System
299 && presentation == Presentation::Text
300 && let Some(found) = preferred.iter().find_map(|family| {
301 let face_id =
302 registry.family_face(family, style.weight, style.style, style.stretch)?;
303 (!exclude.contains(&face_id) && glyph_paint_of(face_id) == Some(GlyphPaint::Plain))
304 .then_some((face_id, GlyphPaint::Plain))
305 })
306 {
307 return Some(found);
308 }
309 for (face_id, entry) in registry.all_entries() {
310 if exclude.contains(&face_id) {
311 continue;
312 }
313 let visits = match pass {
314 Pass::EmojiNamed => registry.is_emoji_family(face_id),
315 Pass::Explicit => !entry.is_system,
316 Pass::System => entry.is_system,
317 };
318 if !visits || !entry.color_tables().drawable() {
319 continue;
320 }
321 let Some(glyph) = swash::FontRef::from_index(entry.bytes(), entry.face_index as usize)
322 .map(|font_ref| font_ref.charmap().map(ch))
323 .filter(|&glyph| glyph != 0)
324 else {
325 continue;
326 };
327 let paint = glyph_paint(entry, glyph);
328 match presentation.rank(paint) {
329 0 => return Some(matching((face_id, paint))),
330 1 if pass == Pass::System => {
331 return Some(matching(second.unwrap_or((face_id, paint))));
332 }
333 _ => {
334 second.get_or_insert((face_id, paint));
335 }
336 }
337 }
338 }
339 second.map(matching)
340}
341
342pub(crate) fn face_covers(registry: &FontRegistry, face_id: FontFaceId, text: &str) -> bool {
346 let Some(entry) = registry.get(face_id) else {
347 return false;
348 };
349 let Some(font_ref) = swash::FontRef::from_index(entry.bytes(), entry.face_index as usize)
350 else {
351 return false;
352 };
353 let charmap = font_ref.charmap();
354 text.chars()
355 .filter(|&c| !c.is_whitespace() && !c.is_control() && !is_default_ignorable(c))
356 .all(|c| charmap.map(c) != 0)
357}
358
359fn is_default_ignorable(c: char) -> bool {
362 matches!(
363 c,
364 '\u{00AD}'
365 | '\u{034F}'
366 | '\u{180B}'..='\u{180F}'
367 | '\u{200B}'..='\u{200F}'
368 | '\u{202A}'..='\u{202E}'
369 | '\u{2060}'..='\u{206F}'
370 | '\u{FE00}'..='\u{FE0F}'
371 | '\u{FEFF}'
372 | '\u{E0000}'..='\u{E0FFF}'
373 )
374}
375
376fn resolve_weight(font_weight: Option<u32>, font_bold: Option<bool>) -> u16 {
378 if let Some(w) = font_weight {
379 return w.min(1000) as u16;
380 }
381 if font_bold == Some(true) {
382 return 700;
383 }
384 400 }