use std::borrow::Cow;
use std::collections::BTreeSet;
use std::sync::{Mutex, OnceLock, PoisonError};
use iced_graphics::text::cosmic_text::{self, fontdb};
use super::SnapshotError;
use super::env::Runner;
#[cfg(feature = "bundled-fonts")]
pub const INTER_REGULAR: &[u8] = include_bytes!("../../fonts/Inter-Regular.ttf");
#[cfg(feature = "bundled-fonts")]
pub const INTER_MEDIUM: &[u8] = include_bytes!("../../fonts/Inter-Medium.ttf");
#[cfg(feature = "bundled-fonts")]
pub const INTER_SEMIBOLD: &[u8] = include_bytes!("../../fonts/Inter-SemiBold.ttf");
#[cfg(feature = "bundled-fonts")]
pub const INTER_BOLD: &[u8] = include_bytes!("../../fonts/Inter-Bold.ttf");
#[cfg(feature = "bundled-fonts")]
pub const JETBRAINS_MONO_REGULAR: &[u8] = include_bytes!("../../fonts/JetBrainsMono-Regular.ttf");
#[cfg(feature = "bundled-fonts")]
pub const JETBRAINS_MONO_BOLD: &[u8] = include_bytes!("../../fonts/JetBrainsMono-Bold.ttf");
#[cfg(feature = "bundled-fonts")]
pub const BUNDLED: &[&[u8]] = &[
INTER_REGULAR,
INTER_MEDIUM,
INTER_SEMIBOLD,
INTER_BOLD,
JETBRAINS_MONO_REGULAR,
JETBRAINS_MONO_BOLD,
];
#[cfg(not(feature = "bundled-fonts"))]
pub const BUNDLED: &[&[u8]] = &[];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FontMode {
Bundled,
System,
}
impl FontMode {
#[must_use]
pub const fn default_mode() -> Self {
if cfg!(feature = "bundled-fonts") {
Self::Bundled
} else {
Self::System
}
}
#[must_use]
pub fn is_unreliable(self) -> bool {
self == Self::System
}
}
pub(crate) fn decide(
runner: Runner,
default: FontMode,
requested: FontMode,
loaded: Option<FontMode>,
) -> Result<FontMode, SnapshotError> {
if requested != default && runner == Runner::Shared {
return Err(SnapshotError::SystemFontsNeedProcessPerTest);
}
match loaded {
Some(loaded) if loaded != requested => Err(SnapshotError::FontModeChanged {
before: loaded,
now: requested,
}),
_ => Ok(requested),
}
}
static MODE: OnceLock<FontMode> = OnceLock::new();
#[must_use]
pub fn mode() -> FontMode {
MODE.get().copied().unwrap_or(FontMode::default_mode())
}
pub(crate) fn prepare(system_fonts: bool) -> Result<(), SnapshotError> {
let requested = if system_fonts {
FontMode::System
} else {
FontMode::default_mode()
};
let default = FontMode::default_mode();
decide(Runner::current(), default, requested, MODE.get().copied())?;
let loaded = *MODE.get_or_init(|| {
install(requested);
requested
});
decide(Runner::current(), default, requested, Some(loaded)).map(|_| ())
}
pub const SANS: &str = "Inter";
pub const MONO: &str = "JetBrains Mono";
const LOCALE: &str = "en-US";
pub fn ensure_loaded() {
MODE.get_or_init(|| {
let mode = FontMode::default_mode();
install(mode);
mode
});
}
fn install(mode: FontMode) {
let mut system = iced_graphics::text::font_system()
.write()
.unwrap_or_else(PoisonError::into_inner);
let raw = system.raw();
if mode == FontMode::System {
for font in BUNDLED {
raw.db_mut().load_font_data(font.to_vec());
}
return;
}
let mut db = fontdb::Database::new();
let built_in: Vec<fontdb::Source> = raw
.db()
.faces()
.filter(|face| face.index == 0 && matches!(face.source, fontdb::Source::Binary(_)))
.map(|face| face.source.clone())
.collect();
for source in built_in {
let _ = db.load_font_source(source);
}
for font in BUNDLED {
db.load_font_data(font.to_vec());
}
db.set_sans_serif_family(SANS);
db.set_serif_family(SANS);
db.set_cursive_family(SANS);
db.set_fantasy_family(SANS);
db.set_monospace_family(MONO);
*raw = cosmic_text::FontSystem::new_with_locale_and_db(LOCALE.to_owned(), db);
}
#[must_use]
pub fn uncovered(text: &str) -> BTreeSet<char> {
let mut wanted: BTreeSet<char> = text
.chars()
.filter(|c| !c.is_whitespace() && !c.is_control())
.collect();
if wanted.is_empty() {
return wanted;
}
ensure_loaded();
let mut system = iced_graphics::text::font_system()
.write()
.unwrap_or_else(PoisonError::into_inner);
let db = system.raw().db();
let ids: Vec<fontdb::ID> = db.faces().map(|face| face.id).collect();
for id in ids {
if wanted.is_empty() {
break;
}
db.with_face_data(id, |data, index| {
if let Ok(face) = ttf_parser::Face::parse(data, index) {
wanted.retain(|c| face.glyph_index(*c).is_none());
}
});
}
wanted
}
#[must_use]
pub fn fingerprint() -> u64 {
ensure_loaded();
let mut system = iced_graphics::text::font_system()
.write()
.unwrap_or_else(PoisonError::into_inner);
let db = system.raw().db();
let mut hash = Fnv::new();
let ids: Vec<fontdb::ID> = db.faces().map(|face| face.id).collect();
for id in ids {
db.with_face_data(id, |data, index| {
hash.write(data);
hash.write(&index.to_le_bytes());
});
}
hash.finish()
}
#[must_use]
pub fn faces() -> Vec<(String, u16, bool)> {
ensure_loaded();
let mut system = iced_graphics::text::font_system()
.write()
.unwrap_or_else(PoisonError::into_inner);
system
.raw()
.db()
.faces()
.map(|face| {
let family = face
.families
.first()
.map(|(name, _)| name.clone())
.unwrap_or_default();
(family, face.weight.0, face.monospaced)
})
.collect()
}
#[must_use]
pub fn generic_family(family: iced_core::font::Family) -> String {
ensure_loaded();
let mut system = iced_graphics::text::font_system()
.write()
.unwrap_or_else(PoisonError::into_inner);
let db = system.raw().db();
let family = match family {
iced_core::font::Family::Name(name) => return name.to_owned(),
iced_core::font::Family::Serif => fontdb::Family::Serif,
iced_core::font::Family::SansSerif => fontdb::Family::SansSerif,
iced_core::font::Family::Cursive => fontdb::Family::Cursive,
iced_core::font::Family::Fantasy => fontdb::Family::Fantasy,
iced_core::font::Family::Monospace => fontdb::Family::Monospace,
};
db.family_name(&family).to_owned()
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Fnv(u64);
impl Fnv {
pub(crate) fn new() -> Self {
Self(0xcbf2_9ce4_8422_2325)
}
pub(crate) fn write(&mut self, bytes: &[u8]) {
for byte in bytes {
self.0 = (self.0 ^ u64::from(*byte)).wrapping_mul(0x0100_0000_01b3);
}
}
pub(crate) fn finish(self) -> u64 {
self.0
}
pub(crate) fn of(bytes: &[u8]) -> u64 {
let mut hash = Self::new();
hash.write(bytes);
hash.finish()
}
}
type FontKey = (usize, u64);
fn key(bytes: &[u8]) -> FontKey {
(bytes.len(), Fnv::of(bytes))
}
#[derive(Debug, Default)]
pub(crate) struct FontLedger {
boot: Option<Vec<FontKey>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct FontPlan {
pub load: Vec<usize>,
}
impl FontLedger {
pub(crate) fn boot(
&mut self,
runner: Runner,
bundled: &[FontKey],
fonts: &[FontKey],
) -> Result<FontPlan, SnapshotError> {
let own: Vec<(usize, FontKey)> = fonts
.iter()
.copied()
.enumerate()
.filter(|(_, key)| !bundled.contains(key))
.collect();
if let (Runner::Shared, Some((_, (bytes, _)))) = (runner, own.first()) {
return Err(SnapshotError::FontsNeedProcessPerTest { bytes: *bytes });
}
let set: Vec<FontKey> = own.iter().map(|(_, key)| *key).collect();
match &self.boot {
Some(before) if *before != set => {
return Err(SnapshotError::FontSetChanged {
before: before.len(),
now: set.len(),
});
}
Some(_) => {}
None => self.boot = Some(set),
}
Ok(FontPlan {
load: own.into_iter().map(|(index, _)| index).collect(),
})
}
pub(crate) fn load(
runner: Runner,
bundled: &[FontKey],
font: FontKey,
) -> Result<bool, SnapshotError> {
if bundled.contains(&font) {
return Ok(false);
}
match runner {
Runner::ProcessPerTest => Ok(true),
Runner::Shared => Err(SnapshotError::FontsNeedProcessPerTest { bytes: font.0 }),
}
}
}
fn bundled_keys() -> &'static [FontKey] {
static KEYS: std::sync::OnceLock<Vec<FontKey>> = std::sync::OnceLock::new();
KEYS.get_or_init(|| BUNDLED.iter().map(|font| key(font)).collect())
}
fn ledger() -> std::sync::MutexGuard<'static, FontLedger> {
static LEDGER: Mutex<FontLedger> = Mutex::new(FontLedger { boot: None });
LEDGER.lock().unwrap_or_else(PoisonError::into_inner)
}
fn load(font: Cow<'static, [u8]>) {
iced_graphics::text::font_system()
.write()
.unwrap_or_else(PoisonError::into_inner)
.load_font(font);
}
pub(crate) fn load_program_fonts(fonts: &[Cow<'static, [u8]>]) -> Result<(), SnapshotError> {
let keys: Vec<FontKey> = fonts.iter().map(|font| key(font)).collect();
let plan = ledger().boot(Runner::current(), bundled_keys(), &keys)?;
for index in plan.load {
if let Some(font) = fonts.get(index) {
load(font.clone());
}
}
Ok(())
}
pub(crate) fn load_program_font(font: Cow<'static, [u8]>) -> Result<(), SnapshotError> {
if FontLedger::load(Runner::current(), bundled_keys(), key(&font))? {
load(font);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "bundled-fonts")]
const OWN: FontKey = (3, 7);
#[cfg(feature = "bundled-fonts")]
fn bundled() -> Vec<FontKey> {
BUNDLED.iter().map(|font| key(font)).collect()
}
#[test]
fn the_first_harness_decides_the_mode_and_a_shared_process_keeps_the_default() {
use FontMode::{Bundled, System};
assert_eq!(
decide(Runner::Shared, Bundled, Bundled, None).unwrap(),
Bundled
);
assert!(matches!(
decide(Runner::Shared, Bundled, System, None),
Err(SnapshotError::SystemFontsNeedProcessPerTest)
));
assert_eq!(
decide(Runner::ProcessPerTest, Bundled, System, None).unwrap(),
System
);
assert!(matches!(
decide(Runner::ProcessPerTest, Bundled, Bundled, Some(System)),
Err(SnapshotError::FontModeChanged {
before: System,
now: Bundled
})
));
assert_eq!(
decide(Runner::Shared, System, System, Some(System)).unwrap(),
System,
"without the bundled set every harness keeps the machine's fonts"
);
assert!(System.is_unreliable() && !Bundled.is_unreliable());
}
#[cfg(feature = "bundled-fonts")]
#[test]
fn characters_no_face_covers_are_listed() {
assert!(uncovered("Leeks and beans 123").is_empty());
let missing = uncovered("tea \u{1F375} \u{10FFFD}");
assert_eq!(
missing.into_iter().collect::<Vec<_>>(),
vec!['\u{1F375}', '\u{10FFFD}']
);
assert!(uncovered(" \n\t").is_empty());
}
#[cfg(feature = "bundled-fonts")]
#[test]
fn after_loading_only_built_in_and_bundled_faces_remain() {
ensure_loaded();
let faces = faces();
let families: Vec<&str> = faces.iter().map(|(family, _, _)| family.as_str()).collect();
assert!(
families
.iter()
.all(|f| matches!(*f, "Inter" | "JetBrains Mono" | "Iced-Icons")),
"{families:?}"
);
assert_eq!(families.iter().filter(|f| **f == "Inter").count(), 4);
assert_eq!(
families.iter().filter(|f| **f == "JetBrains Mono").count(),
2
);
let mut system = iced_graphics::text::font_system()
.write()
.unwrap_or_else(PoisonError::into_inner);
assert!(
system
.raw()
.db()
.faces()
.all(|face| matches!(face.source, fontdb::Source::Binary(_))),
"no face comes from a file"
);
}
#[cfg(feature = "bundled-fonts")]
#[test]
fn generic_families_resolve_to_the_bundled_faces() {
assert_eq!(generic_family(iced_core::font::Family::SansSerif), "Inter");
assert_eq!(generic_family(iced_core::font::Family::Serif), "Inter");
assert_eq!(
generic_family(iced_core::font::Family::Monospace),
"JetBrains Mono"
);
}
#[test]
fn a_second_call_changes_nothing() {
let before = fingerprint();
ensure_loaded();
assert_eq!(fingerprint(), before);
}
#[cfg(feature = "bundled-fonts")]
#[test]
fn a_shared_process_loads_bundled_bytes_as_a_no_op_and_refuses_others() {
let bundled = bundled();
let mut ledger = FontLedger::default();
let plan = ledger
.boot(Runner::Shared, &bundled, &[bundled[0], bundled[4]])
.unwrap();
assert!(plan.load.is_empty());
assert!(matches!(
ledger.boot(Runner::Shared, &bundled, &[bundled[0], OWN]),
Err(SnapshotError::FontsNeedProcessPerTest { bytes: 3 })
));
assert!(!FontLedger::load(Runner::Shared, &bundled, bundled[1]).unwrap());
assert!(matches!(
FontLedger::load(Runner::Shared, &bundled, OWN),
Err(SnapshotError::FontsNeedProcessPerTest { .. })
));
}
#[cfg(feature = "bundled-fonts")]
#[test]
fn a_process_per_test_loads_program_fonts_and_holds_later_harnesses_to_them() {
let bundled = bundled();
let mut ledger = FontLedger::default();
let plan = ledger
.boot(Runner::ProcessPerTest, &bundled, &[bundled[0], OWN])
.unwrap();
assert_eq!(plan.load, vec![1]);
assert!(
ledger
.boot(Runner::ProcessPerTest, &bundled, &[OWN])
.is_ok(),
"the same set again"
);
assert!(matches!(
ledger.boot(Runner::ProcessPerTest, &bundled, &[]),
Err(SnapshotError::FontSetChanged { before: 1, now: 0 })
));
assert!(FontLedger::load(Runner::ProcessPerTest, &bundled, OWN).unwrap());
}
}