pub mod atlas;
pub mod cluster;
pub mod color;
pub mod face;
pub mod fallback;
#[cfg(all(test, feature = "parsed-font"))]
pub(crate) mod fixtures;
pub mod layout;
pub mod shape;
#[cfg(feature = "system-fonts")]
pub mod system;
pub use crcbl_image::raster;
use core::fmt;
use std::sync::Arc;
#[cfg(feature = "parsed-font")]
use std::sync::OnceLock;
#[cfg(feature = "parsed-font")]
use std::sync::atomic::{AtomicU32, Ordering};
#[cfg(feature = "parsed-font")]
use skrifa::instance::{LocationRef, Size};
#[cfg(feature = "parsed-font")]
use skrifa::raw::TableProvider;
#[cfg(feature = "parsed-font")]
use skrifa::{FontRef, MetadataProvider};
use face::Synthesis;
#[cfg(feature = "parsed-font")]
pub const SANS_TTF: &[u8] = include_bytes!("../../fonts/AtkinsonHyperlegible-Regular.ttf");
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum FontFamily {
#[default]
Bitmap,
#[cfg(feature = "parsed-font")]
Sans,
}
impl FontFamily {
#[must_use]
pub fn font(self) -> Option<&'static Font> {
match self {
Self::Bitmap => None,
#[cfg(feature = "parsed-font")]
Self::Sans => Some(Font::sans()),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct FamilyName(u64);
impl FamilyName {
#[must_use]
pub fn new(name: &str) -> Self {
let mut hasher = std::hash::DefaultHasher::new();
std::hash::Hash::hash(&name.to_ascii_lowercase(), &mut hasher);
Self(std::hash::Hasher::finish(&hasher))
}
}
const RESERVED_FAMILIES: &[&str] = &[
"bitmap",
"atkinson hyperlegible",
"serif",
"sans-serif",
"monospace",
"cursive",
"fantasy",
"system-ui",
"ui-serif",
"ui-sans-serif",
"ui-monospace",
"ui-rounded",
"math",
"emoji",
"fangsong",
"initial",
"inherit",
"unset",
"revert",
"revert-layer",
"default",
];
pub(crate) fn is_reserved_family(name: &str) -> bool {
name.is_empty()
|| RESERVED_FAMILIES
.iter()
.any(|reserved| reserved.eq_ignore_ascii_case(name))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReservedFamilyName(pub String);
impl fmt::Display for ReservedFamilyName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"`{}` is reserved: no `font-family` list selects a registered font by it",
self.0
)
}
}
impl std::error::Error for ReservedFamilyName {}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct FontId(u32);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct GlyphId(pub u32);
impl GlyphId {
pub const NOTDEF: Self = Self(0);
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FontError {
Unreadable(String),
NoUnitsPerEm,
ParsedFontOff,
}
impl fmt::Display for FontError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unreadable(why) => write!(f, "the font cannot be read: {why}"),
Self::NoUnitsPerEm => f.write_str("the font's head table gives no units per em"),
Self::ParsedFontOff => f.write_str(
"crcbl-ui was built without its `parsed-font` feature, so it parses no fonts",
),
}
}
}
impl std::error::Error for FontError {}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Underline {
pub offset: f32,
pub thickness: f32,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FontMetrics {
pub units_per_em: u16,
pub ascent: f32,
pub descent: f32,
pub line_gap: f32,
}
impl FontMetrics {
#[must_use]
pub fn scale(&self, size: f32) -> f32 {
size / f32::from(self.units_per_em)
}
#[must_use]
pub fn normal_line_height(&self, size: f32) -> f32 {
(self.ascent - self.descent + self.line_gap) * self.scale(size)
}
}
const LATIN1_END: u32 = 0x100;
#[derive(Clone)]
pub struct FontData(Bytes);
#[derive(Clone)]
enum Bytes {
Static(&'static [u8]),
Shared(Arc<dyn AsRef<[u8]> + Send + Sync>),
}
impl FontData {
#[must_use]
pub fn as_bytes(&self) -> &[u8] {
match &self.0 {
Bytes::Static(bytes) => bytes,
Bytes::Shared(bytes) => (**bytes).as_ref(),
}
}
}
impl fmt::Debug for FontData {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FontData")
.field("len", &self.as_bytes().len())
.finish()
}
}
impl From<&'static [u8]> for FontData {
fn from(bytes: &'static [u8]) -> Self {
Self(Bytes::Static(bytes))
}
}
impl<const N: usize> From<&'static [u8; N]> for FontData {
fn from(bytes: &'static [u8; N]) -> Self {
Self(Bytes::Static(bytes))
}
}
impl From<Arc<[u8]>> for FontData {
fn from(bytes: Arc<[u8]>) -> Self {
Self(Bytes::Shared(Arc::new(bytes)))
}
}
impl From<Vec<u8>> for FontData {
fn from(bytes: Vec<u8>) -> Self {
Self(Bytes::Shared(Arc::new(bytes)))
}
}
impl From<Box<[u8]>> for FontData {
fn from(bytes: Box<[u8]>) -> Self {
Self(Bytes::Shared(Arc::new(bytes)))
}
}
#[derive(Clone)]
pub struct Font {
parsed: Arc<Parsed>,
synthesis: Synthesis,
fallback: Arc<[Font]>,
}
struct Parsed {
#[cfg(not(feature = "parsed-font"))]
never: NoParsedFont,
ids: [FontId; SYNTHESES],
data: FontData,
metrics: FontMetrics,
underline: Option<Underline>,
weight: f32,
italic: bool,
#[cfg(feature = "parsed-font")]
color: bool,
latin1: [u32; LATIN1_END as usize],
advances: Box<[f32]>,
#[cfg(feature = "parsed-font")]
shaper: Option<harfrust::Font>,
}
impl fmt::Debug for Font {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Font")
.field("id", &self.id())
.field("metrics", &self.parsed.metrics)
.field("weight", &self.parsed.weight)
.field("italic", &self.parsed.italic)
.field("synthesis", &self.synthesis)
.field("fallback", &self.fallback.len())
.field("glyphs", &self.parsed.advances.len())
.finish_non_exhaustive()
}
}
impl PartialEq for Font {
fn eq(&self, other: &Self) -> bool {
self.id() == other.id()
}
}
impl Eq for Font {}
impl From<&Font> for Font {
fn from(font: &Font) -> Self {
font.clone()
}
}
#[cfg(not(feature = "parsed-font"))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum NoParsedFont {}
const SYNTHESES: usize = 4;
#[cfg(feature = "parsed-font")]
fn next_ids() -> [FontId; SYNTHESES] {
static NEXT_ID: AtomicU32 = AtomicU32::new(0);
let first = NEXT_ID.fetch_add(SYNTHESES as u32, Ordering::Relaxed);
core::array::from_fn(|at| FontId(first + at as u32))
}
impl Font {
#[cfg(feature = "parsed-font")]
#[must_use]
pub fn sans() -> &'static Self {
static SANS: OnceLock<Font> = OnceLock::new();
SANS.get_or_init(|| Self::parse(SANS_TTF).expect("the committed UI font parses"))
}
#[cfg(not(feature = "parsed-font"))]
pub fn parse(data: impl Into<FontData>) -> Result<Self, FontError> {
drop(data.into());
Err(FontError::ParsedFontOff)
}
#[cfg(feature = "parsed-font")]
pub fn parse(data: impl Into<FontData>) -> Result<Self, FontError> {
let data = data.into();
let font = FontRef::new(data.as_bytes())
.map_err(|error| FontError::Unreadable(error.to_string()))?;
let unscaled = font.metrics(Size::unscaled(), LocationRef::default());
if unscaled.units_per_em == 0 {
return Err(FontError::NoUnitsPerEm);
}
let metrics = FontMetrics {
units_per_em: unscaled.units_per_em,
ascent: unscaled.ascent,
descent: unscaled.descent,
line_gap: unscaled.leading,
};
let underline = unscaled.underline.map(|line| Underline {
offset: line.offset,
thickness: line.thickness,
});
let attributes = font.attributes();
let color = font.colr().is_ok() || font.cbdt().is_ok() || font.sbix().is_ok();
let charmap = font.charmap();
let mut latin1 = [0; LATIN1_END as usize];
for (codepoint, glyph) in latin1.iter_mut().enumerate() {
*glyph = charmap
.map(codepoint as u32)
.map_or(0, skrifa::GlyphId::to_u32);
}
let glyph_metrics = font.glyph_metrics(Size::unscaled(), LocationRef::default());
let advances = (0..glyph_metrics.glyph_count())
.map(|glyph| {
glyph_metrics
.advance_width(skrifa::GlyphId::new(glyph))
.unwrap_or(0.0)
})
.collect();
let shaper = match &data.0 {
Bytes::Static(bytes) => harfrust::Font::new(*bytes, 0),
Bytes::Shared(bytes) => harfrust::Font::new(Arc::clone(bytes), 0),
}
.ok_or_else(|| FontError::Unreadable("harfrust cannot read it".to_owned()))?;
Ok(Self {
parsed: Arc::new(Parsed {
ids: next_ids(),
data,
metrics,
underline,
weight: attributes.weight.value(),
italic: attributes.style != skrifa::attribute::Style::Normal,
color,
latin1,
advances,
shaper: Some(shaper),
}),
synthesis: Synthesis::NONE,
fallback: no_fallback(),
})
}
#[must_use]
pub fn id(&self) -> FontId {
self.parsed.ids[self.synthesis.index()]
}
#[must_use]
pub fn synthesized(&self, synthesis: Synthesis) -> Self {
Self {
parsed: Arc::clone(&self.parsed),
synthesis,
fallback: Arc::clone(&self.fallback),
}
}
#[must_use]
pub fn with_fallback(&self, fallback: &[Self]) -> Self {
let faces = fallback
.iter()
.take(fallback::MAX_FALLBACK_FACES)
.map(|face| Self {
parsed: Arc::clone(&face.parsed),
synthesis: face.synthesis,
fallback: no_fallback(),
})
.collect();
Self {
parsed: Arc::clone(&self.parsed),
synthesis: self.synthesis,
fallback: faces,
}
}
#[must_use]
pub fn fallback(&self) -> &[Self] {
&self.fallback
}
#[must_use]
pub fn face(&self, index: u8) -> &Self {
match index.checked_sub(1) {
Some(at) => self.fallback.get(usize::from(at)).unwrap_or(self),
None => self,
}
}
#[cfg(not(feature = "parsed-font"))]
#[must_use]
pub fn has_color_glyph(&self, _glyph: GlyphId) -> bool {
match self.parsed.never {}
}
#[cfg(not(feature = "parsed-font"))]
pub(crate) fn has_color_tables(&self) -> bool {
match self.parsed.never {}
}
#[cfg(feature = "parsed-font")]
pub(crate) fn has_color_tables(&self) -> bool {
self.parsed.color
}
#[cfg(feature = "parsed-font")]
#[must_use]
pub fn has_color_glyph(&self, glyph: GlyphId) -> bool {
self.parsed.color
&& FontRef::new(self.data())
.is_ok_and(|font| color::has_color_glyph(&font, skrifa::GlyphId::new(glyph.0)))
}
#[must_use]
pub const fn synthesis(&self) -> Synthesis {
self.synthesis
}
#[must_use]
pub fn weight(&self) -> f32 {
self.parsed.weight
}
#[must_use]
pub fn is_italic(&self) -> bool {
self.parsed.italic
}
#[must_use]
pub fn underline(&self) -> Option<Underline> {
self.parsed.underline
}
#[must_use]
pub fn data(&self) -> &[u8] {
self.parsed.data.as_bytes()
}
#[must_use]
pub fn metrics(&self) -> FontMetrics {
self.parsed.metrics
}
#[must_use]
pub fn glyph_count(&self) -> usize {
self.parsed.advances.len()
}
#[must_use]
pub fn glyph_id(&self, c: char) -> GlyphId {
let codepoint = c as u32;
if codepoint < LATIN1_END {
return GlyphId(self.parsed.latin1[codepoint as usize]);
}
#[cfg(not(feature = "parsed-font"))]
match self.parsed.never {}
#[cfg(feature = "parsed-font")]
FontRef::new(self.data())
.ok()
.and_then(|font| font.charmap().map(codepoint))
.map_or(GlyphId::NOTDEF, |glyph| GlyphId(glyph.to_u32()))
}
#[must_use]
pub fn advance(&self, glyph: GlyphId) -> f32 {
let Some(&advance) = self.parsed.advances.get(glyph.0 as usize) else {
return 0.0;
};
if self.synthesis.bold {
advance + f32::from(self.parsed.metrics.units_per_em) * face::SYNTHETIC_BOLD_EM
} else {
advance
}
}
#[cfg(all(test, feature = "parsed-font"))]
pub(crate) fn fixed_pitch(metrics: FontMetrics, advance: f32) -> &'static Self {
Self::fixed_pitch_face(metrics, advance, 400.0, false)
}
#[cfg(all(test, feature = "parsed-font"))]
pub(crate) fn fixed_pitch_face(
metrics: FontMetrics,
advance: f32,
weight: f32,
italic: bool,
) -> &'static Self {
Box::leak(Box::new(Self {
parsed: Arc::new(Parsed {
ids: next_ids(),
data: FontData::from(&[]),
metrics,
underline: None,
weight,
italic,
color: false,
latin1: [1; LATIN1_END as usize],
advances: Box::new([0.0, advance]),
shaper: None,
}),
synthesis: Synthesis::NONE,
fallback: no_fallback(),
}))
}
}
fn no_fallback() -> Arc<[Font]> {
Arc::from(Vec::new())
}
#[cfg(all(test, not(feature = "parsed-font")))]
mod off_tests {
use super::*;
#[test]
fn without_the_feature_every_parse_is_refused_and_says_why() {
let bytes = include_bytes!("../../fonts/AtkinsonHyperlegible-Regular.ttf");
let refused = Font::parse(bytes);
assert!(matches!(refused, Err(FontError::ParsedFontOff)));
let message = FontError::ParsedFontOff.to_string();
assert!(message.contains("parsed-font"), "{message}");
assert_eq!(FontFamily::default().font(), None);
}
}
#[cfg(all(test, feature = "parsed-font"))]
mod tests {
use super::*;
#[test]
fn the_committed_font_parses_with_latin1_and_shaping() {
let font = Font::sans();
let reference = FontRef::new(SANS_TTF).expect("reads");
let metrics = reference.metrics(Size::unscaled(), LocationRef::default());
assert_eq!(font.metrics().units_per_em, metrics.units_per_em);
assert_eq!(font.metrics().ascent, metrics.ascent);
assert_eq!(font.metrics().descent, metrics.descent);
assert!(font.metrics().ascent > 0.0 && font.metrics().descent < 0.0);
let printable = (0x20u32..0x7f).chain(0xa0..0x100);
for codepoint in printable {
let c = char::from_u32(codepoint).expect("Latin-1 is valid");
assert_ne!(
font.glyph_id(c),
GlyphId::NOTDEF,
"U+{codepoint:04X} has no glyph"
);
}
assert!(
font.parsed.shaper.is_some(),
"the committed font is not ready to shape"
);
}
#[test]
fn an_unmapped_codepoint_is_notdef_and_a_mapped_one_is_not() {
let font = Font::sans();
let reference = FontRef::new(SANS_TTF).expect("reads");
let charmap = reference.charmap();
for c in ['\u{1}', '\u{7f}', '\u{4e2d}', '\u{1f600}'] {
assert_eq!(charmap.map(c as u32), None, "{c:?} is mapped after all");
assert_eq!(font.glyph_id(c), GlyphId::NOTDEF, "{c:?}");
}
for c in ['€', '–'] {
let want = charmap.map(c as u32).expect("the font maps it");
assert_eq!(font.glyph_id(c), GlyphId(want.to_u32()), "{c:?}");
assert_ne!(font.glyph_id(c), GlyphId::NOTDEF);
}
}
#[test]
fn bytes_that_are_not_a_font_are_refused() {
assert!(matches!(
Font::parse(b"not a font at all"),
Err(FontError::Unreadable(_))
));
}
#[test]
fn advances_are_the_fonts_own() {
let font = Font::sans();
let reference = FontRef::new(SANS_TTF).expect("reads");
let metrics = reference.glyph_metrics(Size::unscaled(), LocationRef::default());
assert_eq!(font.glyph_count(), metrics.glyph_count() as usize);
for c in ['A', 'i', 'W', ' ', 'é'] {
let glyph = font.glyph_id(c);
assert_eq!(
Some(font.advance(glyph)),
metrics.advance_width(skrifa::GlyphId::new(glyph.0)),
"{c:?}"
);
}
assert_eq!(font.advance(GlyphId(u32::MAX)), 0.0);
}
#[test]
fn a_font_from_run_time_bytes_holds_them_until_its_last_clone_goes() {
let bytes: Arc<[u8]> = Arc::from(SANS_TTF);
let font = Font::parse(Arc::clone(&bytes)).expect("parses");
assert_eq!(font.metrics(), Font::sans().metrics());
assert_eq!(font.glyph_id('A'), Font::sans().glyph_id('A'));
let copy = font.clone();
assert_eq!(copy, font, "a clone is the same font");
assert_eq!(Arc::strong_count(&bytes), 2);
drop(font);
assert_eq!(Arc::strong_count(&bytes), 2, "the clone still holds them");
drop(copy);
assert_eq!(Arc::strong_count(&bytes), 1, "freed with the last clone");
let owned = Font::parse(SANS_TTF.to_vec()).expect("parses");
assert_eq!(owned.data(), SANS_TTF);
}
#[test]
fn every_parse_is_its_own_id() {
let a = Font::parse(SANS_TTF).expect("parses");
let b = Font::parse(SANS_TTF).expect("parses");
assert_ne!(a.id(), b.id());
}
}