Skip to main content

text_typeset/font/
resolve.rs

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/// A resolved font face with all parameters needed for shaping and rasterization.
7#[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    /// Device pixel ratio applied during shaping and rasterization.
14    /// Shaping happens at `size_px * scale_factor` and results are
15    /// divided by `scale_factor` to produce logical-pixel metrics,
16    /// so downstream layout stays in logical space.
17    pub scale_factor: f32,
18    /// Resolved font weight (CSS-style 100–900). Used as the `wght`
19    /// variation axis when rasterizing variable fonts and as part of
20    /// the glyph cache key so different weights produce separate
21    /// rasterized bitmaps.
22    pub weight: u16,
23    /// Whether the text asks for italic. A face that has no italic draws it
24    /// with a synthetic slant (see `crate::font::synthesis`); the glyph cache
25    /// keys on it.
26    pub italic: bool,
27}
28
29/// Resolve a font from text formatting parameters.
30///
31/// The resolution order is:
32/// 1. If font_family is set, query by family name (with generic mapping)
33/// 2. Apply font_weight (or font_bold as weight 700)
34/// 3. Apply font_italic
35/// 4. Fall back to the default font if no match
36#[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    // `font_scale` is the per-document logical text-magnification factor
50    // (accessibility "grow all text"), distinct from `scale_factor` (HiDPI
51    // raster density). It multiplies the logical point size so advances, line
52    // heights, and content height all grow and the text reflows correctly.
53    let size_px = font_point_size
54        .map(|s| s as f32)
55        .unwrap_or(registry.default_size_px())
56        * font_scale;
57
58    // Try the specified family first.
59    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        // A family was explicitly requested but is not registered. Warn once
73        // (per family, per process) so the silent fall-back to the default
74        // font is visible — a theme that sets `family = "Roboto"` without
75        // registering Roboto would otherwise just render the default with no
76        // signal. This is the only place that warns; the lower-level
77        // `query_font` is also used for glyph-fallback probing, which misses
78        // by design and must stay quiet.
79        warn_unknown_family(family);
80    }
81
82    // Fall back to default font, but still try to match weight/italic
83    // by querying for a variant of the default font's family.
84    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
111/// Warn once per process per family when a requested font family is not
112/// registered, so the silent fall-back to the default font is visible.
113fn 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
128/// Check if a font has a glyph for the given character.
129/// Used for glyph fallback -trying other registered fonts when
130/// the primary font doesn't cover a character.
131pub 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
143/// Find a fallback font that has the given character.
144///
145/// Explicitly-registered faces are tried before OS-discovered ones, so a
146/// host's bundled fallback fonts win over arbitrary system fonts; system
147/// fonts (whose bytes load lazily on this scan) are the last resort.
148pub 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/// The weight, style and width a fallback face should match: those of the
178/// text it stands in for.
179#[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    /// The requested `weight`, with the style and width of `face_id`, the
188    /// face the text was resolved to. The weight comes from the request,
189    /// not the face: a variable face resolves every weight to one face.
190    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/// How a character is to be drawn, which decides the face fallback prefers.
203#[derive(Debug, Clone, Copy, PartialEq, Eq)]
204pub(crate) enum Presentation {
205    /// As text: a face that draws it plain first, then one that draws it in
206    /// colour. A symbol with no emoji presentation of its own (U+2764 with no
207    /// U+FE0F after it) stays a text symbol when a text face has it.
208    Text,
209    /// As an emoji: a face that draws it in colour first (see
210    /// [`crate::shaping::emoji`]), then one that draws it plain.
211    Emoji,
212}
213
214impl Presentation {
215    /// 0 for the glyph this presentation wants, 1 for the one it makes do
216    /// with.
217    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
225/// Find a face other than those in `exclude` that has a glyph for `ch`,
226/// and say how that glyph is drawn.
227///
228/// Faces are visited explicitly-registered first, then system faces, and for
229/// [`Presentation::Emoji`] the faces whose family name says "emoji" before
230/// both: every colour emoji font in use (Apple Color Emoji, Segoe UI Emoji,
231/// Noto Color Emoji, Twemoji) says so in its name, and asking the metadata
232/// first finds it without opening, one by one, the system faces that sit
233/// before it and happen to have a monochrome glyph.
234///
235/// The first face whose glyph is drawn as the presentation wants (see
236/// [`Presentation`]) is taken. Failing that, the first face that draws the
237/// glyph some other way, so that the system faces need not all be opened,
238/// which loads every one of them, to find that none draws it as wanted.
239///
240/// The face taken is then swapped for the face of its family that matches
241/// `style` (see [`FontRegistry::family_face_matching`]), when that face has
242/// the glyph too and draws it as well: the first face found is whichever
243/// file the system lists first, Bold as readily as Regular.
244///
245/// For text, between the explicitly-registered faces and the system ones,
246/// the families of `preferred` are asked in turn, each for its face matching
247/// `style`, and the first that draws the glyph plain is taken: the faces the
248/// system ships for the character's script and language (see
249/// [`crate::font::script_fallback`]), which the first system face to cover
250/// it often is not. A face the host registered still wins over them.
251pub(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        // A face the rasterizer cannot draw would put blanks where the text is.
273        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    // The first face seen that draws the glyph, but not as wanted.
294    let mut second: Option<(FontFaceId, GlyphPaint)> = None;
295    for &pass in passes {
296        // The table comes after the faces the host registered, so an app that
297        // ships its own font for a script keeps it, and before the system's.
298        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
342/// Whether `face_id` has a glyph for every character of `text` that needs
343/// one: whitespace, controls and default-ignorable characters (variation
344/// selectors, zero-width joiners) are skipped.
345pub(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
359/// The default-ignorable characters a font need not map: they shape to
360/// nothing whether it does or not.
361fn 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
376/// Convert TextFormat weight fields to a u16 weight value for fontdb.
377fn 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 // Normal weight
385}