Skip to main content

f_office_fonts/
folder.rs

1//! Loading font files by their paths, for native builds.
2//!
3//! [`FontDb::add_files`] reads of each file only what the faces' descriptions need: the start
4//! of the file that holds its table directories, and the tables that
5//! [`FaceDescription::read`] reads. It keeps the file's length and modification time, and the
6//! file's bytes load at the first choice of one of its faces ([`FontDb::load`]).
7
8use std::collections::HashMap;
9use std::fmt;
10use std::fs::File;
11use std::io::{self, Read, Seek, SeekFrom};
12use std::path::{Path, PathBuf};
13use std::sync::{Arc, OnceLock};
14use std::time::SystemTime;
15
16use skrifa::Tag;
17use skrifa::font::{Blob, Font};
18use skrifa::raw::{CollectionRef, FontRef, MinByteRange, ReadError, TableDirectory};
19
20use crate::face::FaceDescription;
21use crate::file::{FaceOrigin, FaceSource, FileNotRead, LoadedFile, NotReadCause};
22use crate::{FontDb, FontError, FontId};
23
24/// File extensions of OpenType fonts and font collections.
25const EXTENSIONS: [&str; 4] = ["ttf", "otf", "ttc", "otc"];
26
27/// The tables that a face's description reads ([`FaceDescription::read`]).
28const DESCRIPTION_TABLES: [Tag; 6] = [
29    Tag::new(b"head"),
30    Tag::new(b"hhea"),
31    Tag::new(b"hmtx"),
32    Tag::new(b"OS/2"),
33    Tag::new(b"post"),
34    Tag::new(b"name"),
35];
36
37/// The first four bytes of a font collection.
38const COLLECTION_TAG: &[u8] = b"ttcf";
39
40/// The bytes of a file's start that are read first, and the fewest bytes that are read when the
41/// parse of its table directories needs more.
42const FIRST_READ: u64 = 4096;
43
44impl FontDb {
45    /// Adds the fonts of the files `files`, in the order given, and returns the new IDs.
46    ///
47    /// The faces take their IDs in the order of `files`, and so does the choice between two
48    /// faces of equal style: the face query keeps the first ([`FontDb::query`]). The order is
49    /// the caller's, the order of its font sources, and never the files' names. Each file must
50    /// be a font file ([`is_font_file`]) that holds fonts that [`FontDb::add_font`] would take
51    /// from its bytes. Of each file, only the table directories and the tables of the faces'
52    /// names, style and metrics are read here, and the bytes at the first choice of one of its
53    /// faces ([`FontDb::load`]). This helper exists only in native builds.
54    ///
55    /// # Errors
56    ///
57    /// Returns the first file that is not added, with the cause: a file that is not a font
58    /// file, one whose bytes are not fonts that the database takes, or one that cannot be read
59    /// (a font file not added). The files before it stay added, and the files
60    /// after it are not read.
61    pub fn add_files(&mut self, files: &[PathBuf]) -> Result<Vec<FontId>, FileNotAdded> {
62        let mut ids = Vec::new();
63        for path in files {
64            let not_added = |cause| FileNotAdded {
65                path: path.clone(),
66                cause,
67            };
68            if !is_font_file(path) {
69                return Err(not_added(NotAddedCause::NotAFontFile));
70            }
71            let (file, descriptions) = read_descriptions(path.clone())
72                .map_err(|error| not_added(NotAddedCause::Unreadable(error)))?
73                .map_err(|error| not_added(NotAddedCause::Font(error)))?;
74            let added = self
75                .add_faces(FaceSource::Folder(file), descriptions, FaceOrigin::Caller)
76                .map_err(|error| not_added(NotAddedCause::Font(error)))?;
77            ids.extend(added);
78        }
79        Ok(ids)
80    }
81}
82
83/// A file that [`FontDb::add_files`] was given and did not add (a font file not added).
84#[derive(Debug)]
85#[non_exhaustive]
86pub struct FileNotAdded {
87    /// The file's path, as the caller gave it.
88    pub path: PathBuf,
89    /// Why the file was not added.
90    pub cause: NotAddedCause,
91}
92
93/// Why [`FontDb::add_files`] did not add a file.
94#[derive(Debug)]
95#[non_exhaustive]
96pub enum NotAddedCause {
97    /// The file's extension is not one of a font file ([`is_font_file`]).
98    NotAFontFile,
99    /// The file's bytes are not fonts that the database takes, as [`FontDb::add_font`] would
100    /// say of them.
101    Font(FontError),
102    /// The file could not be opened or read.
103    Unreadable(io::Error),
104}
105
106impl fmt::Display for FileNotAdded {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        let path = self.path.display();
109        match &self.cause {
110            NotAddedCause::NotAFontFile => write!(
111                f,
112                "{path} is not a font file: its extension is not ttf, otf, ttc or otc"
113            ),
114            NotAddedCause::Font(error) => write!(f, "{path} is not added: {error}"),
115            NotAddedCause::Unreadable(error) => write!(f, "{path} cannot be read: {error}"),
116        }
117    }
118}
119
120impl std::error::Error for FileNotAdded {
121    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
122        match &self.cause {
123            NotAddedCause::NotAFontFile => None,
124            NotAddedCause::Font(error) => Some(error),
125            NotAddedCause::Unreadable(error) => Some(error),
126        }
127    }
128}
129
130impl From<FileNotAdded> for io::Error {
131    /// An I/O error of the file's own kind when it could not be read, and of the kind
132    /// `InvalidData` otherwise, whose message names the file.
133    fn from(not_added: FileNotAdded) -> Self {
134        let kind = match &not_added.cause {
135            NotAddedCause::Unreadable(error) => error.kind(),
136            NotAddedCause::NotAFontFile | NotAddedCause::Font(_) => io::ErrorKind::InvalidData,
137        };
138        Self::new(kind, not_added)
139    }
140}
141
142/// Whether `path` has the extension of a font file: `ttf`, `otf`, `ttc` or `otc`, in any case.
143/// [`FontDb::add_files`] takes only such files.
144#[must_use]
145pub fn is_font_file(path: &Path) -> bool {
146    path.extension()
147        .and_then(|extension| extension.to_str())
148        .is_some_and(|extension| {
149            EXTENSIONS
150                .iter()
151                .any(|known| known.eq_ignore_ascii_case(extension))
152        })
153}
154
155/// A font file of a folder, whose bytes load at the first call of [`FolderFile::load`].
156pub(crate) struct FolderFile {
157    path: PathBuf,
158    /// The file's name, which a warning shows in place of its whole path.
159    name: String,
160    /// The file's length and modification time when its folder was read.
161    stamp: Stamp,
162    /// The number of faces in the file.
163    faces: u32,
164    /// The result of the first load, which every later call gives.
165    loaded: OnceLock<Result<LoadedFile, NotReadCause>>,
166}
167
168impl FolderFile {
169    /// The loaded file, which loads at the first call.
170    ///
171    /// # Errors
172    ///
173    /// Returns the file's name and the cause when the file did not load.
174    pub(crate) fn load(&self) -> Result<&LoadedFile, FileNotRead> {
175        self.loaded().map_err(|cause| FileNotRead {
176            file: self.name.clone(),
177            cause,
178        })
179    }
180
181    /// The loaded file, which loads at the first call, or why it did not load.
182    pub(crate) fn loaded(&self) -> Result<&LoadedFile, NotReadCause> {
183        self.loaded
184            .get_or_init(|| self.read())
185            .as_ref()
186            .map_err(|cause| *cause)
187    }
188
189    /// Reads the file's bytes, when its length and modification time are still the ones of its
190    /// stamp, and the font of each of its faces.
191    fn read(&self) -> Result<LoadedFile, NotReadCause> {
192        let unreadable = |error: io::Error| NotReadCause::Unreadable(error.kind());
193        let mut file = File::open(&self.path).map_err(unreadable)?;
194        if Stamp::of(&file).map_err(unreadable)? != self.stamp {
195            return Err(NotReadCause::Changed);
196        }
197        let mut bytes = Vec::with_capacity(usize::try_from(self.stamp.len).unwrap_or(0));
198        file.read_to_end(&mut bytes).map_err(unreadable)?;
199        if u64::try_from(bytes.len()).ok() != Some(self.stamp.len) {
200            return Err(NotReadCause::Changed);
201        }
202        let data: Arc<[u8]> = bytes.into();
203        let fonts = (0..self.faces)
204            .map(|index| Font::new(Blob::Shared(Arc::new(Arc::clone(&data))), index))
205            .collect::<Option<Vec<_>>>()
206            .ok_or(NotReadCause::Changed)?;
207        Ok(LoadedFile::new(data.into(), fonts))
208    }
209}
210
211/// The length and modification time of a file.
212#[derive(Clone, Copy, Debug, PartialEq, Eq)]
213struct Stamp {
214    len: u64,
215    modified: Option<SystemTime>,
216}
217
218impl Stamp {
219    fn of(file: &File) -> io::Result<Self> {
220        let metadata = file.metadata()?;
221        Ok(Self {
222            len: metadata.len(),
223            modified: metadata.modified().ok(),
224        })
225    }
226}
227
228/// The font file at `path` with the description of each of its faces, in the file's order, or
229/// the error of [`FontDb::add_font`] when it would reject the file's bytes: the file is not an
230/// OpenType font or collection, a face's table directory does not read, or a face lacks a table
231/// that its description needs.
232fn read_descriptions(
233    path: PathBuf,
234) -> io::Result<Result<(FolderFile, Vec<FaceDescription>), FontError>> {
235    let mut file = File::open(&path)?;
236    let stamp = Stamp::of(&file)?;
237    let mut start = Start {
238        file: &mut file,
239        len: stamp.len,
240        bytes: Vec::new(),
241    };
242    let Some(directories) = start.directories()? else {
243        return Ok(Err(FontError::NotAFont));
244    };
245    let mut tables = HashMap::new();
246    let mut descriptions = Vec::new();
247    for records in &directories {
248        let font = start.description_font(records, &mut tables)?;
249        match font.as_ref().map(FaceDescription::read) {
250            Some(Ok(description)) => descriptions.push(description),
251            Some(Err(error)) => return Ok(Err(error)),
252            None => return Ok(Err(FontError::NotAFont)),
253        }
254    }
255    let Ok(faces) = u32::try_from(descriptions.len()) else {
256        return Ok(Err(FontError::TooManyFaces));
257    };
258    let name = path
259        .file_name()
260        .map_or_else(String::new, |name| name.to_string_lossy().into_owned());
261    let file = FolderFile {
262        path,
263        name,
264        stamp,
265        faces,
266        loaded: OnceLock::new(),
267    };
268    Ok(Ok((file, descriptions)))
269}
270
271/// The table records of a face's table directory: each table's tag, offset and length.
272type Records = Vec<(Tag, u32, u32)>;
273
274/// The table records of a face's table directory, or `OutOfBounds` when the bytes end before
275/// its last record. `skrifa` reads a directory whose bytes end there as one without records, so
276/// the parse must ask for more of the file itself; the whole file gives the same face no tables,
277/// which [`FaceDescription::read`] rejects, as this error does.
278fn records(directory: &TableDirectory<'_>) -> Result<Records, ReadError> {
279    if directory.offset_data().len() < directory.min_byte_range().end {
280        return Err(ReadError::OutOfBounds);
281    }
282    let records = directory.table_records().iter();
283    Ok(records
284        .map(|record| (record.tag(), record.offset(), record.length()))
285        .collect())
286}
287
288/// A font file and the bytes of its start that are read so far.
289struct Start<'a> {
290    file: &'a mut File,
291    /// The file's length.
292    len: u64,
293    bytes: Vec<u8>,
294}
295
296impl Start<'_> {
297    /// The table records of each face of the file, in the file's order, as `skrifa` reads them
298    /// from the whole file when it makes the face's font, or `None` when it would make none: the
299    /// file is not an OpenType font or collection, or a face's table directory does not read.
300    fn directories(&mut self) -> io::Result<Option<Vec<Records>>> {
301        let tag = self.parse(|bytes| {
302            bytes
303                .get(..4)
304                .ok_or(ReadError::OutOfBounds)
305                .map(<[u8]>::to_vec)
306        })?;
307        if tag.ok().as_deref() != Some(COLLECTION_TAG) {
308            let face = self.parse(|bytes| records(FontRef::new(bytes)?.table_directory()))?;
309            return Ok(face.ok().map(|face| vec![face]));
310        }
311        let Ok(count) = self.parse(|bytes| CollectionRef::new(bytes).map(|fonts| fonts.len()))?
312        else {
313            return Ok(None);
314        };
315        let mut faces = Vec::new();
316        for index in 0..count {
317            let face = self.parse(|bytes| {
318                let font = CollectionRef::new(bytes)?.get(index)?;
319                records(font.table_directory())
320            })?;
321            let Ok(face) = face else {
322                return Ok(None);
323            };
324            faces.push(face);
325        }
326        Ok(Some(faces))
327    }
328
329    /// Parses the bytes read so far with `parse`, and reads more of the file while the parse runs
330    /// out of bytes before the end of the file. A parse that reads each value at its place in the
331    /// bytes so gives the result that it gives on the whole file.
332    fn parse<T>(
333        &mut self,
334        parse: impl Fn(&[u8]) -> Result<T, ReadError>,
335    ) -> io::Result<Result<T, ReadError>> {
336        loop {
337            let parsed = parse(&self.bytes);
338            if !matches!(parsed, Err(ReadError::OutOfBounds)) || !self.read_more()? {
339                return Ok(parsed);
340            }
341        }
342    }
343
344    /// Reads as many bytes again as are read so far, at least [`FIRST_READ`] and at most to the
345    /// end of the file, and returns whether any came.
346    fn read_more(&mut self) -> io::Result<bool> {
347        let had = u64::try_from(self.bytes.len()).unwrap_or(u64::MAX);
348        let more = had.max(FIRST_READ).min(self.len.saturating_sub(had));
349        self.file.seek(SeekFrom::Start(had))?;
350        (&mut *self.file).take(more).read_to_end(&mut self.bytes)?;
351        Ok(u64::try_from(self.bytes.len()).unwrap_or(u64::MAX) > had)
352    }
353
354    /// The font of a face's description: the tables of [`DESCRIPTION_TABLES`] that `records`
355    /// list within the file, as `skrifa`'s font of the whole file finds them (the first record
356    /// of each tag, and a record at offset 0 as a table at the file's start), and no other
357    /// table. `read` keeps each table that is read, by offset and length, for the faces of a
358    /// collection that share it.
359    fn description_font(
360        &mut self,
361        records: &Records,
362        read: &mut HashMap<(u32, u32), Blob>,
363    ) -> io::Result<Option<Font>> {
364        let mut tables = Vec::new();
365        for tag in DESCRIPTION_TABLES {
366            let Some(&(_, offset, length)) = records.iter().find(|(listed, ..)| *listed == tag)
367            else {
368                continue;
369            };
370            if offset
371                .checked_add(length)
372                .is_none_or(|end| u64::from(end) > self.len)
373            {
374                continue;
375            }
376            let blob = match read.get(&(offset, length)) {
377                Some(blob) => blob.clone(),
378                None => self.table(offset, length)?,
379            };
380            read.insert((offset, length), blob.clone());
381            tables.push((tag, blob));
382        }
383        let source: Arc<dyn Fn(Tag) -> Option<Blob> + Send + Sync> = Arc::new(move |tag| {
384            let found = tables.iter().find(|(listed, _)| *listed == tag);
385            found.map(|(_, blob)| blob.clone())
386        });
387        Ok(Font::new(source, 0))
388    }
389
390    /// The bytes of the table at `offset` with `length`, which lies within the file.
391    fn table(&mut self, offset: u32, length: u32) -> io::Result<Blob> {
392        let start = usize::try_from(offset).unwrap_or(usize::MAX);
393        let end = start.saturating_add(usize::try_from(length).unwrap_or(usize::MAX));
394        if let Some(bytes) = self.bytes.get(start..end) {
395            return Ok(Blob::from(bytes.to_vec()));
396        }
397        self.file.seek(SeekFrom::Start(u64::from(offset)))?;
398        let mut bytes = Vec::with_capacity(usize::try_from(length).unwrap_or(0));
399        (&mut *self.file)
400            .take(u64::from(length))
401            .read_to_end(&mut bytes)?;
402        if bytes.len() != usize::try_from(length).unwrap_or(usize::MAX) {
403            return Err(io::ErrorKind::UnexpectedEof.into());
404        }
405        Ok(Blob::from(bytes))
406    }
407}
408
409#[cfg(test)]
410mod tests;