typst_kit/fonts.rs
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
//! Default implementation for searching local and system installed fonts as
//! well as loading embedded default fonts.
//!
//! # Embedded fonts
//! The following fonts are available as embedded fonts via the `embed-fonts`
//! feature flag:
//! - For text: Libertinus Serif, New Computer Modern
//! - For math: New Computer Modern Math
//! - For code: Deja Vu Sans Mono
use std::path::PathBuf;
use std::sync::OnceLock;
use std::{fs, path::Path};
use fontdb::{Database, Source};
use typst::text::{Font, FontBook, FontInfo};
use typst_timing::TimingScope;
/// Holds details about the location of a font and lazily the font itself.
#[derive(Debug)]
pub struct FontSlot {
/// The path at which the font can be found on the system.
path: Option<PathBuf>,
/// The index of the font in its collection. Zero if the path does not point
/// to a collection.
index: u32,
/// The lazily loaded font.
font: OnceLock<Option<Font>>,
}
impl FontSlot {
/// Returns the path at which the font can be found on the system, or `None`
/// if the font was embedded.
pub fn path(&self) -> Option<&Path> {
self.path.as_deref()
}
/// Returns the index of the font in its collection. Zero if the path does
/// not point to a collection.
pub fn index(&self) -> u32 {
self.index
}
/// Get the font for this slot. This loads the font into memory on first
/// access.
pub fn get(&self) -> Option<Font> {
self.font
.get_or_init(|| {
let _scope = TimingScope::new("load font", None);
let data = fs::read(
self.path
.as_ref()
.expect("`path` is not `None` if `font` is uninitialized"),
)
.ok()?
.into();
Font::new(data, self.index)
})
.clone()
}
}
/// The result of a font search, created by calling [`FontSearcher::search`].
#[derive(Debug)]
pub struct Fonts {
/// Metadata about all discovered fonts.
pub book: FontBook,
/// Slots that the fonts are loaded into.
pub fonts: Vec<FontSlot>,
}
impl Fonts {
/// Creates a new font searcer with the default settings.
pub fn searcher() -> FontSearcher {
FontSearcher::new()
}
}
/// Searches for fonts.
///
/// Fonts are added in the following order (descending priority):
/// 1. Font directories
/// 2. System fonts (if included & enabled)
/// 3. Embedded fonts (if enabled)
#[derive(Debug)]
pub struct FontSearcher {
db: Database,
include_system_fonts: bool,
#[cfg(feature = "embed-fonts")]
include_embedded_fonts: bool,
book: FontBook,
fonts: Vec<FontSlot>,
}
impl FontSearcher {
/// Create a new, empty system searcher. The searcher is created with the
/// default configuration, it will include embedded fonts and system fonts.
pub fn new() -> Self {
Self {
db: Database::new(),
include_system_fonts: true,
#[cfg(feature = "embed-fonts")]
include_embedded_fonts: true,
book: FontBook::new(),
fonts: vec![],
}
}
/// Whether to search for and load system fonts, defaults to `true`.
pub fn include_system_fonts(&mut self, value: bool) -> &mut Self {
self.include_system_fonts = value;
self
}
/// Whether to load embedded fonts, defaults to `true`.
#[cfg(feature = "embed-fonts")]
pub fn include_embedded_fonts(&mut self, value: bool) -> &mut Self {
self.include_embedded_fonts = value;
self
}
/// Start searching for and loading fonts. To additionally load fonts
/// from specific directories, use [`search_with`][Self::search_with].
///
/// # Examples
/// ```no_run
/// # use typst_kit::fonts::FontSearcher;
/// let fonts = FontSearcher::new()
/// .include_system_fonts(true)
/// .search();
/// ```
pub fn search(&mut self) -> Fonts {
self.search_with::<_, &str>([])
}
/// Start searching for and loading fonts, with additional directories.
///
/// # Examples
/// ```no_run
/// # use typst_kit::fonts::FontSearcher;
/// let fonts = FontSearcher::new()
/// .include_system_fonts(true)
/// .search_with(["./assets/fonts/"]);
/// ```
pub fn search_with<I, P>(&mut self, font_dirs: I) -> Fonts
where
I: IntoIterator<Item = P>,
P: AsRef<Path>,
{
// Font paths have highest priority.
for path in font_dirs {
self.db.load_fonts_dir(path);
}
if self.include_system_fonts {
// System fonts have second priority.
self.db.load_system_fonts();
}
for face in self.db.faces() {
let path = match &face.source {
Source::File(path) | Source::SharedFile(path, _) => path,
// We never add binary sources to the database, so there
// shouldn't be any.
Source::Binary(_) => continue,
};
let info = self
.db
.with_face_data(face.id, FontInfo::new)
.expect("database must contain this font");
if let Some(info) = info {
self.book.push(info);
self.fonts.push(FontSlot {
path: Some(path.clone()),
index: face.index,
font: OnceLock::new(),
});
}
}
// Embedded fonts have lowest priority.
#[cfg(feature = "embed-fonts")]
if self.include_embedded_fonts {
self.add_embedded();
}
Fonts {
book: std::mem::take(&mut self.book),
fonts: std::mem::take(&mut self.fonts),
}
}
/// Add fonts that are embedded in the binary.
#[cfg(feature = "embed-fonts")]
fn add_embedded(&mut self) {
for data in typst_assets::fonts() {
let buffer = typst::foundations::Bytes::from_static(data);
for (i, font) in Font::iter(buffer).enumerate() {
self.book.push(font.info().clone());
self.fonts.push(FontSlot {
path: None,
index: i as u32,
font: OnceLock::from(Some(font)),
});
}
}
}
}
impl Default for FontSearcher {
fn default() -> Self {
Self::new()
}
}