#![expect(unsafe_code, reason = "the NDK's font API and JNI are the FFI here")]
use std::ffi::{CStr, CString, c_char, c_void};
use std::os::unix::ffi::OsStrExt;
use std::path::PathBuf;
use std::sync::OnceLock;
use jni::objects::JString;
use jni::{EnvUnowned, Outcome, jni_sig, jni_str};
use libloading::Library;
use crate::text::system_fonts::Query;
use crate::text::system_fonts::source::Source;
static LANGUAGES: OnceLock<Vec<String>> = OnceLock::new();
pub unsafe fn init(jni_env: *mut c_void) {
let mut env = unsafe { EnvUnowned::from_raw(jni_env.cast()) };
let outcome = env
.with_env(|env| -> Result<String, jni::errors::Error> {
let read = (|| {
let list = env
.call_static_method(
jni_str!("android/os/LocaleList"),
jni_str!("getDefault"),
jni_sig!("()Landroid/os/LocaleList;"),
&[],
)?
.l()?;
let tags =
env.call_method(&list, jni_str!("toLanguageTags"), jni_sig!("()Ljava/lang/String;"), &[])?.l()?;
env.cast_local::<JString>(tags)?.try_to_string(env)
})();
if env.exception_check() {
env.exception_clear();
}
read
})
.into_outcome();
let languages = match outcome {
Outcome::Ok(tags) => tags.split(',').filter(|tag| !tag.is_empty()).map(str::to_owned).collect(),
Outcome::Err(_) | Outcome::Panic(_) => Vec::new(),
};
let _ = LANGUAGES.set(languages);
}
pub(crate) fn languages() -> Option<Vec<String>> {
LANGUAGES.get().filter(|languages| !languages.is_empty()).cloned()
}
struct SystemFont {
family: String,
weight: u16,
italic: bool,
source: Source,
}
pub(crate) struct FontMatcher {
create: unsafe extern "C" fn() -> *mut c_void,
destroy: unsafe extern "C" fn(*mut c_void),
set_locales: unsafe extern "C" fn(*mut c_void, *const c_char),
set_style: unsafe extern "C" fn(*mut c_void, u16, bool),
matches: unsafe extern "C" fn(*const c_void, *const c_char, *const u16, u32, *mut u32) -> *mut c_void,
close: unsafe extern "C" fn(*mut c_void),
file_path: unsafe extern "C" fn(*const c_void) -> *const c_char,
collection_index: unsafe extern "C" fn(*const c_void) -> usize,
font_weight: unsafe extern "C" fn(*const c_void) -> u16,
font_is_italic: unsafe extern "C" fn(*const c_void) -> bool,
iterator_open: unsafe extern "C" fn() -> *mut c_void,
iterator_next: unsafe extern "C" fn(*mut c_void) -> *mut c_void,
iterator_close: unsafe extern "C" fn(*mut c_void),
fonts: OnceLock<Vec<SystemFont>>,
_library: Library,
}
impl FontMatcher {
pub(crate) fn new() -> Option<FontMatcher> {
LANGUAGES.get()?;
Self::load()
}
fn load() -> Option<FontMatcher> {
let library = unsafe { Library::new("libandroid.so") }.ok()?;
macro_rules! symbol {
($name:literal) => {
*unsafe { library.get(concat!($name, "\0").as_bytes()) }.ok()?
};
}
Some(FontMatcher {
create: symbol!("AFontMatcher_create"),
destroy: symbol!("AFontMatcher_destroy"),
set_locales: symbol!("AFontMatcher_setLocales"),
set_style: symbol!("AFontMatcher_setStyle"),
matches: symbol!("AFontMatcher_match"),
close: symbol!("AFont_close"),
file_path: symbol!("AFont_getFontFilePath"),
collection_index: symbol!("AFont_getCollectionIndex"),
font_weight: symbol!("AFont_getWeight"),
font_is_italic: symbol!("AFont_isItalic"),
iterator_open: symbol!("ASystemFontIterator_open"),
iterator_next: symbol!("ASystemFontIterator_next"),
iterator_close: symbol!("ASystemFontIterator_close"),
fonts: OnceLock::new(),
_library: library,
})
}
pub(crate) fn prepare(&self) {
self.fonts();
}
pub(crate) fn candidates(&self, query: &Query<'_>) -> Vec<(String, Source)> {
let mut candidates = query.family.map_or_else(Vec::new, |family| of_family(self.fonts(), family, query));
candidates.extend(self.matched(query));
candidates
}
fn fonts(&self) -> &[SystemFont] {
self.fonts.get_or_init(|| {
let mut fonts = Vec::new();
unsafe {
let iterator = (self.iterator_open)();
if iterator.is_null() {
return fonts;
}
loop {
let font = (self.iterator_next)(iterator);
if font.is_null() {
break;
}
let (source, weight, italic) =
(self.source(font), (self.font_weight)(font), (self.font_is_italic)(font));
(self.close)(font);
if let Some(family) = source.family_name() {
fonts.push(SystemFont { family, weight, italic, source });
}
}
(self.iterator_close)(iterator);
}
fonts
})
}
unsafe fn source(&self, font: *const c_void) -> Source {
let path =
unsafe { PathBuf::from(std::ffi::OsStr::from_bytes(CStr::from_ptr((self.file_path)(font)).to_bytes())) };
let index = unsafe { (self.collection_index)(font) } as u32;
Source::File { path, index }
}
fn matched(&self, query: &Query<'_>) -> Option<(String, Source)> {
let mut probe = [0; 2];
let probe = query.probe.encode_utf16(&mut probe);
let locales = CString::new(query.languages.join(",")).ok()?;
let family = CString::new(query.family.unwrap_or("sans-serif")).ok()?;
unsafe {
let matcher = (self.create)();
if matcher.is_null() {
return None;
}
if !query.languages.is_empty() {
(self.set_locales)(matcher, locales.as_ptr());
}
(self.set_style)(matcher, query.weight, query.italic);
let font =
(self.matches)(matcher, family.as_ptr(), probe.as_ptr(), probe.len() as u32, std::ptr::null_mut());
(self.destroy)(matcher);
if font.is_null() {
return None;
}
let source = self.source(font);
(self.close)(font);
Some((source.family_name().unwrap_or_default(), source))
}
}
}
const MAX_FAMILY_FONTS: usize = 8;
fn of_family(fonts: &[SystemFont], family: &str, query: &Query<'_>) -> Vec<(String, Source)> {
let mut found: Vec<&SystemFont> = fonts.iter().filter(|font| font.family.eq_ignore_ascii_case(family)).collect();
if found.iter().any(|font| font.italic == query.italic) {
found.retain(|font| font.italic == query.italic);
}
found.sort_by_key(|font| font.weight.abs_diff(query.weight));
found.into_iter().take(MAX_FAMILY_FONTS).map(|font| (font.family.clone(), font.source.clone())).collect()
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use super::{FontMatcher, SystemFont, of_family};
use crate::text::system_fonts::Query;
use crate::text::system_fonts::source::Source;
#[test]
fn a_family_lists_its_fonts_of_the_style_asked_for_the_closest_weight_first() {
let font = |family: &str, weight, italic, path: &str| SystemFont {
family: family.to_owned(),
weight,
italic,
source: Source::File { path: PathBuf::from(path), index: 0 },
};
let fonts = [
font("Noto Serif", 400, false, "regular"),
font("Noto Serif", 700, true, "bold italic"),
font("Roboto", 700, false, "roboto"),
font("Noto Serif", 700, false, "bold"),
];
let query =
Query { name: None, family: Some("noto serif"), probe: 'a', languages: &[], weight: 700, italic: false };
let paths: Vec<PathBuf> = of_family(&fonts, "noto serif", &query)
.into_iter()
.map(|(_, source)| {
let Source::File { path, .. } = source;
path
})
.collect();
assert_eq!(paths, ["bold", "regular"].map(PathBuf::from));
let query = Query { italic: true, weight: 400, ..query };
let paths: Vec<PathBuf> = of_family(&fonts[..1], "noto serif", &query)
.into_iter()
.map(|(_, source)| {
let Source::File { path, .. } = source;
path
})
.collect();
assert_eq!(paths, ["regular"].map(PathBuf::from));
}
fn api_level() -> u32 {
let output = std::process::Command::new("getprop").arg("ro.build.version.sdk").output().unwrap();
String::from_utf8_lossy(&output.stdout).trim().parse().unwrap()
}
#[test]
fn the_matcher_is_there_from_api_29() {
assert_eq!(FontMatcher::load().is_some(), api_level() >= 29);
}
#[test]
fn outside_an_app_the_matcher_is_left_out() {
assert!(FontMatcher::new().is_none());
}
}