tytanic_core/world_builder/
font.rs

1use typst::text::Font;
2use typst::text::FontBook;
3use typst::utils::LazyHash;
4use typst_kit::fonts::FontSlot;
5use typst_kit::fonts::Fonts;
6
7use super::ProvideFont;
8
9/// Provides access to fonts from memory.
10#[derive(Debug)]
11pub struct VirtualFontProvider {
12    book: LazyHash<FontBook>,
13    fonts: Vec<Font>,
14}
15
16impl VirtualFontProvider {
17    /// Creates a new font provider with the given fonts.
18    pub fn new(book: FontBook, fonts: Vec<Font>) -> Self {
19        Self {
20            book: LazyHash::new(book),
21            fonts,
22        }
23    }
24}
25
26impl VirtualFontProvider {
27    /// The font book storing the font metadata.
28    pub fn book(&self) -> &LazyHash<FontBook> {
29        &self.book
30    }
31
32    /// The slots used to store the fonts.
33    pub fn fonts(&self) -> &[Font] {
34        &self.fonts
35    }
36}
37
38impl VirtualFontProvider {
39    /// Access the font with the given index.
40    pub fn font(&self, index: usize) -> Option<&Font> {
41        self.fonts.get(index)
42    }
43}
44
45impl ProvideFont for VirtualFontProvider {
46    fn provide_font_book(&self) -> &LazyHash<FontBook> {
47        self.book()
48    }
49
50    fn provide_font(&self, index: usize) -> Option<Font> {
51        self.font(index).cloned()
52    }
53}
54
55/// Provides access to fonts from the filesystem.
56#[derive(Debug)]
57pub struct FilesystemFontProvider {
58    book: LazyHash<FontBook>,
59    fonts: Vec<FontSlot>,
60}
61
62impl FilesystemFontProvider {
63    /// Creates a new font provider with the given fonts.
64    pub fn new(book: FontBook, fonts: Vec<FontSlot>) -> Self {
65        Self {
66            book: LazyHash::new(book),
67            fonts,
68        }
69    }
70
71    /// Creates a new default font provider with the given font searcher result.
72    pub fn from_searcher(fonts: Fonts) -> Self {
73        Self::new(fonts.book, fonts.fonts)
74    }
75}
76
77impl FilesystemFontProvider {
78    /// The font book storing the font metadata.
79    pub fn book(&self) -> &LazyHash<FontBook> {
80        &self.book
81    }
82
83    /// The slots used to store the fonts.
84    pub fn fonts(&self) -> &[FontSlot] {
85        &self.fonts
86    }
87}
88
89impl FilesystemFontProvider {
90    /// Access the canonical slot for the font with the given index.
91    pub fn font(&self, index: usize) -> Option<&FontSlot> {
92        self.fonts.get(index)
93    }
94}
95
96impl ProvideFont for FilesystemFontProvider {
97    fn provide_font_book(&self) -> &LazyHash<FontBook> {
98        self.book()
99    }
100
101    fn provide_font(&self, index: usize) -> Option<Font> {
102        self.font(index).and_then(FontSlot::get)
103    }
104}