1#![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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
69pub struct FontId(u32);
70
71impl FontId {
72 #[must_use]
74 pub const fn from_index(index: u32) -> Self {
75 Self(index)
76 }
77
78 #[must_use]
80 pub const fn index(self) -> u32 {
81 self.0
82 }
83}
84
85#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87pub enum FontError {
88 NotAFont,
90 BadTable(&'static str),
93 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#[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 #[must_use]
128 pub fn new() -> Self {
129 Self::default()
130 }
131
132 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 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 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 pub fn load(&self, id: FontId) -> Result<(), FileNotRead> {
220 self.face(id)
221 .map_or(Ok(()), |face| face.source.load().map(|_| ()))
222 }
223
224 pub fn add_description(&mut self, description: Description) {
229 self.descriptions.push(description);
230 }
231
232 #[must_use]
234 pub fn descriptions(&self) -> &[Description] {
235 &self.descriptions
236 }
237
238 #[must_use]
240 pub fn len(&self) -> usize {
241 self.faces.len()
242 }
243
244 #[must_use]
246 pub fn is_empty(&self) -> bool {
247 self.faces.is_empty()
248 }
249
250 pub fn faces(&self) -> impl Iterator<Item = (FontId, &FaceInfo)> {
252 self.indexed().map(|(id, face)| (id, &face.info))
253 }
254
255 #[must_use]
257 pub fn info(&self, id: FontId) -> Option<&FaceInfo> {
258 self.face(id).map(|face| &face.info)
259 }
260
261 #[must_use]
263 pub fn origin(&self, id: FontId) -> Option<FaceOrigin> {
264 self.face(id).map(|face| face.origin)
265 }
266
267 #[must_use]
269 pub fn metrics(&self, id: FontId) -> Option<&FontMetrics> {
270 self.face(id).map(|face| &face.metrics)
271 }
272
273 #[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;