1use 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
24const EXTENSIONS: [&str; 4] = ["ttf", "otf", "ttc", "otc"];
26
27const 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
37const COLLECTION_TAG: &[u8] = b"ttcf";
39
40const FIRST_READ: u64 = 4096;
43
44impl FontDb {
45 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#[derive(Debug)]
85#[non_exhaustive]
86pub struct FileNotAdded {
87 pub path: PathBuf,
89 pub cause: NotAddedCause,
91}
92
93#[derive(Debug)]
95#[non_exhaustive]
96pub enum NotAddedCause {
97 NotAFontFile,
99 Font(FontError),
102 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 fn from(not_added: FileNotAdded) -> Self {
134 let kind = match ¬_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#[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
155pub(crate) struct FolderFile {
157 path: PathBuf,
158 name: String,
160 stamp: Stamp,
162 faces: u32,
164 loaded: OnceLock<Result<LoadedFile, NotReadCause>>,
166}
167
168impl FolderFile {
169 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 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 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#[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
228fn 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
271type Records = Vec<(Tag, u32, u32)>;
273
274fn 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
288struct Start<'a> {
290 file: &'a mut File,
291 len: u64,
293 bytes: Vec<u8>,
294}
295
296impl Start<'_> {
297 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 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 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 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 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;