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
use ab_glyph::{FontRef, InvalidFont, PxScale, PxScaleFont};
use font_kit::source::SystemSource;
use font_kit::{family_name::FamilyName, handle::Handle, properties::Properties};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::RwLock;
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct FontId(u32);
impl FontId {
pub fn get(self) -> usize {
self.0 as usize
}
}
#[derive(Copy, Clone, Debug)]
pub struct Font {
font: &'static FontRef<'static>,
}
impl Font {
#[inline]
pub(crate) fn font_scale(self, dpem: f32) -> f32 {
use ab_glyph::Font;
let upem = self.font.units_per_em().unwrap();
dpem / upem * self.font.height_unscaled()
}
#[inline]
pub(crate) fn scaled(self, scale: f32) -> PxScaleFont<&'static FontRef<'static>> {
use ab_glyph::Font;
self.font.into_scaled(PxScale::from(scale))
}
#[inline]
pub fn line_height(self, dpem: f32) -> f32 {
self.font_scale(dpem)
}
}
struct FontStore<'a> {
ab_glyph: FontRef<'a>,
#[cfg(feature = "harfbuzz_rs")]
harfbuzz: harfbuzz_rs::Shared<harfbuzz_rs::Face<'a>>,
}
impl<'a> FontStore<'a> {
fn new(data: &'a [u8], index: u32) -> Result<Self, InvalidFont> {
Ok(FontStore {
ab_glyph: FontRef::try_from_slice_and_index(data, index)?,
#[cfg(feature = "harfbuzz_rs")]
harfbuzz: harfbuzz_rs::Face::from_bytes(data, index).into(),
})
}
}
pub struct FontLibrary {
data: RwLock<HashMap<PathBuf, Box<[u8]>>>,
fonts: RwLock<Vec<Box<FontStore<'static>>>>,
}
impl FontLibrary {
pub fn get(&self, id: FontId) -> Font {
let fonts = self.fonts.read().unwrap();
assert!(id.get() < fonts.len(), "FontLibrary: invalid {:?}!", id);
let font: &FontRef<'static> = &fonts[id.get()].ab_glyph;
let font = unsafe { extend_lifetime(font) };
Font { font }
}
#[cfg(feature = "harfbuzz_rs")]
pub fn get_harfbuzz(&self, id: FontId) -> harfbuzz_rs::Owned<harfbuzz_rs::Font<'static>> {
let fonts = self.fonts.read().unwrap();
assert!(id.get() < fonts.len(), "FontLibrary: invalid {:?}!", id);
harfbuzz_rs::Font::new(fonts[id.get()].harfbuzz.clone())
}
pub fn ab_glyph_fonts_vec(&self) -> Vec<&'static FontRef<'static>> {
let fonts = self.fonts.read().unwrap();
fonts
.iter()
.map(|font| unsafe { extend_lifetime(&font.ab_glyph) })
.collect()
}
pub fn load_default(&self) -> Result<FontId, Box<dyn std::error::Error>> {
let fonts = self.fonts.read().unwrap();
if fonts.len() > 0 {
return Ok(FontId(0));
}
drop(fonts);
let families = [FamilyName::SansSerif];
let properties = Properties::new();
let handle = SOURCE.with(|source| source.select_best_match(&families, &properties))?;
let (path, index) = match handle {
Handle::Path { path, font_index } => (path, font_index),
Handle::Memory { .. } => panic!("Unexpected: font in memory"),
};
let mut data = self.data.write().unwrap();
let slice = if let Some(entry) = data.get(&path) {
let slice: &[u8] = &entry[..];
unsafe { extend_lifetime(slice) }
} else {
let v = std::fs::read(&path)?.into_boxed_slice();
let slice = &data.entry(path).or_insert(v)[..];
unsafe { extend_lifetime(slice) }
};
drop(data);
let store = FontStore::new(slice, index)?;
let mut fonts = self.fonts.write().unwrap();
let id = FontId(fonts.len() as u32);
fonts.push(Box::new(store));
Ok(id)
}
}
unsafe fn extend_lifetime<'b, T: ?Sized>(r: &'b T) -> &'static T {
std::mem::transmute::<&'b T, &'static T>(r)
}
impl FontLibrary {
fn new() -> Self {
FontLibrary {
data: Default::default(),
fonts: Default::default(),
}
}
}
lazy_static::lazy_static! {
static ref LIBRARY: FontLibrary = FontLibrary::new();
}
thread_local! {
static SOURCE: SystemSource = SystemSource::new();
}
pub fn fonts() -> &'static FontLibrary {
&*LIBRARY
}