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
#![allow(non_snake_case)]
#![cfg_attr(not(feature = "std"), no_std)]
extern crate xmlparser;
extern crate mmapio;
extern crate allsorts;
extern crate core;
extern crate alloc;
#[cfg(feature = "std")]
use std::thread;
#[cfg(feature = "std")]
use std::path::PathBuf;
use alloc::string::String;
use alloc::collections::btree_map::BTreeMap;
#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
#[repr(C)]
pub enum PatternMatch {
True,
False,
DontCare,
}
impl PatternMatch {
fn into_option(&self) -> Option<bool> {
match self {
PatternMatch::True => Some(true),
PatternMatch::False => Some(false),
PatternMatch::DontCare => None,
}
}
}
impl Default for PatternMatch {
fn default() -> Self {
PatternMatch::DontCare
}
}
#[derive(Debug, Default, Clone, PartialOrd, Ord, PartialEq, Eq)]
#[repr(C)]
pub struct FcPattern {
pub name: Option<String>,
pub family: Option<String>,
pub italic: PatternMatch,
pub oblique: PatternMatch,
pub bold: PatternMatch,
pub monospace: PatternMatch,
}
#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
#[repr(C)]
pub struct FcFontPath {
pub path: String,
pub font_index: usize,
}
#[derive(Debug, Default, Clone, PartialOrd, Ord, PartialEq, Eq)]
pub struct FcFontCache {
map: BTreeMap<FcPattern, FcFontPath>
}
impl FcFontCache {
#[cfg(feature = "std")]
pub fn build() -> Self {
#[cfg(target_os = "linux")] {
FcFontCache {
map: FcScanDirectories().unwrap_or_default().into_iter().collect()
}
}
#[cfg(target_os = "windows")] {
FcFontCache {
map: FcScanSingleDirectoryRecursive(PathBuf::from("C:\\Windows\\Fonts\\"))
.unwrap_or_default().into_iter().collect()
}
}
#[cfg(target_os = "macos")] {
FcFontCache {
map: FcScanSingleDirectoryRecursive(PathBuf::from("~/Library/Fonts"))
.unwrap_or_default().into_iter().collect()
}
}
}
pub fn list(&self) -> &BTreeMap<FcPattern, FcFontPath> {
&self.map
}
pub fn query(&self, pattern: &FcPattern) -> Option<&FcFontPath> {
let name_needs_to_match = pattern.name.is_some();
let family_needs_to_match = pattern.family.is_some();
let italic_needs_to_match = pattern.italic.into_option();
let oblique_needs_to_match = pattern.oblique.into_option();
let bold_needs_to_match = pattern.bold.into_option();
let monospace_needs_to_match = pattern.monospace.into_option();
let result1 = self.map
.iter()
.find(|(k, _)| {
let name_matches = k.name == pattern.name;
let family_matches = k.family == pattern.family;
let italic_matches = k.italic == pattern.italic;
let oblique_matches = k.oblique == pattern.oblique;
let bold_matches = k.bold == pattern.bold;
let monospace_matches = k.monospace == pattern.monospace;
if name_needs_to_match && !name_matches {
return false;
}
if family_needs_to_match && !family_matches {
return false;
}
if let Some(italic_m) = italic_needs_to_match {
if italic_matches != italic_m {
return false;
}
}
if let Some(oblique_m) = oblique_needs_to_match {
if oblique_matches != oblique_m {
return false;
}
}
if let Some(bold_m) = bold_needs_to_match {
if bold_matches != bold_m {
return false;
}
}
if let Some(monospace_m) = monospace_needs_to_match {
if monospace_matches != monospace_m {
return false;
}
}
true
});
if let Some((_, r1)) = result1.as_ref() {
return Some(r1);
}
None
}
}
#[cfg(feature = "std")]
fn FcScanDirectories() -> Option<Vec<(FcPattern, FcFontPath)>> {
use std::path::Path;
use xmlparser::Tokenizer;
use xmlparser::Token::*;
use std::fs;
let fontconfig_path = Path::new("/etc/fonts/fonts.conf");
if !fontconfig_path.exists() {
return None;
}
let xml_utf8 = fs::read_to_string(fontconfig_path).ok()?;
let mut font_paths_count = 0;
let mut font_paths = [(None, "");32];
let mut current_prefix: Option<&str> = None;
let mut current_dir: Option<&str> = None;
let mut is_in_dir = false;
for token in Tokenizer::from(xml_utf8.as_str()) {
let token = token.ok()?;
match token {
ElementStart { local, .. } => {
if local.as_str() != "dir" {
continue;
}
if is_in_dir { return None; }
is_in_dir = true;
current_dir = None;
},
Text { text, .. } => {
let text = text.as_str().trim();
if text.is_empty() {
continue;
}
if is_in_dir {
current_dir = Some(text);
}
},
Attribute { local, value, .. } => {
if !is_in_dir {
continue;
}
if local.as_str() == "prefix" {
current_prefix = Some(value.as_str());
}
},
ElementEnd { end, .. } => {
let end_tag = match end {
xmlparser::ElementEnd::Close(_, a) => a,
_ => continue,
};
if end_tag.as_str() != "dir" {
continue;
}
if !is_in_dir {
continue;
}
if let Some(d) = current_dir.as_ref() {
if font_paths_count >= font_paths.len() {
return None;
}
font_paths[font_paths_count] = (current_prefix, d);
font_paths_count += 1;
is_in_dir = false;
current_dir = None;
current_prefix = None;
}
},
_ => { },
}
}
let font_paths = &font_paths[0..font_paths_count];
if font_paths.is_empty() {
return None;
}
FcScanDirectoriesInner(font_paths)
}
#[cfg(feature = "std")]
fn FcScanDirectoriesInner(paths: &[(Option<&str>, &str)]) -> Option<Vec<(FcPattern, FcFontPath)>> {
let mut threads = (0..32).map(|_| None).collect::<Vec<_>>();
let mut result = Vec::new();
for (p_id, (prefix, p)) in paths.iter().enumerate() {
let mut path = match prefix {
None => PathBuf::new(),
Some(s) => PathBuf::from(s),
};
path.push(p);
threads[p_id] = Some(thread::spawn(move || FcScanSingleDirectoryRecursive(path)));
}
for t in threads.iter_mut() {
let t_result = match t.take() {
Some(s) => s,
None => continue,
};
let mut t_result = t_result.join().ok()?;
match &mut t_result {
Some(c) => { result.append(c); },
None => { },
}
}
Some(result)
}
#[cfg(feature = "std")]
fn FcScanSingleDirectoryRecursive(dir: PathBuf)-> Option<Vec<(FcPattern, FcFontPath)>> {
let mut threads = Vec::new();
for entry in std::fs::read_dir(dir).ok()? {
let entry = entry.ok()?;
let path = entry.path();
let pathbuf = path.to_path_buf();
if path.is_dir() {
threads.push(Some(thread::spawn(move || FcScanSingleDirectoryRecursive(pathbuf))));
} else {
threads.push(Some(thread::spawn(move || FcParseFont(pathbuf))));
}
}
let mut results = Vec::new();
for t in threads.iter_mut() {
let mut t_result = t.take().and_then(|q| q.join().ok().and_then(|o| o)).unwrap_or_default();
results.append(&mut t_result);
}
Some(results)
}
#[cfg(feature = "std")]
fn FcParseFont(filepath: PathBuf)-> Option<Vec<(FcPattern, FcFontPath)>> {
use allsorts::{
tag,
binary::read::ReadScope,
font_data::FontData,
tables::{
FontTableProvider, NameTable, HeadTable,
}
};
use std::fs::File;
use mmapio::MmapOptions;
use std::collections::BTreeSet;
use allsorts::get_name::fontcode_get_name;
const FONT_SPECIFIER_NAME_ID: u16 = 4;
const FONT_SPECIFIER_FAMILY_ID: u16 = 1;
let font_index = 0;
let file = File::open(filepath.clone()).ok()?;
let font_bytes = unsafe { MmapOptions::new().map(&file).ok()? };
let scope = ReadScope::new(&font_bytes[..]);
let font_file = scope.read::<FontData<'_>>().ok()?;
let provider = font_file.table_provider(font_index).ok()?;
let head_data = provider.table_data(tag::HEAD).ok()??.into_owned();
let head_table = ReadScope::new(&head_data).read::<HeadTable>().ok()?;
let is_bold = head_table.is_bold();
let is_italic = head_table.is_italic();
let name_data = provider.table_data(tag::NAME).ok()??.into_owned();
let name_table = ReadScope::new(&name_data).read::<NameTable>().ok()?;
let mut f_family = None;
let patterns = name_table.name_records
.iter()
.filter_map(|name_record| {
let name_id = name_record.name_id;
if name_id == FONT_SPECIFIER_FAMILY_ID {
let family = fontcode_get_name(&name_data, FONT_SPECIFIER_FAMILY_ID).ok()??;
f_family = Some(family.to_string_lossy().to_string());
None
} else if name_id == FONT_SPECIFIER_NAME_ID {
let family = f_family.as_ref()?;
let name = fontcode_get_name(&name_data, FONT_SPECIFIER_NAME_ID).ok()??;
let name = name.to_string_lossy().to_string();
if name.is_empty() {
None
} else {
Some((FcPattern {
name: Some(name),
family: Some(family.clone()),
bold: if is_bold { PatternMatch::True } else { PatternMatch::False },
italic: if is_italic { PatternMatch::True } else { PatternMatch::False },
.. Default::default()
}, font_index))
}
} else {
None
}
}).collect::<BTreeSet<_>>();
Some(
patterns
.into_iter()
.map(|(pat, index)| (pat, FcFontPath {
path: filepath.clone().to_string_lossy().to_string(),
font_index: index
}))
.collect()
)
}