-
Notifications
You must be signed in to change notification settings - Fork 31
/
lib.rs
1300 lines (1130 loc) · 44.5 KB
/
lib.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
`fontdb` is a simple, in-memory font database with CSS-like queries.
# Features
- The database can load fonts from files, directories and raw data (`Vec<u8>`).
- The database can match a font using CSS-like queries. See `Database::query`.
- The database can try to load system fonts.
Currently, this is implemented by scanning predefined directories.
The library does not interact with the system API.
- Provides a unique ID for each font face.
# Non-goals
- Advanced font properties querying.<br>
The database provides only storage and matching capabilities.
For font properties querying you can use [ttf-parser].
- A font fallback mechanism.<br>
This library can be used to implement a font fallback mechanism, but it doesn't implement one.
- Application's global database.<br>
The database doesn't use `static`, therefore it's up to the caller where it should be stored.
- Font types support other than TrueType.
# Font vs Face
A font is a collection of font faces. Therefore, a font face is a subset of a font.
A simple font (\*.ttf/\*.otf) usually contains a single font face,
but a font collection (\*.ttc) can contain multiple font faces.
`fontdb` stores and matches font faces, not fonts.
Therefore, after loading a font collection with 5 faces (for example), the database will be populated
with 5 `FaceInfo` objects, all of which will be pointing to the same file or binary data.
# Performance
The database performance is largely limited by the storage itself.
We are using [ttf-parser], so the parsing should not be a bottleneck.
On my machine with Samsung SSD 860 and Gentoo Linux, it takes ~20ms
to load 1906 font faces (most of them are from Google Noto collection)
with a hot disk cache and ~860ms with a cold one.
On Mac Mini M1 it takes just 9ms to load 898 fonts.
# Safety
The library relies on memory-mapped files, which is inherently unsafe.
But since we do not keep the files open it should be perfectly safe.
If you would like to use a persistent memory mapping of the font files,
then you can use the unsafe [`Database::make_shared_face_data`] function.
[ttf-parser]: https://github.com/RazrFalcon/ttf-parser
*/
#![cfg_attr(not(feature = "std"), no_std)]
#![warn(missing_docs)]
#![warn(missing_debug_implementations)]
#![warn(missing_copy_implementations)]
extern crate alloc;
#[cfg(not(feature = "std"))]
use alloc::{
string::{String, ToString},
vec::Vec,
};
pub use ttf_parser::Language;
pub use ttf_parser::Width as Stretch;
use slotmap::SlotMap;
use tinyvec::TinyVec;
/// A unique per database face ID.
///
/// Since `Database` is not global/unique, we cannot guarantee that a specific ID
/// is actually from the same db instance. This is up to the caller.
///
/// ID overflow will cause a panic, but it's highly unlikely that someone would
/// load more than 4 billion font faces.
///
/// Because the internal representation of ID is private, The `Display` trait
/// implementation for this type only promise that unequal IDs will be displayed
/// as different strings, but does not make any guarantees about format or
/// content of the strings.
///
/// [`KeyData`]: https://docs.rs/slotmap/latest/slotmap/struct.KeyData.html
#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd, Debug, Default)]
pub struct ID(InnerId);
slotmap::new_key_type! {
/// Internal ID type.
struct InnerId;
}
impl ID {
/// Creates a dummy ID.
///
/// Should be used in tandem with [`Database::push_face_info`].
#[inline]
pub fn dummy() -> Self {
Self(InnerId::from(slotmap::KeyData::from_ffi(core::u64::MAX)))
}
}
impl core::fmt::Display for ID {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", (self.0).0.as_ffi())
}
}
/// A list of possible font loading errors.
#[derive(Debug)]
enum LoadError {
/// A malformed font.
///
/// Typically means that [ttf-parser](https://github.com/RazrFalcon/ttf-parser)
/// wasn't able to parse it.
MalformedFont,
/// A valid TrueType font without a valid *Family Name*.
UnnamedFont,
/// A file IO related error.
#[cfg(feature = "std")]
IoError(std::io::Error),
}
#[cfg(feature = "std")]
impl From<std::io::Error> for LoadError {
#[inline]
fn from(e: std::io::Error) -> Self {
LoadError::IoError(e)
}
}
impl core::fmt::Display for LoadError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
LoadError::MalformedFont => write!(f, "malformed font"),
LoadError::UnnamedFont => write!(f, "font doesn't have a family name"),
#[cfg(feature = "std")]
LoadError::IoError(ref e) => write!(f, "{}", e),
}
}
}
/// A font database.
#[derive(Clone, Debug)]
pub struct Database {
faces: SlotMap<InnerId, FaceInfo>,
family_serif: String,
family_sans_serif: String,
family_cursive: String,
family_fantasy: String,
family_monospace: String,
}
impl Default for Database {
fn default() -> Self {
Self::new()
}
}
impl Database {
/// Create a new, empty `Database`.
///
/// Generic font families would be set to:
///
/// - `serif` - Times New Roman
/// - `sans-serif` - Arial
/// - `cursive` - Comic Sans MS
/// - `fantasy` - Impact (Papyrus on macOS)
/// - `monospace` - Courier New
#[inline]
pub fn new() -> Self {
Database {
faces: SlotMap::with_key(),
family_serif: "Times New Roman".to_string(),
family_sans_serif: "Arial".to_string(),
family_cursive: "Comic Sans MS".to_string(),
#[cfg(not(target_os = "macos"))]
family_fantasy: "Impact".to_string(),
#[cfg(target_os = "macos")]
family_fantasy: "Papyrus".to_string(),
family_monospace: "Courier New".to_string(),
}
}
/// Loads a font data into the `Database`.
///
/// Will load all font faces in case of a font collection.
pub fn load_font_data(&mut self, data: Vec<u8>) {
self.load_font_source(Source::Binary(alloc::sync::Arc::new(data)));
}
/// Loads a font from the given source into the `Database` and returns
/// the ID of the loaded font.
///
/// Will load all font faces in case of a font collection.
pub fn load_font_source(&mut self, source: Source) -> TinyVec<[ID; 8]> {
let ids = source.with_data(|data| {
let n = ttf_parser::fonts_in_collection(data).unwrap_or(1);
let mut ids = TinyVec::with_capacity(n as usize);
for index in 0..n {
match parse_face_info(source.clone(), data, index) {
Ok(mut info) => {
let id = self.faces.insert_with_key(|k| {
info.id = ID(k);
info
});
ids.push(ID(id));
}
Err(e) => log::warn!(
"Failed to load a font face {} from source cause {}.",
index,
e
),
}
}
ids
});
ids.unwrap_or_default()
}
/// Backend function used by load_font_file to load font files.
#[cfg(feature = "fs")]
fn load_fonts_from_file(&mut self, path: &std::path::Path, data: &[u8]) {
let source = Source::File(path.into());
let n = ttf_parser::fonts_in_collection(data).unwrap_or(1);
for index in 0..n {
match parse_face_info(source.clone(), data, index) {
Ok(info) => self.push_face_info(info),
Err(e) => {
log::warn!(
"Failed to load a font face {} from '{}' cause {}.",
index,
path.display(),
e
)
}
}
}
}
/// Loads a font file into the `Database`.
///
/// Will load all font faces in case of a font collection.
#[cfg(all(feature = "fs", feature = "memmap"))]
pub fn load_font_file<P: AsRef<std::path::Path>>(
&mut self,
path: P,
) -> Result<(), std::io::Error> {
self.load_font_file_impl(path.as_ref())
}
// A non-generic version.
#[cfg(all(feature = "fs", feature = "memmap"))]
fn load_font_file_impl(&mut self, path: &std::path::Path) -> Result<(), std::io::Error> {
let file = std::fs::File::open(path)?;
let data: &[u8] = unsafe { &memmap2::MmapOptions::new().map(&file)? };
self.load_fonts_from_file(path, data);
Ok(())
}
/// Loads a font file into the `Database`.
///
/// Will load all font faces in case of a font collection.
#[cfg(all(feature = "fs", not(feature = "memmap")))]
pub fn load_font_file<P: AsRef<std::path::Path>>(
&mut self,
path: P,
) -> Result<(), std::io::Error> {
self.load_font_file_impl(path.as_ref())
}
// A non-generic version.
#[cfg(all(feature = "fs", not(feature = "memmap")))]
fn load_font_file_impl(&mut self, path: &std::path::Path) -> Result<(), std::io::Error> {
let data = std::fs::read(path)?;
self.load_fonts_from_file(path, &data);
Ok(())
}
/// Loads font files from the selected directory into the `Database`.
///
/// This method will scan directories recursively.
///
/// Will load `ttf`, `otf`, `ttc` and `otc` fonts.
///
/// Unlike other `load_*` methods, this one doesn't return an error.
/// It will simply skip malformed fonts and will print a warning into the log for each of them.
#[cfg(feature = "fs")]
pub fn load_fonts_dir<P: AsRef<std::path::Path>>(&mut self, dir: P) {
self.load_fonts_dir_impl(dir.as_ref())
}
// A non-generic version.
#[rustfmt::skip] // keep extensions match as is
#[cfg(feature = "fs")]
fn load_fonts_dir_impl(&mut self, dir: &std::path::Path) {
let fonts_dir = match std::fs::read_dir(dir) {
Ok(dir) => dir,
Err(_) => return,
};
for entry in fonts_dir.flatten() {
let path = entry.path();
let file_type = match entry.file_type() {
Ok(t) => t,
Err(_) => return,
};
if file_type.is_file() {
match path.extension().and_then(|e| e.to_str()) {
Some("ttf") | Some("ttc") | Some("TTF") | Some("TTC") |
Some("otf") | Some("otc") | Some("OTF") | Some("OTC") => {
if let Err(e) = self.load_font_file(&path) {
log::warn!("Failed to load '{}' cause {}.", path.display(), e);
}
}
_ => {}
}
} else if file_type.is_dir() {
// TODO: ignore symlinks?
self.load_fonts_dir(path);
}
}
}
/// Attempts to load system fonts.
///
/// Supports Windows, Linux and macOS.
///
/// System fonts loading is a surprisingly complicated task,
/// mostly unsolvable without interacting with system libraries.
/// And since `fontdb` tries to be small and portable, this method
/// will simply scan some predefined directories.
/// Which means that fonts that are not in those directories must
/// be added manually.
#[cfg(feature = "fs")]
pub fn load_system_fonts(&mut self) {
#[cfg(target_os = "windows")]
{
if let Some(ref system_root) = std::env::var_os("SYSTEMROOT") {
let system_root_path = std::path::Path::new(system_root);
self.load_fonts_dir(system_root_path.join("Fonts"));
} else {
self.load_fonts_dir("C:\\Windows\\Fonts\\");
}
if let Ok(ref home) = std::env::var("USERPROFILE") {
let home_path = std::path::Path::new(home);
self.load_fonts_dir(home_path.join("AppData\\Local\\Microsoft\\Windows\\Fonts"));
self.load_fonts_dir(home_path.join("AppData\\Roaming\\Microsoft\\Windows\\Fonts"));
}
}
#[cfg(target_os = "macos")]
{
self.load_fonts_dir("/Library/Fonts");
self.load_fonts_dir("/System/Library/Fonts");
// Downloadable fonts, location varies on major macOS releases
if let Ok(dir) = std::fs::read_dir("/System/Library/AssetsV2") {
for entry in dir {
let entry = match entry {
Ok(entry) => entry,
Err(_) => continue,
};
if entry
.file_name()
.to_string_lossy()
.starts_with("com_apple_MobileAsset_Font")
{
self.load_fonts_dir(entry.path());
}
}
}
self.load_fonts_dir("/Network/Library/Fonts");
if let Ok(ref home) = std::env::var("HOME") {
let home_path = std::path::Path::new(home);
self.load_fonts_dir(home_path.join("Library/Fonts"));
}
}
// Redox OS.
#[cfg(target_os = "redox")]
{
self.load_fonts_dir("/ui/fonts");
}
// Linux.
#[cfg(all(unix, not(any(target_os = "macos", target_os = "android"))))]
{
#[cfg(feature = "fontconfig")]
{
self.load_fontconfig();
}
#[cfg(not(feature = "fontconfig"))]
{
self.load_fonts_dir("/usr/share/fonts/");
self.load_fonts_dir("/usr/local/share/fonts/");
if let Ok(ref home) = std::env::var("HOME") {
let home_path = std::path::Path::new(home);
self.load_fonts_dir(home_path.join(".fonts"));
self.load_fonts_dir(home_path.join(".local/share/fonts"));
}
}
}
}
// Linux.
#[cfg(all(
unix,
feature = "fontconfig",
not(any(target_os = "macos", target_os = "android"))
))]
fn load_fontconfig(&mut self) {
use std::path::Path;
let mut fontconfig = fontconfig_parser::FontConfig::default();
let home = std::env::var("HOME");
if let Ok(ref config_file) = std::env::var("FONTCONFIG_FILE") {
let _ = fontconfig.merge_config(Path::new(config_file));
} else {
let xdg_config_home = if let Ok(val) = std::env::var("XDG_CONFIG_HOME") {
Some(val.into())
} else if let Ok(ref home) = home {
// according to https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
// $XDG_CONFIG_HOME should default to $HOME/.config if not set
Some(Path::new(home).join(".config"))
} else {
None
};
let read_global = match xdg_config_home {
Some(p) => fontconfig
.merge_config(&p.join("fontconfig/fonts.conf"))
.is_err(),
None => true,
};
if read_global {
let _ = fontconfig.merge_config(Path::new("/etc/fonts/local.conf"));
}
let _ = fontconfig.merge_config(Path::new("/etc/fonts/fonts.conf"));
}
for fontconfig_parser::Alias {
alias,
default,
prefer,
accept,
} in fontconfig.aliases
{
let name = prefer
.get(0)
.or_else(|| accept.get(0))
.or_else(|| default.get(0));
if let Some(name) = name {
match alias.to_lowercase().as_str() {
"serif" => self.set_serif_family(name),
"sans-serif" => self.set_sans_serif_family(name),
"sans serif" => self.set_sans_serif_family(name),
"monospace" => self.set_monospace_family(name),
"cursive" => self.set_cursive_family(name),
"fantasy" => self.set_fantasy_family(name),
_ => {}
}
}
}
for dir in fontconfig.dirs {
let path = if dir.path.starts_with("~") {
if let Ok(ref home) = home {
Path::new(home).join(dir.path.strip_prefix("~").unwrap())
} else {
continue;
}
} else {
dir.path
};
self.load_fonts_dir(path);
}
}
/// Pushes a user-provided `FaceInfo` to the database.
///
/// In some cases, a caller might want to ignore the font's metadata and provide their own.
/// This method doesn't parse the `source` font.
///
/// The `id` field should be set to [`ID::dummy()`] and will be then overwritten by this method.
pub fn push_face_info(&mut self, mut info: FaceInfo) {
self.faces.insert_with_key(|k| {
info.id = ID(k);
info
});
}
/// Removes a font face by `id` from the database.
///
/// Returns `false` while attempting to remove a non-existing font face.
///
/// Useful when you want to ignore some specific font face(s)
/// after loading a large directory with fonts.
/// Or a specific face from a font.
pub fn remove_face(&mut self, id: ID) {
self.faces.remove(id.0);
}
/// Returns `true` if the `Database` contains no font faces.
#[inline]
pub fn is_empty(&self) -> bool {
self.faces.is_empty()
}
/// Returns the number of font faces in the `Database`.
///
/// Note that `Database` stores font faces, not fonts.
/// For example, if a caller will try to load a font collection (`*.ttc`) that contains 5 faces,
/// then the `Database` will load 5 font faces and this method will return 5, not 1.
#[inline]
pub fn len(&self) -> usize {
self.faces.len()
}
/// Sets the family that will be used by `Family::Serif`.
pub fn set_serif_family<S: Into<String>>(&mut self, family: S) {
self.family_serif = family.into();
}
/// Sets the family that will be used by `Family::SansSerif`.
pub fn set_sans_serif_family<S: Into<String>>(&mut self, family: S) {
self.family_sans_serif = family.into();
}
/// Sets the family that will be used by `Family::Cursive`.
pub fn set_cursive_family<S: Into<String>>(&mut self, family: S) {
self.family_cursive = family.into();
}
/// Sets the family that will be used by `Family::Fantasy`.
pub fn set_fantasy_family<S: Into<String>>(&mut self, family: S) {
self.family_fantasy = family.into();
}
/// Sets the family that will be used by `Family::Monospace`.
pub fn set_monospace_family<S: Into<String>>(&mut self, family: S) {
self.family_monospace = family.into();
}
/// Returns the generic family name or the `Family::Name` itself.
///
/// Generic family names should be set via `Database::set_*_family` methods.
pub fn family_name<'a>(&'a self, family: &'a Family) -> &'a str {
match family {
Family::Name(name) => name,
Family::Serif => self.family_serif.as_str(),
Family::SansSerif => self.family_sans_serif.as_str(),
Family::Cursive => self.family_cursive.as_str(),
Family::Fantasy => self.family_fantasy.as_str(),
Family::Monospace => self.family_monospace.as_str(),
}
}
/// Performs a CSS-like query and returns the best matched font face.
pub fn query(&self, query: &Query) -> Option<ID> {
for family in query.families {
let name = self.family_name(family);
let candidates: Vec<_> = self
.faces
.iter()
.filter(|(_, face)| face.families.iter().any(|family| family.0 == name))
.map(|(_, info)| info)
.collect();
if !candidates.is_empty() {
if let Some(index) = find_best_match(&candidates, query) {
return Some(candidates[index].id);
}
}
}
None
}
/// Returns an iterator over the internal storage.
///
/// This can be used for manual font matching.
#[inline]
pub fn faces(&self) -> impl Iterator<Item = &FaceInfo> + '_ {
self.faces.iter().map(|(_, info)| info)
}
/// Selects a `FaceInfo` by `id`.
///
/// Returns `None` if a face with such ID was already removed,
/// or this ID belong to the other `Database`.
pub fn face(&self, id: ID) -> Option<&FaceInfo> {
self.faces.get(id.0)
}
/// Returns font face storage and the face index by `ID`.
pub fn face_source(&self, id: ID) -> Option<(Source, u32)> {
self.face(id).map(|info| (info.source.clone(), info.index))
}
/// Executes a closure with a font's data.
///
/// We can't return a reference to a font binary data because of lifetimes.
/// So instead, you can use this method to process font's data.
///
/// The closure accepts raw font data and font face index.
///
/// In case of `Source::File`, the font file will be memory mapped.
///
/// Returns `None` when font file loading failed.
///
/// # Example
///
/// ```ignore
/// let is_variable = db.with_face_data(id, |font_data, face_index| {
/// let font = ttf_parser::Face::from_slice(font_data, face_index).unwrap();
/// font.is_variable()
/// })?;
/// ```
pub fn with_face_data<P, T>(&self, id: ID, p: P) -> Option<T>
where
P: FnOnce(&[u8], u32) -> T,
{
let (src, face_index) = self.face_source(id)?;
src.with_data(|data| p(data, face_index))
}
/// Makes the font data that backs the specified face id shared so that the application can
/// hold a reference to it.
///
/// # Safety
///
/// If the face originates from a file from disk, then the file is mapped from disk. This is unsafe as
/// another process may make changes to the file on disk, which may become visible in this process'
/// mapping and possibly cause crashes.
///
/// If the underlying font provides multiple faces, then all faces are updated to participate in
/// the data sharing. If the face was previously marked for data sharing, then this function will
/// return a clone of the existing reference.
#[cfg(all(feature = "fs", feature = "memmap"))]
pub unsafe fn make_shared_face_data(
&mut self,
id: ID,
) -> Option<(std::sync::Arc<dyn AsRef<[u8]> + Send + Sync>, u32)> {
let face_info = self.faces.get(id.0)?;
let face_index = face_info.index;
let old_source = face_info.source.clone();
let (path, shared_data) = match &old_source {
Source::Binary(data) => {
return Some((data.clone(), face_index));
}
Source::File(ref path) => {
let file = std::fs::File::open(path).ok()?;
let shared_data = std::sync::Arc::new(memmap2::MmapOptions::new().map(&file).ok()?)
as std::sync::Arc<dyn AsRef<[u8]> + Send + Sync>;
(path.clone(), shared_data)
}
Source::SharedFile(_, data) => {
return Some((data.clone(), face_index));
}
};
let shared_source = Source::SharedFile(path.clone(), shared_data.clone());
self.faces.iter_mut().for_each(|(_, face)| {
if matches!(&face.source, Source::File(old_path) if old_path == &path) {
face.source = shared_source.clone();
}
});
Some((shared_data, face_index))
}
/// Transfers ownership of shared font data back to the font database. This is the reverse operation
/// of [`Self::make_shared_face_data`]. If the font data belonging to the specified face is mapped
/// from a file on disk, then that mapping is closed and the data becomes private to the process again.
#[cfg(all(feature = "fs", feature = "memmap"))]
pub fn make_face_data_unshared(&mut self, id: ID) {
let face_info = match self.faces.get(id.0) {
Some(face_info) => face_info,
None => return,
};
let old_source = face_info.source.clone();
let shared_path = match old_source {
#[cfg(all(feature = "fs", feature = "memmap"))]
Source::SharedFile(path, _) => path,
_ => return,
};
let new_source = Source::File(shared_path.clone());
self.faces.iter_mut().for_each(|(_, face)| {
if matches!(&face.source, Source::SharedFile(path, ..) if path == &shared_path) {
face.source = new_source.clone();
}
});
}
}
/// A single font face info.
///
/// A font can have multiple faces.
///
/// A single item of the `Database`.
#[derive(Clone, Debug)]
pub struct FaceInfo {
/// An unique ID.
pub id: ID,
/// A font source.
///
/// Note that multiple `FaceInfo` objects can reference the same data in case of
/// font collections, which means that they'll use the same Source.
pub source: Source,
/// A face index in the `source`.
pub index: u32,
/// A list of family names.
///
/// Contains pairs of Name + Language. Where the first family is always English US,
/// unless it's missing from the font.
///
/// Corresponds to a *Typographic Family* (ID 16) or a *Font Family* (ID 1) [name ID]
/// in a TrueType font.
///
/// This is not an *Extended Typographic Family* or a *Full Name*.
/// Meaning it will contain _Arial_ and not _Arial Bold_.
///
/// [name ID]: https://docs.microsoft.com/en-us/typography/opentype/spec/name#name-ids
pub families: Vec<(String, Language)>,
/// A PostScript name.
///
/// Corresponds to a *PostScript name* (6) [name ID] in a TrueType font.
///
/// [name ID]: https://docs.microsoft.com/en-us/typography/opentype/spec/name#name-ids
pub post_script_name: String,
/// A font face style.
pub style: Style,
/// A font face weight.
pub weight: Weight,
/// A font face stretch.
pub stretch: Stretch,
/// Indicates that the font face is monospaced.
pub monospaced: bool,
}
/// A font source.
///
/// Either a raw binary data or a file path.
///
/// Stores the whole font and not just a single face.
#[derive(Clone)]
pub enum Source {
/// A font's raw data, typically backed by a Vec<u8>.
Binary(alloc::sync::Arc<dyn AsRef<[u8]> + Sync + Send>),
/// A font's path.
#[cfg(feature = "fs")]
File(std::path::PathBuf),
/// A font's raw data originating from a shared file mapping.
#[cfg(all(feature = "fs", feature = "memmap"))]
SharedFile(
std::path::PathBuf,
std::sync::Arc<dyn AsRef<[u8]> + Sync + Send>,
),
}
impl core::fmt::Debug for Source {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Binary(arg0) => f
.debug_tuple("SharedBinary")
.field(&arg0.as_ref().as_ref())
.finish(),
#[cfg(feature = "fs")]
Self::File(arg0) => f.debug_tuple("File").field(arg0).finish(),
#[cfg(all(feature = "fs", feature = "memmap"))]
Self::SharedFile(arg0, arg1) => f
.debug_tuple("SharedFile")
.field(arg0)
.field(&arg1.as_ref().as_ref())
.finish(),
}
}
}
impl Source {
fn with_data<P, T>(&self, p: P) -> Option<T>
where
P: FnOnce(&[u8]) -> T,
{
match &self {
#[cfg(all(feature = "fs", not(feature = "memmap")))]
Source::File(ref path) => {
let data = std::fs::read(path).ok()?;
Some(p(&data))
}
#[cfg(all(feature = "fs", feature = "memmap"))]
Source::File(ref path) => {
let file = std::fs::File::open(path).ok()?;
let data = unsafe { &memmap2::MmapOptions::new().map(&file).ok()? };
Some(p(data))
}
Source::Binary(ref data) => Some(p(data.as_ref().as_ref())),
#[cfg(all(feature = "fs", feature = "memmap"))]
Source::SharedFile(_, ref data) => Some(p(data.as_ref().as_ref())),
}
}
}
/// A database query.
///
/// Mainly used by `Database::query()`.
#[derive(Clone, Copy, Default, Debug, Eq, PartialEq, Hash)]
pub struct Query<'a> {
/// A prioritized list of font family names or generic family names.
///
/// [font-family](https://www.w3.org/TR/2018/REC-css-fonts-3-20180920/#propdef-font-family) in CSS.
pub families: &'a [Family<'a>],
/// Specifies the weight of glyphs in the font, their degree of blackness or stroke thickness.
///
/// [font-weight](https://www.w3.org/TR/2018/REC-css-fonts-3-20180920/#font-weight-prop) in CSS.
pub weight: Weight,
/// Selects a normal, condensed, or expanded face from a font family.
///
/// [font-stretch](https://www.w3.org/TR/2018/REC-css-fonts-3-20180920/#font-stretch-prop) in CSS.
pub stretch: Stretch,
/// Allows italic or oblique faces to be selected.
///
/// [font-style](https://www.w3.org/TR/2018/REC-css-fonts-3-20180920/#font-style-prop) in CSS.
pub style: Style,
}
// Enum value descriptions are from the CSS spec.
/// A [font family](https://www.w3.org/TR/2018/REC-css-fonts-3-20180920/#propdef-font-family).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Family<'a> {
/// The name of a font family of choice.
///
/// This must be a *Typographic Family* (ID 16) or a *Family Name* (ID 1) in terms of TrueType.
/// Meaning you have to pass a family without any additional suffixes like _Bold_, _Italic_,
/// _Regular_, etc.
///
/// Localized names are allowed.
Name(&'a str),
/// Serif fonts represent the formal text style for a script.
Serif,
/// Glyphs in sans-serif fonts, as the term is used in CSS, are generally low contrast
/// and have stroke endings that are plain — without any flaring, cross stroke,
/// or other ornamentation.
SansSerif,
/// Glyphs in cursive fonts generally use a more informal script style,
/// and the result looks more like handwritten pen or brush writing than printed letterwork.
Cursive,
/// Fantasy fonts are primarily decorative or expressive fonts that
/// contain decorative or expressive representations of characters.
Fantasy,
/// The sole criterion of a monospace font is that all glyphs have the same fixed width.
Monospace,
}
/// Specifies the weight of glyphs in the font, their degree of blackness or stroke thickness.
#[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Debug, Hash)]
pub struct Weight(pub u16);
impl Default for Weight {
#[inline]
fn default() -> Weight {
Weight::NORMAL
}
}
impl Weight {
/// Thin weight (100), the thinnest value.
pub const THIN: Weight = Weight(100);
/// Extra light weight (200).
pub const EXTRA_LIGHT: Weight = Weight(200);
/// Light weight (300).
pub const LIGHT: Weight = Weight(300);
/// Normal (400).
pub const NORMAL: Weight = Weight(400);
/// Medium weight (500, higher than normal).
pub const MEDIUM: Weight = Weight(500);
/// Semibold weight (600).
pub const SEMIBOLD: Weight = Weight(600);
/// Bold weight (700).
pub const BOLD: Weight = Weight(700);
/// Extra-bold weight (800).
pub const EXTRA_BOLD: Weight = Weight(800);
/// Black weight (900), the thickest value.
pub const BLACK: Weight = Weight(900);
}
/// Allows italic or oblique faces to be selected.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum Style {
/// A face that is neither italic not obliqued.
Normal,
/// A form that is generally cursive in nature.
Italic,
/// A typically-sloped version of the regular face.
Oblique,
}
impl Default for Style {
#[inline]
fn default() -> Style {
Style::Normal
}
}
fn parse_face_info(source: Source, data: &[u8], index: u32) -> Result<FaceInfo, LoadError> {
let raw_face = ttf_parser::RawFace::parse(data, index).map_err(|_| LoadError::MalformedFont)?;
let (families, post_script_name) = parse_names(&raw_face).ok_or(LoadError::UnnamedFont)?;
let (mut style, weight, stretch) = parse_os2(&raw_face);
let (monospaced, italic) = parse_post(&raw_face);
if style == Style::Normal && italic {
style = Style::Italic;
}
Ok(FaceInfo {
id: ID::dummy(),
source,
index,
families,
post_script_name,
style,
weight,
stretch,
monospaced,
})
}
fn parse_names(raw_face: &ttf_parser::RawFace) -> Option<(Vec<(String, Language)>, String)> {
const NAME_TAG: ttf_parser::Tag = ttf_parser::Tag::from_bytes(b"name");
let name_data = raw_face.table(NAME_TAG)?;
let name_table = ttf_parser::name::Table::parse(name_data)?;
let mut families = collect_families(ttf_parser::name_id::TYPOGRAPHIC_FAMILY, &name_table.names);
// We have to fallback to Family Name when no Typographic Family Name was set.
if families.is_empty() {
families = collect_families(ttf_parser::name_id::FAMILY, &name_table.names);
}
// Make English US the first one.
if families.len() > 1 {
if let Some(index) = families
.iter()
.position(|f| f.1 == Language::English_UnitedStates)
{
if index != 0 {
families.swap(0, index);
}
}
}
if families.is_empty() {