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
#![deny(warnings)]
use std::collections::HashSet;
use std::path::Path;
use futures::future::try_join_all;
use tokio::fs::File;
use tokio::io::AsyncReadExt;
mod proto;
use proto::glyphs;
type GlyphResult = Result<glyphs::glyphs, protobuf::ProtobufError>;
pub async fn get_font_stack(
font_path: &Path,
font_names: Vec<String>,
start: u32,
end: u32,
) -> GlyphResult {
let mut load_futures: Vec<_> = vec![];
for font in font_names.iter() {
load_futures.push(load_glyphs(font_path, font, start, end));
}
match try_join_all(load_futures).await {
Ok(data) => {
if let Some(result) = combine_glyphs(data) {
Ok(result)
} else {
let mut result = glyphs::glyphs::new();
let mut stack = glyphs::fontstack::new();
stack.set_name(font_names.join(", "));
stack.set_range(format!("{}-{}", start, end));
result.mut_stacks().push(stack);
Ok(result)
}
}
Err(e) => Err(e),
}
}
pub async fn load_glyphs(font_path: &Path, font_name: &str, start: u32, end: u32) -> GlyphResult {
let full_path = font_path
.join(font_name)
.join(format!("{}-{}.pbf", start, end));
let mut file = File::open(full_path).await?;
let mut buf = Vec::new();
file.read_to_end(&mut buf).await?;
protobuf::parse_from_bytes(&buf)
}
pub fn combine_glyphs(data: Vec<glyphs::glyphs>) -> Option<glyphs::glyphs> {
let mut result = glyphs::glyphs::new();
let mut combined_stack = glyphs::fontstack::new();
let mut coverage: HashSet<u32> = HashSet::new();
for glyph_stack in data {
for font_stack in glyph_stack.get_stacks() {
if !combined_stack.has_name() {
combined_stack.set_name(String::from(font_stack.get_name()));
} else {
let stack_name = combined_stack.get_name().to_owned();
let this_name = font_stack.get_name();
combined_stack.set_name(format!("{}, {}", stack_name, this_name));
}
for glyph in font_stack.get_glyphs() {
if !coverage.contains(&glyph.get_id()) {
coverage.insert(glyph.get_id());
combined_stack.mut_glyphs().push(glyph.to_owned());
}
}
}
}
let start = coverage.iter().min()?;
let end = coverage.iter().min()?;
combined_stack.set_range(format!("{}-{}", start, end));
result.mut_stacks().push(combined_stack);
Some(result)
}