Skip to main content

f_office_fonts/
lib.rs

1//! Font database.
2//!
3//! This crate loads font files from bytes that the caller passes, indexes them by family and
4//! style, and reads their metrics and glyph outlines. Loading from a folder is a helper for
5//! native builds only, because a WASM build has no file system: it reads the names, style and
6//! metrics of each face at once, and the bytes of a file at the first choice of one of its
7//! faces ([`FontDb::load`]). The rules that choose a font for a piece of text belong to the
8//! format crates, because each Office app has its own.
9//!
10//! Every value is in font units, as the font stores it, so that the format crates decide how to
11//! scale and round.
12
13#![deny(clippy::float_arithmetic)]
14
15mod bilevel;
16pub mod environment;
17mod face;
18mod family_name;
19mod file;
20#[cfg(not(target_arch = "wasm32"))]
21mod folder;
22mod form;
23mod glyph;
24mod kerning;
25mod layout_values;
26mod ligature;
27mod math;
28mod metrics;
29#[cfg(feature = "open-fonts")]
30pub mod open_fonts;
31mod query;
32mod script_glyphs;
33mod shape;
34mod symbol_map;
35mod vdmx;
36
37use std::fmt;
38use std::ops::Range;
39use std::sync::Arc;
40
41pub use compatifont::Description;
42pub use f_office_truetype::plain_device_width;
43use skrifa::font::{Font, Format};
44
45use crate::face::{Face, FaceDescription};
46pub use crate::face::{FaceClassification, FaceInfo, version_number};
47pub use crate::family_name::FamilyName;
48pub use crate::file::{FaceOrigin, FileNotRead, FontBytes, NotReadCause};
49use crate::file::{FaceSource, LoadedFile};
50#[cfg(not(target_arch = "wasm32"))]
51pub use crate::folder::{FileNotAdded, NotAddedCause, is_font_file};
52pub use crate::glyph::{OutlineError, PathCommand, Point};
53pub use crate::kerning::KerningSource;
54pub use crate::layout_values::{
55    Comparison, Difference, KindComparison, LayoutValues, Place, ValueKind, Values,
56};
57pub use crate::ligature::Ligature;
58pub use crate::math::{
59    AssemblyPart, HorizontalConstruction, MathAccent, MathBars, MathCorner, MathLimitGaps,
60    MathLimits, MathRadical, MathSkewedFraction, MathStretchStack,
61};
62pub use crate::metrics::{Decoration, FontMetrics, LineMetrics, Os2Metrics, ScriptMetrics};
63pub use crate::script_glyphs::ScriptLevel;
64pub use crate::shape::{ShapeDirection, ShapeFailure, ShapeRequest, ShapedGlyph, ShapedScript};
65pub use crate::symbol_map::SymbolFont;
66
67/// Identifies one font face in the font database.
68#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
69pub struct FontId(u32);
70
71impl FontId {
72    /// Makes an ID from the index of the face in the database.
73    #[must_use]
74    pub const fn from_index(index: u32) -> Self {
75        Self(index)
76    }
77
78    /// Returns the index of the face in the database.
79    #[must_use]
80    pub const fn index(self) -> u32 {
81        self.0
82    }
83}
84
85/// Why font data could not be added.
86#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87pub enum FontError {
88    /// The data is not an OpenType font or font collection.
89    NotAFont,
90    /// A face lacks a table that the database needs, or the table is malformed. The value is
91    /// the table tag.
92    BadTable(&'static str),
93    /// The database cannot hold more faces.
94    TooManyFaces,
95}
96
97impl fmt::Display for FontError {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        match self {
100            Self::NotAFont => f.write_str("the data is not an OpenType font"),
101            Self::BadTable(tag) => write!(f, "the font's {tag} table is missing or malformed"),
102            Self::TooManyFaces => f.write_str("the font database is full"),
103        }
104    }
105}
106
107impl std::error::Error for FontError {}
108
109/// Font faces loaded from bytes, addressed by [`FontId`].
110#[derive(Default)]
111pub struct FontDb {
112    faces: Vec<Face>,
113    descriptions: Vec<Description>,
114}
115
116impl fmt::Debug for FontDb {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        f.debug_struct("FontDb")
119            .field("faces", &self.faces.len())
120            .field("descriptions", &self.descriptions.len())
121            .finish_non_exhaustive()
122    }
123}
124
125impl FontDb {
126    /// Makes an empty database.
127    #[must_use]
128    pub fn new() -> Self {
129        Self::default()
130    }
131
132    /// Adds every face in an OpenType font or font collection, and returns their IDs in the
133    /// order of the faces in the data.
134    ///
135    /// When built with the `woff2` feature, WOFF2 containers (`wOF2`) are transparently
136    /// decompressed to OpenType before indexing. Full-table WOFF2 files preserve exact layout
137    /// metrics, while web-subsetted WOFF2 files may omit glyphs or OpenType tables needed for
138    /// exact Word line breaks.
139    ///
140    /// This is the only way to load fonts in a WASM build. When one face fails to load, no
141    /// face is added.
142    ///
143    /// # Errors
144    ///
145    /// Returns an error when the data is not an OpenType font or collection (or a valid WOFF2
146    /// font when `woff2` is enabled), or when a face lacks the `head`, `hhea` or `hmtx` table.
147    pub fn add_font(&mut self, data: impl Into<Arc<[u8]>>) -> Result<Vec<FontId>, FontError> {
148        let data: Arc<[u8]> = data.into();
149        self.add_bytes(data.into(), FaceOrigin::Caller)
150    }
151
152    /// Adds every face of an OpenType font or font collection compiled into the program, such
153    /// as a built-in font, without a copy of its bytes, and returns their IDs in the order of
154    /// the faces in the data. The faces read as the faces of [`FontDb::add_font`] do, also in a
155    /// WASM build; of two faces with the same family, style and weight, [`FontDb::query`]
156    /// takes the one that the caller added.
157    ///
158    /// # Errors
159    ///
160    /// As for [`FontDb::add_font`]; then no face is added.
161    pub fn add_static(&mut self, data: &'static [u8]) -> Result<Vec<FontId>, FontError> {
162        self.add_bytes(data.into(), FaceOrigin::BuiltIn)
163    }
164
165    fn add_bytes(&mut self, data: FontBytes, origin: FaceOrigin) -> Result<Vec<FontId>, FontError> {
166        #[cfg(feature = "woff2")]
167        let data = if data.starts_with(b"wOF2") {
168            let decoded = wuff::decompress_woff2(&data).map_err(|_| FontError::NotAFont)?;
169            FontBytes::from(Arc::<[u8]>::from(decoded))
170        } else {
171            data
172        };
173        let Some(Format::Sfnt(count)) = Format::new(&data) else {
174            return Err(FontError::NotAFont);
175        };
176        let mut fonts = Vec::new();
177        let mut descriptions = Vec::new();
178        for index in 0..count {
179            let font = Font::new(data.blob(), index).ok_or(FontError::NotAFont)?;
180            descriptions.push(FaceDescription::read(&font)?);
181            fonts.push(font);
182        }
183        let source = FaceSource::Given(LoadedFile::new(data, fonts));
184        self.add_faces(source, descriptions, origin)
185    }
186
187    /// Adds the faces of the file of `source`, one for each description in the file's order,
188    /// and returns their IDs.
189    fn add_faces(
190        &mut self,
191        source: FaceSource,
192        descriptions: Vec<FaceDescription>,
193        origin: FaceOrigin,
194    ) -> Result<Vec<FontId>, FontError> {
195        let ids = self.next_ids(descriptions.len())?;
196        let source = Arc::new(source);
197        let faces = descriptions
198            .into_iter()
199            .zip(0..)
200            .map(|(description, index)| Face::new(description, Arc::clone(&source), index, origin));
201        self.faces.extend(faces);
202        Ok(ids.map(FontId).collect())
203    }
204
205    /// Loads the bytes of the file that holds a face, when they are not loaded yet.
206    ///
207    /// Only a file that [`FontDb::add_files`] added loads here, at the first call for one of
208    /// its faces, and only once: every later call for a face of the file, from any thread,
209    /// gives the result of the first. The file's length and modification time must still be
210    /// the ones that `add_files` found. Every method that reads a face's bytes loads them in
211    /// the same way, and answers for a face whose file did not load as for an unknown face. A
212    /// font choice calls this for the face that it chooses, so that such a face counts as
213    /// missing and the choice searches again without it.
214    ///
215    /// # Errors
216    ///
217    /// Returns the file's name in its folder and the cause when the file did not load. An
218    /// unknown face has nothing to load and gives `Ok`.
219    pub fn load(&self, id: FontId) -> Result<(), FileNotRead> {
220        self.face(id)
221            .map_or(Ok(()), |face| face.source.load().map(|_| ()))
222    }
223
224    /// Adds the description of a font family in the Compatifont format: its files with their
225    /// SHA-256, and the other families that its faces can replace with the values that they
226    /// share. The rules of the format crates read it to choose a family that draws a missing
227    /// one, and to know a face that lays out as the target's own.
228    pub fn add_description(&mut self, description: Description) {
229        self.descriptions.push(description);
230    }
231
232    /// Returns the descriptions in the order they were added.
233    #[must_use]
234    pub fn descriptions(&self) -> &[Description] {
235        &self.descriptions
236    }
237
238    /// Returns the number of faces.
239    #[must_use]
240    pub fn len(&self) -> usize {
241        self.faces.len()
242    }
243
244    /// Returns `true` when the database holds no face.
245    #[must_use]
246    pub fn is_empty(&self) -> bool {
247        self.faces.is_empty()
248    }
249
250    /// Returns every face with its ID, in the order they were added.
251    pub fn faces(&self) -> impl Iterator<Item = (FontId, &FaceInfo)> {
252        self.indexed().map(|(id, face)| (id, &face.info))
253    }
254
255    /// Returns the names and style of a face.
256    #[must_use]
257    pub fn info(&self, id: FontId) -> Option<&FaceInfo> {
258        self.face(id).map(|face| &face.info)
259    }
260
261    /// Returns where a face came from.
262    #[must_use]
263    pub fn origin(&self, id: FontId) -> Option<FaceOrigin> {
264        self.face(id).map(|face| face.origin)
265    }
266
267    /// Returns the font-wide metrics of a face, in font units.
268    #[must_use]
269    pub fn metrics(&self, id: FontId) -> Option<&FontMetrics> {
270        self.face(id).map(|face| &face.metrics)
271    }
272
273    /// Returns the bytes of the font file that holds a face, with the index of the face in it.
274    ///
275    /// The bytes are the ones that [`FontDb::add_font`] or [`FontDb::add_static`] took, or that a
276    /// file of a folder held,
277    /// so the faces of one collection share them and differ by index. Output crates pass them
278    /// on to embed the font. Returns `None` for an unknown face and a face whose file did not
279    /// load ([`FontDb::load`]).
280    #[must_use]
281    pub fn data(&self, id: FontId) -> Option<(&FontBytes, u32)> {
282        let face = self.face(id)?;
283        Some((face.data()?, face.index))
284    }
285
286    fn indexed(&self) -> impl Iterator<Item = (FontId, &Face)> {
287        (0..).map(FontId).zip(&self.faces)
288    }
289
290    fn face(&self, id: FontId) -> Option<&Face> {
291        self.faces.get(usize::try_from(id.0).ok()?)
292    }
293
294    fn next_ids(&self, count: usize) -> Result<Range<u32>, FontError> {
295        let start = self.faces.len();
296        let end = start.checked_add(count).ok_or(FontError::TooManyFaces)?;
297        let index = |value: usize| u32::try_from(value).map_err(|_| FontError::TooManyFaces);
298        Ok(index(start)?..index(end)?)
299    }
300}
301
302#[cfg(test)]
303mod tests;