use crate::font::color::{GlyphPaint, glyph_paint};
use crate::font::registry::FontRegistry;
use crate::font::script_fallback::{ScriptContext, preferred_families};
use crate::types::FontFaceId;
#[non_exhaustive]
pub struct ResolvedFont {
pub font_face_id: FontFaceId,
pub size_px: f32,
pub face_index: u32,
pub swash_cache_key: swash::CacheKey,
pub scale_factor: f32,
pub weight: u16,
pub italic: bool,
}
#[allow(clippy::too_many_arguments)]
pub fn resolve_font(
registry: &FontRegistry,
font_family: Option<&str>,
font_weight: Option<u32>,
font_bold: Option<bool>,
font_italic: Option<bool>,
font_point_size: Option<u32>,
scale_factor: f32,
font_scale: f32,
) -> Option<ResolvedFont> {
let weight = resolve_weight(font_weight, font_bold);
let italic = font_italic.unwrap_or(false);
let size_px = font_point_size
.map(|s| s as f32)
.unwrap_or(registry.default_size_px())
* font_scale;
if let Some(family) = font_family {
if let Some(face_id) = registry.query_font(family, weight, italic) {
let entry = registry.get(face_id)?;
return Some(ResolvedFont {
font_face_id: face_id,
size_px,
face_index: entry.face_index,
swash_cache_key: entry.swash_cache_key,
scale_factor,
weight,
italic,
});
}
warn_unknown_family(family);
}
let default_id = registry.default_font()?;
if (weight != 400 || italic)
&& let Some(variant_id) = registry.query_variant(default_id, weight, italic)
{
let variant_entry = registry.get(variant_id)?;
return Some(ResolvedFont {
font_face_id: variant_id,
size_px,
face_index: variant_entry.face_index,
swash_cache_key: variant_entry.swash_cache_key,
scale_factor,
weight,
italic,
});
}
let entry = registry.get(default_id)?;
Some(ResolvedFont {
font_face_id: default_id,
size_px,
face_index: entry.face_index,
swash_cache_key: entry.swash_cache_key,
scale_factor,
weight,
italic,
})
}
fn warn_unknown_family(family: &str) {
use std::collections::HashSet;
use std::sync::{LazyLock, Mutex};
static WARNED: LazyLock<Mutex<HashSet<String>>> = LazyLock::new(|| Mutex::new(HashSet::new()));
if let Ok(mut warned) = WARNED.lock()
&& warned.insert(family.to_string())
{
eprintln!(
"text-typeset: font family {family:?} is not registered; falling back \
to the default font. Register it (e.g. via the host application's font \
registrar) before shaping."
);
}
}
pub fn font_has_glyph(registry: &FontRegistry, face_id: FontFaceId, ch: char) -> bool {
let entry = match registry.get(face_id) {
Some(e) => e,
None => return false,
};
let font_ref = match swash::FontRef::from_index(entry.bytes(), entry.face_index as usize) {
Some(f) => f,
None => return false,
};
font_ref.charmap().map(ch) != 0
}
pub fn find_fallback_font(
registry: &FontRegistry,
ch: char,
exclude: FontFaceId,
) -> Option<FontFaceId> {
let weight = registry
.get(exclude)
.and_then(|entry| registry.fontdb_weight(entry.fontdb_id))
.unwrap_or(400);
let style = FaceStyle::of_face(registry, exclude, weight);
let mut text = [0; 4];
let preferred = preferred_families(
ch,
&ScriptContext::new(ch.encode_utf8(&mut text), None),
0,
registry.default_language(),
registry.fallback_platform(),
);
find_fallback_face(
registry,
ch,
Presentation::Text,
style,
&[exclude],
preferred,
)
.map(|(face, _)| face)
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct FaceStyle {
pub(crate) weight: u16,
pub(crate) style: fontdb::Style,
pub(crate) stretch: fontdb::Stretch,
}
impl FaceStyle {
pub(crate) fn of_face(registry: &FontRegistry, face_id: FontFaceId, weight: u16) -> Self {
let (style, stretch) = registry
.face_style(face_id)
.unwrap_or((fontdb::Style::Normal, fontdb::Stretch::Normal));
Self {
weight,
style,
stretch,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Presentation {
Text,
Emoji,
}
impl Presentation {
fn rank(self, paint: GlyphPaint) -> u8 {
match (self, paint) {
(Presentation::Text, GlyphPaint::Plain) | (Presentation::Emoji, GlyphPaint::Color) => 0,
(Presentation::Text, GlyphPaint::Color) | (Presentation::Emoji, GlyphPaint::Plain) => 1,
}
}
}
pub(crate) fn find_fallback_face(
registry: &FontRegistry,
ch: char,
presentation: Presentation,
style: FaceStyle,
exclude: &[FontFaceId],
preferred: &[&str],
) -> Option<(FontFaceId, GlyphPaint)> {
#[derive(Clone, Copy, PartialEq)]
enum Pass {
EmojiNamed,
Explicit,
System,
}
let passes: &[Pass] = match presentation {
Presentation::Text => &[Pass::Explicit, Pass::System],
Presentation::Emoji => &[Pass::EmojiNamed, Pass::Explicit, Pass::System],
};
let glyph_paint_of = |face_id: FontFaceId| {
let entry = registry.get(face_id)?;
if !entry.color_tables().drawable() {
return None;
}
let glyph = swash::FontRef::from_index(entry.bytes(), entry.face_index as usize)?
.charmap()
.map(ch);
(glyph != 0).then(|| glyph_paint(entry, glyph))
};
let matching = |(face_id, paint): (FontFaceId, GlyphPaint)| {
registry
.family_face_matching(face_id, style.weight, style.style, style.stretch)
.filter(|&better| better != face_id && !exclude.contains(&better))
.and_then(|better| {
let better_paint = glyph_paint_of(better)?;
(presentation.rank(better_paint) <= presentation.rank(paint))
.then_some((better, better_paint))
})
.unwrap_or((face_id, paint))
};
let mut second: Option<(FontFaceId, GlyphPaint)> = None;
for &pass in passes {
if pass == Pass::System
&& presentation == Presentation::Text
&& let Some(found) = preferred.iter().find_map(|family| {
let face_id =
registry.family_face(family, style.weight, style.style, style.stretch)?;
(!exclude.contains(&face_id) && glyph_paint_of(face_id) == Some(GlyphPaint::Plain))
.then_some((face_id, GlyphPaint::Plain))
})
{
return Some(found);
}
for (face_id, entry) in registry.all_entries() {
if exclude.contains(&face_id) {
continue;
}
let visits = match pass {
Pass::EmojiNamed => registry.is_emoji_family(face_id),
Pass::Explicit => !entry.is_system,
Pass::System => entry.is_system,
};
if !visits || !entry.color_tables().drawable() {
continue;
}
let Some(glyph) = swash::FontRef::from_index(entry.bytes(), entry.face_index as usize)
.map(|font_ref| font_ref.charmap().map(ch))
.filter(|&glyph| glyph != 0)
else {
continue;
};
let paint = glyph_paint(entry, glyph);
match presentation.rank(paint) {
0 => return Some(matching((face_id, paint))),
1 if pass == Pass::System => {
return Some(matching(second.unwrap_or((face_id, paint))));
}
_ => {
second.get_or_insert((face_id, paint));
}
}
}
}
second.map(matching)
}
pub(crate) fn face_covers(registry: &FontRegistry, face_id: FontFaceId, text: &str) -> bool {
let Some(entry) = registry.get(face_id) else {
return false;
};
let Some(font_ref) = swash::FontRef::from_index(entry.bytes(), entry.face_index as usize)
else {
return false;
};
let charmap = font_ref.charmap();
text.chars()
.filter(|&c| !c.is_whitespace() && !c.is_control() && !is_default_ignorable(c))
.all(|c| charmap.map(c) != 0)
}
fn is_default_ignorable(c: char) -> bool {
matches!(
c,
'\u{00AD}'
| '\u{034F}'
| '\u{180B}'..='\u{180F}'
| '\u{200B}'..='\u{200F}'
| '\u{202A}'..='\u{202E}'
| '\u{2060}'..='\u{206F}'
| '\u{FE00}'..='\u{FE0F}'
| '\u{FEFF}'
| '\u{E0000}'..='\u{E0FFF}'
)
}
fn resolve_weight(font_weight: Option<u32>, font_bold: Option<bool>) -> u16 {
if let Some(w) = font_weight {
return w.min(1000) as u16;
}
if font_bold == Some(true) {
return 700;
}
400 }