1use std::any::Any;
15use std::sync::Arc;
16
17#[cfg(not(target_arch = "wasm32"))]
18mod android;
19#[cfg(any(target_os = "macos", target_os = "ios"))]
20mod coretext;
21mod files;
22#[cfg(not(target_arch = "wasm32"))]
23mod scan;
24mod sfnt;
25
26#[cfg(not(target_arch = "wasm32"))]
27pub use android::Android;
28#[cfg(any(target_os = "macos", target_os = "ios"))]
29pub use coretext::CoreText;
30#[cfg(not(target_arch = "wasm32"))]
31pub use scan::Scan;
32pub use sfnt::assemble;
33pub use skrifa::raw::types::Tag;
34
35pub type FontData = Arc<dyn AsRef<[u8]> + Send + Sync>;
37
38#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
40pub enum Slant {
41 #[default]
42 Upright,
43 Italic,
44 Oblique,
45}
46
47#[derive(Clone, Copy, Debug, PartialEq)]
51pub struct Style {
52 pub weight: u16,
54 pub width: f32,
56 pub slant: Slant,
57}
58
59pub const NORMAL_WIDTH: f32 = 100.0;
61
62impl Default for Style {
63 fn default() -> Self {
64 Style {
65 weight: 400,
66 width: NORMAL_WIDTH,
67 slant: Slant::Upright,
68 }
69 }
70}
71
72impl Style {
73 fn distance(self, requested: Style) -> (u32, u8, u16) {
75 let width = ((self.width - requested.width).abs() * 10.0) as u32;
76 let slant = match (requested.slant, self.slant) {
77 (a, b) if a == b => 0,
78 (Slant::Italic, Slant::Oblique) | (Slant::Oblique, Slant::Italic) => 1,
79 _ => 2,
80 };
81 (width, slant, self.weight.abs_diff(requested.weight))
82 }
83}
84
85#[derive(Clone)]
91pub struct Typeface {
92 data: FontData,
93 index: u32,
94 family: String,
95 style: Style,
96}
97
98impl Typeface {
99 pub fn new(data: FontData, index: u32, family: impl Into<String>, style: Style) -> Typeface {
100 Typeface {
101 data,
102 index,
103 family: family.into(),
104 style,
105 }
106 }
107
108 pub fn data(&self) -> &[u8] {
110 (*self.data).as_ref()
111 }
112
113 pub fn shared_data(&self) -> FontData {
115 Arc::clone(&self.data)
116 }
117
118 pub fn index(&self) -> u32 {
120 self.index
121 }
122
123 pub fn family(&self) -> &str {
125 &self.family
126 }
127
128 pub fn style(&self) -> Style {
129 self.style
130 }
131
132 pub fn covers(&self, character: char) -> bool {
134 files::covers(self.data(), self.index, character)
135 }
136
137 pub fn tables(&self) -> Vec<(Tag, &[u8])> {
142 sfnt::served_tables(self.data(), self.index).unwrap_or_default()
143 }
144}
145
146impl std::fmt::Debug for Typeface {
147 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
148 f.debug_struct("Typeface")
149 .field("family", &self.family)
150 .field("index", &self.index)
151 .field("style", &self.style)
152 .finish_non_exhaustive()
153 }
154}
155
156pub trait FontManager: Send + Sync {
164 fn family(&self, family: &str) -> Vec<Typeface>;
167
168 fn match_family_style(&self, family: &str, style: Style) -> Option<Typeface> {
171 nearest(self.family(family), style)
172 }
173
174 fn match_character(
179 &self,
180 family: Option<&str>,
181 style: Style,
182 locales: &[&str],
183 character: char,
184 ) -> Option<Typeface>;
185
186 fn system_font(&self, size: f32, style: Style) -> Option<Typeface>;
190
191 fn families(&self) -> Vec<String>;
193
194 fn face_count(&self) -> usize;
197
198 fn watch(&self, on_change: Box<dyn Fn() + Send + Sync>) -> Option<Watch>;
202}
203
204impl<M: FontManager + ?Sized> FontManager for Box<M> {
207 fn family(&self, family: &str) -> Vec<Typeface> {
208 (**self).family(family)
209 }
210
211 fn match_family_style(&self, family: &str, style: Style) -> Option<Typeface> {
212 (**self).match_family_style(family, style)
213 }
214
215 fn match_character(
216 &self,
217 family: Option<&str>,
218 style: Style,
219 locales: &[&str],
220 character: char,
221 ) -> Option<Typeface> {
222 (**self).match_character(family, style, locales, character)
223 }
224
225 fn system_font(&self, size: f32, style: Style) -> Option<Typeface> {
226 (**self).system_font(size, style)
227 }
228
229 fn families(&self) -> Vec<String> {
230 (**self).families()
231 }
232
233 fn face_count(&self) -> usize {
234 (**self).face_count()
235 }
236
237 fn watch(&self, on_change: Box<dyn Fn() + Send + Sync>) -> Option<Watch> {
238 (**self).watch(on_change)
239 }
240}
241
242impl<M: FontManager + ?Sized> FontManager for Arc<M> {
245 fn family(&self, family: &str) -> Vec<Typeface> {
246 (**self).family(family)
247 }
248
249 fn match_family_style(&self, family: &str, style: Style) -> Option<Typeface> {
250 (**self).match_family_style(family, style)
251 }
252
253 fn match_character(
254 &self,
255 family: Option<&str>,
256 style: Style,
257 locales: &[&str],
258 character: char,
259 ) -> Option<Typeface> {
260 (**self).match_character(family, style, locales, character)
261 }
262
263 fn system_font(&self, size: f32, style: Style) -> Option<Typeface> {
264 (**self).system_font(size, style)
265 }
266
267 fn families(&self) -> Vec<String> {
268 (**self).families()
269 }
270
271 fn face_count(&self) -> usize {
272 (**self).face_count()
273 }
274
275 fn watch(&self, on_change: Box<dyn Fn() + Send + Sync>) -> Option<Watch> {
276 (**self).watch(on_change)
277 }
278}
279
280pub struct Watch {
282 _subscription: Box<dyn Any + Send>,
283}
284
285impl Watch {
286 pub fn new(subscription: impl Any + Send) -> Watch {
287 Watch {
288 _subscription: Box::new(subscription),
289 }
290 }
291}
292
293pub fn nearest(faces: Vec<Typeface>, style: Style) -> Option<Typeface> {
296 faces
297 .into_iter()
298 .min_by_key(|face| face.style().distance(style))
299}
300
301#[cfg(not(target_arch = "wasm32"))]
304pub fn platform() -> Box<dyn FontManager> {
305 #[cfg(any(target_os = "macos", target_os = "ios"))]
306 {
307 Box::new(CoreText::new())
308 }
309 #[cfg(target_os = "android")]
310 {
311 Box::new(Android::new())
312 }
313 #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "android")))]
314 {
315 Box::new(Scan::load())
316 }
317}
318
319#[cfg(test)]
320mod tests {
321 use super::*;
322
323 fn face(family: &str, weight: u16, width: f32, slant: Slant) -> Typeface {
324 Typeface::new(
325 Arc::new(Vec::new()),
326 0,
327 family,
328 Style {
329 weight,
330 width,
331 slant,
332 },
333 )
334 }
335
336 #[test]
337 fn nearest_prefers_width_then_slant_then_weight() {
338 let faces = vec![
339 face("a", 400, 100.0, Slant::Italic),
340 face("b", 700, 100.0, Slant::Upright),
341 face("c", 400, 75.0, Slant::Upright),
342 ];
343 let regular = Style::default();
344 assert_eq!(nearest(faces.clone(), regular).unwrap().family(), "b");
345 let italic = Style {
346 slant: Slant::Italic,
347 ..regular
348 };
349 assert_eq!(nearest(faces.clone(), italic).unwrap().family(), "a");
350 let condensed = Style {
351 width: 75.0,
352 ..regular
353 };
354 assert_eq!(nearest(faces, condensed).unwrap().family(), "c");
355 }
356
357 #[test]
358 fn oblique_stands_in_for_italic_before_upright() {
359 let faces = vec![
360 face("upright", 400, 100.0, Slant::Upright),
361 face("oblique", 400, 100.0, Slant::Oblique),
362 ];
363 let italic = Style {
364 slant: Slant::Italic,
365 ..Style::default()
366 };
367 assert_eq!(nearest(faces, italic).unwrap().family(), "oblique");
368 }
369}