f-office-fonts 0.3.0

Font database, metrics and outlines.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! Loading font files by their paths, for native builds.
//!
//! [`FontDb::add_files`] reads of each file only what the faces' descriptions need: the start
//! of the file that holds its table directories, and the tables that
//! [`FaceDescription::read`] reads. It keeps the file's length and modification time, and the
//! file's bytes load at the first choice of one of its faces ([`FontDb::load`]).

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};

/// File extensions of OpenType fonts and font collections.
const EXTENSIONS: [&str; 4] = ["ttf", "otf", "ttc", "otc"];

/// The tables that a face's description reads ([`FaceDescription::read`]).
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"),
];

/// The first four bytes of a font collection.
const COLLECTION_TAG: &[u8] = b"ttcf";

/// The bytes of a file's start that are read first, and the fewest bytes that are read when the
/// parse of its table directories needs more.
const FIRST_READ: u64 = 4096;

impl FontDb {
    /// Adds the fonts of the files `files`, in the order given, and returns the new IDs.
    ///
    /// The faces take their IDs in the order of `files`, and so does the choice between two
    /// faces of equal style: the face query keeps the first ([`FontDb::query`]). The order is
    /// the caller's, the order of its font sources, and never the files' names. Each file must
    /// be a font file ([`is_font_file`]) that holds fonts that [`FontDb::add_font`] would take
    /// from its bytes. Of each file, only the table directories and the tables of the faces'
    /// names, style and metrics are read here, and the bytes at the first choice of one of its
    /// faces ([`FontDb::load`]). This helper exists only in native builds.
    ///
    /// # Errors
    ///
    /// Returns the first file that is not added, with the cause: a file that is not a font
    /// file, one whose bytes are not fonts that the database takes, or one that cannot be read
    /// (a font file not added). The files before it stay added, and the files
    /// after it are not read.
    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)
    }
}

/// A file that [`FontDb::add_files`] was given and did not add (a font file not added).
#[derive(Debug)]
#[non_exhaustive]
pub struct FileNotAdded {
    /// The file's path, as the caller gave it.
    pub path: PathBuf,
    /// Why the file was not added.
    pub cause: NotAddedCause,
}

/// Why [`FontDb::add_files`] did not add a file.
#[derive(Debug)]
#[non_exhaustive]
pub enum NotAddedCause {
    /// The file's extension is not one of a font file ([`is_font_file`]).
    NotAFontFile,
    /// The file's bytes are not fonts that the database takes, as [`FontDb::add_font`] would
    /// say of them.
    Font(FontError),
    /// The file could not be opened or read.
    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 {
    /// An I/O error of the file's own kind when it could not be read, and of the kind
    /// `InvalidData` otherwise, whose message names the file.
    fn from(not_added: FileNotAdded) -> Self {
        let kind = match &not_added.cause {
            NotAddedCause::Unreadable(error) => error.kind(),
            NotAddedCause::NotAFontFile | NotAddedCause::Font(_) => io::ErrorKind::InvalidData,
        };
        Self::new(kind, not_added)
    }
}

/// Whether `path` has the extension of a font file: `ttf`, `otf`, `ttc` or `otc`, in any case.
/// [`FontDb::add_files`] takes only such files.
#[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))
        })
}

/// A font file of a folder, whose bytes load at the first call of [`FolderFile::load`].
pub(crate) struct FolderFile {
    path: PathBuf,
    /// The file's name, which a warning shows in place of its whole path.
    name: String,
    /// The file's length and modification time when its folder was read.
    stamp: Stamp,
    /// The number of faces in the file.
    faces: u32,
    /// The result of the first load, which every later call gives.
    loaded: OnceLock<Result<LoadedFile, NotReadCause>>,
}

impl FolderFile {
    /// The loaded file, which loads at the first call.
    ///
    /// # Errors
    ///
    /// Returns the file's name and the cause when the file did not load.
    pub(crate) fn load(&self) -> Result<&LoadedFile, FileNotRead> {
        self.loaded().map_err(|cause| FileNotRead {
            file: self.name.clone(),
            cause,
        })
    }

    /// The loaded file, which loads at the first call, or why it did not load.
    pub(crate) fn loaded(&self) -> Result<&LoadedFile, NotReadCause> {
        self.loaded
            .get_or_init(|| self.read())
            .as_ref()
            .map_err(|cause| *cause)
    }

    /// Reads the file's bytes, when its length and modification time are still the ones of its
    /// stamp, and the font of each of its faces.
    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))
    }
}

/// The length and modification time of a file.
#[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(),
        })
    }
}

/// The font file at `path` with the description of each of its faces, in the file's order, or
/// the error of [`FontDb::add_font`] when it would reject the file's bytes: the file is not an
/// OpenType font or collection, a face's table directory does not read, or a face lacks a table
/// that its description needs.
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)))
}

/// The table records of a face's table directory: each table's tag, offset and length.
type Records = Vec<(Tag, u32, u32)>;

/// The table records of a face's table directory, or `OutOfBounds` when the bytes end before
/// its last record. `skrifa` reads a directory whose bytes end there as one without records, so
/// the parse must ask for more of the file itself; the whole file gives the same face no tables,
/// which [`FaceDescription::read`] rejects, as this error does.
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())
}

/// A font file and the bytes of its start that are read so far.
struct Start<'a> {
    file: &'a mut File,
    /// The file's length.
    len: u64,
    bytes: Vec<u8>,
}

impl Start<'_> {
    /// The table records of each face of the file, in the file's order, as `skrifa` reads them
    /// from the whole file when it makes the face's font, or `None` when it would make none: the
    /// file is not an OpenType font or collection, or a face's table directory does not read.
    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))
    }

    /// Parses the bytes read so far with `parse`, and reads more of the file while the parse runs
    /// out of bytes before the end of the file. A parse that reads each value at its place in the
    /// bytes so gives the result that it gives on the whole file.
    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);
            }
        }
    }

    /// Reads as many bytes again as are read so far, at least [`FIRST_READ`] and at most to the
    /// end of the file, and returns whether any came.
    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)
    }

    /// The font of a face's description: the tables of [`DESCRIPTION_TABLES`] that `records`
    /// list within the file, as `skrifa`'s font of the whole file finds them (the first record
    /// of each tag, and a record at offset 0 as a table at the file's start), and no other
    /// table. `read` keeps each table that is read, by offset and length, for the faces of a
    /// collection that share it.
    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))
    }

    /// The bytes of the table at `offset` with `length`, which lies within the file.
    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;