use std::{fmt, sync::Arc};
use super::weight::{nearest, FontWeight};
use crate::Id;
type FontData = Arc<dyn AsRef<[u8]> + Send + Sync>;
#[derive(Clone)]
pub struct FontFamily {
faces: Vec<(FontWeight, FontData)>,
}
impl FontFamily {
pub fn new(regular: impl AsRef<[u8]> + Send + Sync + 'static) -> Self {
Self {
faces: vec![(FontWeight::REGULAR, Arc::new(regular))],
}
}
pub fn with_weight(
mut self,
weight: FontWeight,
data: impl AsRef<[u8]> + Send + Sync + 'static,
) -> Self {
self.faces.retain(|(w, _)| *w != weight);
self.faces.push((weight, Arc::new(data)));
self
}
pub fn inter() -> Self {
let family = Self::new(include_bytes!("../../assets/Inter-Regular.ttf"));
#[cfg(feature = "bundled-weights")]
let family = family
.with_weight(
FontWeight::MEDIUM,
include_bytes!("../../assets/Inter-Medium.ttf"),
)
.with_weight(
FontWeight::SEMIBOLD,
include_bytes!("../../assets/Inter-SemiBold.ttf"),
)
.with_weight(
FontWeight::BOLD,
include_bytes!("../../assets/Inter-Bold.ttf"),
);
family
}
#[cfg(feature = "bundled-monospace")]
pub fn jetbrains_mono() -> Self {
let family = Self::new(include_bytes!("../../assets/JetBrainsMono-Regular.ttf"));
#[cfg(feature = "bundled-weights")]
let family = family.with_weight(
FontWeight::BOLD,
include_bytes!("../../assets/JetBrainsMono-Bold.ttf"),
);
family
}
pub(crate) fn default_monospace() -> Option<Self> {
#[cfg(feature = "bundled-monospace")]
return Some(Self::jetbrains_mono());
#[cfg(not(feature = "bundled-monospace"))]
None
}
pub fn weights(&self) -> Vec<FontWeight> {
let mut weights: Vec<_> = self.faces.iter().map(|(w, _)| *w).collect();
weights.sort_unstable();
weights
}
pub fn resolve(&self, wanted: FontWeight) -> FontWeight {
nearest(self.faces.iter().map(|(w, _)| *w), wanted).unwrap_or(FontWeight::REGULAR)
}
pub(super) fn data(&self, weight: FontWeight) -> Option<&[u8]> {
self.faces
.iter()
.find(|(w, _)| *w == weight)
.map(|(_, d)| (**d).as_ref())
}
pub(super) fn faces(&self) -> impl Iterator<Item = (FontWeight, &FontData)> {
self.faces.iter().map(|(w, d)| (*w, d))
}
pub(super) fn identity(&self) -> Id {
let mut parts: Vec<(u16, usize, Vec<u8>)> = self
.faces
.iter()
.map(|(w, d)| {
let bytes = (**d).as_ref();
let step = (bytes.len() / 512).max(1);
let sample = bytes.iter().step_by(step).copied().collect();
(w.value(), bytes.len(), sample)
})
.collect();
parts.sort();
Id::new(parts)
}
}
impl fmt::Debug for FontFamily {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FontFamily")
.field("weights", &self.weights())
.finish()
}
}
impl Default for FontFamily {
fn default() -> Self {
Self::inter()
}
}