use std::collections::HashMap;
use std::fmt;
use std::fs::File;
use std::io::{self, Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use std::sync::{Arc, OnceLock};
use std::time::SystemTime;
use skrifa::Tag;
use skrifa::font::{Blob, Font};
use skrifa::raw::{CollectionRef, FontRef, MinByteRange, ReadError, TableDirectory};
use crate::face::FaceDescription;
use crate::file::{FaceOrigin, FaceSource, FileNotRead, LoadedFile, NotReadCause};
use crate::{FontDb, FontError, FontId};
const EXTENSIONS: [&str; 4] = ["ttf", "otf", "ttc", "otc"];
const DESCRIPTION_TABLES: [Tag; 6] = [
Tag::new(b"head"),
Tag::new(b"hhea"),
Tag::new(b"hmtx"),
Tag::new(b"OS/2"),
Tag::new(b"post"),
Tag::new(b"name"),
];
const COLLECTION_TAG: &[u8] = b"ttcf";
const FIRST_READ: u64 = 4096;
impl FontDb {
pub fn add_files(&mut self, files: &[PathBuf]) -> Result<Vec<FontId>, FileNotAdded> {
let mut ids = Vec::new();
for path in files {
let not_added = |cause| FileNotAdded {
path: path.clone(),
cause,
};
if !is_font_file(path) {
return Err(not_added(NotAddedCause::NotAFontFile));
}
let (file, descriptions) = read_descriptions(path.clone())
.map_err(|error| not_added(NotAddedCause::Unreadable(error)))?
.map_err(|error| not_added(NotAddedCause::Font(error)))?;
let added = self
.add_faces(FaceSource::Folder(file), descriptions, FaceOrigin::Caller)
.map_err(|error| not_added(NotAddedCause::Font(error)))?;
ids.extend(added);
}
Ok(ids)
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct FileNotAdded {
pub path: PathBuf,
pub cause: NotAddedCause,
}
#[derive(Debug)]
#[non_exhaustive]
pub enum NotAddedCause {
NotAFontFile,
Font(FontError),
Unreadable(io::Error),
}
impl fmt::Display for FileNotAdded {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let path = self.path.display();
match &self.cause {
NotAddedCause::NotAFontFile => write!(
f,
"{path} is not a font file: its extension is not ttf, otf, ttc or otc"
),
NotAddedCause::Font(error) => write!(f, "{path} is not added: {error}"),
NotAddedCause::Unreadable(error) => write!(f, "{path} cannot be read: {error}"),
}
}
}
impl std::error::Error for FileNotAdded {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.cause {
NotAddedCause::NotAFontFile => None,
NotAddedCause::Font(error) => Some(error),
NotAddedCause::Unreadable(error) => Some(error),
}
}
}
impl From<FileNotAdded> for io::Error {
fn from(not_added: FileNotAdded) -> Self {
let kind = match ¬_added.cause {
NotAddedCause::Unreadable(error) => error.kind(),
NotAddedCause::NotAFontFile | NotAddedCause::Font(_) => io::ErrorKind::InvalidData,
};
Self::new(kind, not_added)
}
}
#[must_use]
pub fn is_font_file(path: &Path) -> bool {
path.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| {
EXTENSIONS
.iter()
.any(|known| known.eq_ignore_ascii_case(extension))
})
}
pub(crate) struct FolderFile {
path: PathBuf,
name: String,
stamp: Stamp,
faces: u32,
loaded: OnceLock<Result<LoadedFile, NotReadCause>>,
}
impl FolderFile {
pub(crate) fn load(&self) -> Result<&LoadedFile, FileNotRead> {
self.loaded().map_err(|cause| FileNotRead {
file: self.name.clone(),
cause,
})
}
pub(crate) fn loaded(&self) -> Result<&LoadedFile, NotReadCause> {
self.loaded
.get_or_init(|| self.read())
.as_ref()
.map_err(|cause| *cause)
}
fn read(&self) -> Result<LoadedFile, NotReadCause> {
let unreadable = |error: io::Error| NotReadCause::Unreadable(error.kind());
let mut file = File::open(&self.path).map_err(unreadable)?;
if Stamp::of(&file).map_err(unreadable)? != self.stamp {
return Err(NotReadCause::Changed);
}
let mut bytes = Vec::with_capacity(usize::try_from(self.stamp.len).unwrap_or(0));
file.read_to_end(&mut bytes).map_err(unreadable)?;
if u64::try_from(bytes.len()).ok() != Some(self.stamp.len) {
return Err(NotReadCause::Changed);
}
let data: Arc<[u8]> = bytes.into();
let fonts = (0..self.faces)
.map(|index| Font::new(Blob::Shared(Arc::new(Arc::clone(&data))), index))
.collect::<Option<Vec<_>>>()
.ok_or(NotReadCause::Changed)?;
Ok(LoadedFile::new(data.into(), fonts))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Stamp {
len: u64,
modified: Option<SystemTime>,
}
impl Stamp {
fn of(file: &File) -> io::Result<Self> {
let metadata = file.metadata()?;
Ok(Self {
len: metadata.len(),
modified: metadata.modified().ok(),
})
}
}
fn read_descriptions(
path: PathBuf,
) -> io::Result<Result<(FolderFile, Vec<FaceDescription>), FontError>> {
let mut file = File::open(&path)?;
let stamp = Stamp::of(&file)?;
let mut start = Start {
file: &mut file,
len: stamp.len,
bytes: Vec::new(),
};
let Some(directories) = start.directories()? else {
return Ok(Err(FontError::NotAFont));
};
let mut tables = HashMap::new();
let mut descriptions = Vec::new();
for records in &directories {
let font = start.description_font(records, &mut tables)?;
match font.as_ref().map(FaceDescription::read) {
Some(Ok(description)) => descriptions.push(description),
Some(Err(error)) => return Ok(Err(error)),
None => return Ok(Err(FontError::NotAFont)),
}
}
let Ok(faces) = u32::try_from(descriptions.len()) else {
return Ok(Err(FontError::TooManyFaces));
};
let name = path
.file_name()
.map_or_else(String::new, |name| name.to_string_lossy().into_owned());
let file = FolderFile {
path,
name,
stamp,
faces,
loaded: OnceLock::new(),
};
Ok(Ok((file, descriptions)))
}
type Records = Vec<(Tag, u32, u32)>;
fn records(directory: &TableDirectory<'_>) -> Result<Records, ReadError> {
if directory.offset_data().len() < directory.min_byte_range().end {
return Err(ReadError::OutOfBounds);
}
let records = directory.table_records().iter();
Ok(records
.map(|record| (record.tag(), record.offset(), record.length()))
.collect())
}
struct Start<'a> {
file: &'a mut File,
len: u64,
bytes: Vec<u8>,
}
impl Start<'_> {
fn directories(&mut self) -> io::Result<Option<Vec<Records>>> {
let tag = self.parse(|bytes| {
bytes
.get(..4)
.ok_or(ReadError::OutOfBounds)
.map(<[u8]>::to_vec)
})?;
if tag.ok().as_deref() != Some(COLLECTION_TAG) {
let face = self.parse(|bytes| records(FontRef::new(bytes)?.table_directory()))?;
return Ok(face.ok().map(|face| vec![face]));
}
let Ok(count) = self.parse(|bytes| CollectionRef::new(bytes).map(|fonts| fonts.len()))?
else {
return Ok(None);
};
let mut faces = Vec::new();
for index in 0..count {
let face = self.parse(|bytes| {
let font = CollectionRef::new(bytes)?.get(index)?;
records(font.table_directory())
})?;
let Ok(face) = face else {
return Ok(None);
};
faces.push(face);
}
Ok(Some(faces))
}
fn parse<T>(
&mut self,
parse: impl Fn(&[u8]) -> Result<T, ReadError>,
) -> io::Result<Result<T, ReadError>> {
loop {
let parsed = parse(&self.bytes);
if !matches!(parsed, Err(ReadError::OutOfBounds)) || !self.read_more()? {
return Ok(parsed);
}
}
}
fn read_more(&mut self) -> io::Result<bool> {
let had = u64::try_from(self.bytes.len()).unwrap_or(u64::MAX);
let more = had.max(FIRST_READ).min(self.len.saturating_sub(had));
self.file.seek(SeekFrom::Start(had))?;
(&mut *self.file).take(more).read_to_end(&mut self.bytes)?;
Ok(u64::try_from(self.bytes.len()).unwrap_or(u64::MAX) > had)
}
fn description_font(
&mut self,
records: &Records,
read: &mut HashMap<(u32, u32), Blob>,
) -> io::Result<Option<Font>> {
let mut tables = Vec::new();
for tag in DESCRIPTION_TABLES {
let Some(&(_, offset, length)) = records.iter().find(|(listed, ..)| *listed == tag)
else {
continue;
};
if offset
.checked_add(length)
.is_none_or(|end| u64::from(end) > self.len)
{
continue;
}
let blob = match read.get(&(offset, length)) {
Some(blob) => blob.clone(),
None => self.table(offset, length)?,
};
read.insert((offset, length), blob.clone());
tables.push((tag, blob));
}
let source: Arc<dyn Fn(Tag) -> Option<Blob> + Send + Sync> = Arc::new(move |tag| {
let found = tables.iter().find(|(listed, _)| *listed == tag);
found.map(|(_, blob)| blob.clone())
});
Ok(Font::new(source, 0))
}
fn table(&mut self, offset: u32, length: u32) -> io::Result<Blob> {
let start = usize::try_from(offset).unwrap_or(usize::MAX);
let end = start.saturating_add(usize::try_from(length).unwrap_or(usize::MAX));
if let Some(bytes) = self.bytes.get(start..end) {
return Ok(Blob::from(bytes.to_vec()));
}
self.file.seek(SeekFrom::Start(u64::from(offset)))?;
let mut bytes = Vec::with_capacity(usize::try_from(length).unwrap_or(0));
(&mut *self.file)
.take(u64::from(length))
.read_to_end(&mut bytes)?;
if bytes.len() != usize::try_from(length).unwrap_or(usize::MAX) {
return Err(io::ErrorKind::UnexpectedEof.into());
}
Ok(Blob::from(bytes))
}
}
#[cfg(test)]
mod tests;