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
//! Font database.
//!
//! This crate loads font files from bytes that the caller passes, indexes them by family and
//! style, and reads their metrics and glyph outlines. Loading from a folder is a helper for
//! native builds only, because a WASM build has no file system: it reads the names, style and
//! metrics of each face at once, and the bytes of a file at the first choice of one of its
//! faces ([`FontDb::load`]). The rules that choose a font for a piece of text belong to the
//! format crates, because each Office app has its own.
//!
//! Every value is in font units, as the font stores it, so that the format crates decide how to
//! scale and round.
#![deny(clippy::float_arithmetic)]
mod bilevel;
pub mod environment;
mod face;
mod family_name;
mod file;
#[cfg(not(target_arch = "wasm32"))]
mod folder;
mod form;
mod glyph;
mod kerning;
mod layout_values;
mod ligature;
mod math;
mod metrics;
#[cfg(feature = "open-fonts")]
pub mod open_fonts;
mod query;
mod script_glyphs;
mod shape;
mod symbol_map;
mod vdmx;
use std::fmt;
use std::ops::Range;
use std::sync::Arc;
pub use compatifont::Description;
pub use f_office_truetype::plain_device_width;
use skrifa::font::{Font, Format};
use crate::face::{Face, FaceDescription};
pub use crate::face::{FaceClassification, FaceInfo, version_number};
pub use crate::family_name::FamilyName;
pub use crate::file::{FaceOrigin, FileNotRead, FontBytes, NotReadCause};
use crate::file::{FaceSource, LoadedFile};
#[cfg(not(target_arch = "wasm32"))]
pub use crate::folder::{FileNotAdded, NotAddedCause, is_font_file};
pub use crate::glyph::{OutlineError, PathCommand, Point};
pub use crate::kerning::KerningSource;
pub use crate::layout_values::{
Comparison, Difference, KindComparison, LayoutValues, Place, ValueKind, Values,
};
pub use crate::ligature::Ligature;
pub use crate::math::{
AssemblyPart, HorizontalConstruction, MathAccent, MathBars, MathCorner, MathLimitGaps,
MathLimits, MathRadical, MathSkewedFraction, MathStretchStack,
};
pub use crate::metrics::{Decoration, FontMetrics, LineMetrics, Os2Metrics, ScriptMetrics};
pub use crate::script_glyphs::ScriptLevel;
pub use crate::shape::{ShapeDirection, ShapeFailure, ShapeRequest, ShapedGlyph, ShapedScript};
pub use crate::symbol_map::SymbolFont;
/// Identifies one font face in the font database.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FontId(u32);
impl FontId {
/// Makes an ID from the index of the face in the database.
#[must_use]
pub const fn from_index(index: u32) -> Self {
Self(index)
}
/// Returns the index of the face in the database.
#[must_use]
pub const fn index(self) -> u32 {
self.0
}
}
/// Why font data could not be added.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FontError {
/// The data is not an OpenType font or font collection.
NotAFont,
/// A face lacks a table that the database needs, or the table is malformed. The value is
/// the table tag.
BadTable(&'static str),
/// The database cannot hold more faces.
TooManyFaces,
}
impl fmt::Display for FontError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NotAFont => f.write_str("the data is not an OpenType font"),
Self::BadTable(tag) => write!(f, "the font's {tag} table is missing or malformed"),
Self::TooManyFaces => f.write_str("the font database is full"),
}
}
}
impl std::error::Error for FontError {}
/// Font faces loaded from bytes, addressed by [`FontId`].
#[derive(Default)]
pub struct FontDb {
faces: Vec<Face>,
descriptions: Vec<Description>,
}
impl fmt::Debug for FontDb {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FontDb")
.field("faces", &self.faces.len())
.field("descriptions", &self.descriptions.len())
.finish_non_exhaustive()
}
}
impl FontDb {
/// Makes an empty database.
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Adds every face in an OpenType font or font collection, and returns their IDs in the
/// order of the faces in the data.
///
/// When built with the `woff2` feature, WOFF2 containers (`wOF2`) are transparently
/// decompressed to OpenType before indexing. Full-table WOFF2 files preserve exact layout
/// metrics, while web-subsetted WOFF2 files may omit glyphs or OpenType tables needed for
/// exact Word line breaks.
///
/// This is the only way to load fonts in a WASM build. When one face fails to load, no
/// face is added.
///
/// # Errors
///
/// Returns an error when the data is not an OpenType font or collection (or a valid WOFF2
/// font when `woff2` is enabled), or when a face lacks the `head`, `hhea` or `hmtx` table.
pub fn add_font(&mut self, data: impl Into<Arc<[u8]>>) -> Result<Vec<FontId>, FontError> {
let data: Arc<[u8]> = data.into();
self.add_bytes(data.into(), FaceOrigin::Caller)
}
/// Adds every face of an OpenType font or font collection compiled into the program, such
/// as a built-in font, without a copy of its bytes, and returns their IDs in the order of
/// the faces in the data. The faces read as the faces of [`FontDb::add_font`] do, also in a
/// WASM build; of two faces with the same family, style and weight, [`FontDb::query`]
/// takes the one that the caller added.
///
/// # Errors
///
/// As for [`FontDb::add_font`]; then no face is added.
pub fn add_static(&mut self, data: &'static [u8]) -> Result<Vec<FontId>, FontError> {
self.add_bytes(data.into(), FaceOrigin::BuiltIn)
}
fn add_bytes(&mut self, data: FontBytes, origin: FaceOrigin) -> Result<Vec<FontId>, FontError> {
#[cfg(feature = "woff2")]
let data = if data.starts_with(b"wOF2") {
let decoded = wuff::decompress_woff2(&data).map_err(|_| FontError::NotAFont)?;
FontBytes::from(Arc::<[u8]>::from(decoded))
} else {
data
};
let Some(Format::Sfnt(count)) = Format::new(&data) else {
return Err(FontError::NotAFont);
};
let mut fonts = Vec::new();
let mut descriptions = Vec::new();
for index in 0..count {
let font = Font::new(data.blob(), index).ok_or(FontError::NotAFont)?;
descriptions.push(FaceDescription::read(&font)?);
fonts.push(font);
}
let source = FaceSource::Given(LoadedFile::new(data, fonts));
self.add_faces(source, descriptions, origin)
}
/// Adds the faces of the file of `source`, one for each description in the file's order,
/// and returns their IDs.
fn add_faces(
&mut self,
source: FaceSource,
descriptions: Vec<FaceDescription>,
origin: FaceOrigin,
) -> Result<Vec<FontId>, FontError> {
let ids = self.next_ids(descriptions.len())?;
let source = Arc::new(source);
let faces = descriptions
.into_iter()
.zip(0..)
.map(|(description, index)| Face::new(description, Arc::clone(&source), index, origin));
self.faces.extend(faces);
Ok(ids.map(FontId).collect())
}
/// Loads the bytes of the file that holds a face, when they are not loaded yet.
///
/// Only a file that [`FontDb::add_files`] added loads here, at the first call for one of
/// its faces, and only once: every later call for a face of the file, from any thread,
/// gives the result of the first. The file's length and modification time must still be
/// the ones that `add_files` found. Every method that reads a face's bytes loads them in
/// the same way, and answers for a face whose file did not load as for an unknown face. A
/// font choice calls this for the face that it chooses, so that such a face counts as
/// missing and the choice searches again without it.
///
/// # Errors
///
/// Returns the file's name in its folder and the cause when the file did not load. An
/// unknown face has nothing to load and gives `Ok`.
pub fn load(&self, id: FontId) -> Result<(), FileNotRead> {
self.face(id)
.map_or(Ok(()), |face| face.source.load().map(|_| ()))
}
/// Adds the description of a font family in the Compatifont format: its files with their
/// SHA-256, and the other families that its faces can replace with the values that they
/// share. The rules of the format crates read it to choose a family that draws a missing
/// one, and to know a face that lays out as the target's own.
pub fn add_description(&mut self, description: Description) {
self.descriptions.push(description);
}
/// Returns the descriptions in the order they were added.
#[must_use]
pub fn descriptions(&self) -> &[Description] {
&self.descriptions
}
/// Returns the number of faces.
#[must_use]
pub fn len(&self) -> usize {
self.faces.len()
}
/// Returns `true` when the database holds no face.
#[must_use]
pub fn is_empty(&self) -> bool {
self.faces.is_empty()
}
/// Returns every face with its ID, in the order they were added.
pub fn faces(&self) -> impl Iterator<Item = (FontId, &FaceInfo)> {
self.indexed().map(|(id, face)| (id, &face.info))
}
/// Returns the names and style of a face.
#[must_use]
pub fn info(&self, id: FontId) -> Option<&FaceInfo> {
self.face(id).map(|face| &face.info)
}
/// Returns where a face came from.
#[must_use]
pub fn origin(&self, id: FontId) -> Option<FaceOrigin> {
self.face(id).map(|face| face.origin)
}
/// Returns the font-wide metrics of a face, in font units.
#[must_use]
pub fn metrics(&self, id: FontId) -> Option<&FontMetrics> {
self.face(id).map(|face| &face.metrics)
}
/// Returns the bytes of the font file that holds a face, with the index of the face in it.
///
/// The bytes are the ones that [`FontDb::add_font`] or [`FontDb::add_static`] took, or that a
/// file of a folder held,
/// so the faces of one collection share them and differ by index. Output crates pass them
/// on to embed the font. Returns `None` for an unknown face and a face whose file did not
/// load ([`FontDb::load`]).
#[must_use]
pub fn data(&self, id: FontId) -> Option<(&FontBytes, u32)> {
let face = self.face(id)?;
Some((face.data()?, face.index))
}
fn indexed(&self) -> impl Iterator<Item = (FontId, &Face)> {
(0..).map(FontId).zip(&self.faces)
}
fn face(&self, id: FontId) -> Option<&Face> {
self.faces.get(usize::try_from(id.0).ok()?)
}
fn next_ids(&self, count: usize) -> Result<Range<u32>, FontError> {
let start = self.faces.len();
let end = start.checked_add(count).ok_or(FontError::TooManyFaces)?;
let index = |value: usize| u32::try_from(value).map_err(|_| FontError::TooManyFaces);
Ok(index(start)?..index(end)?)
}
}
#[cfg(test)]
mod tests;