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
use core_foundation::array::CFArray;
use core_foundation::base::{CFType, TCFType};
use core_foundation::dictionary::CFDictionary;
use core_foundation::string::CFString;
use core_text::font_collection::{self, CTFontCollection};
use core_text::font_descriptor::{self, CTFontDescriptor};
use core_text::font_manager;
use std::any::Any;
use std::collections::HashMap;
use std::f32;
use std::fs::File;
use std::path::Path;
use std::sync::Arc;
use crate::error::SelectionError;
use crate::family_handle::FamilyHandle;
use crate::family_name::FamilyName;
use crate::file_type::FileType;
use crate::font::Font;
use crate::handle::Handle;
use crate::loaders::core_text::{self as core_text_loader, FONT_WEIGHT_MAPPING};
use crate::properties::{Properties, Stretch, Weight};
use crate::source::Source;
use crate::utils;
#[allow(missing_debug_implementations)]
#[allow(missing_copy_implementations)]
pub struct CoreTextSource;
impl CoreTextSource {
#[inline]
pub fn new() -> CoreTextSource {
CoreTextSource
}
pub fn all_fonts(&self) -> Result<Vec<Handle>, SelectionError> {
let collection = font_collection::create_for_all_families();
create_handles_from_core_text_collection(collection)
}
pub fn all_families(&self) -> Result<Vec<String>, SelectionError> {
let core_text_family_names = font_manager::copy_available_font_family_names();
let mut families = Vec::with_capacity(core_text_family_names.len() as usize);
for core_text_family_name in core_text_family_names.iter() {
families.push(core_text_family_name.to_string())
}
Ok(families)
}
pub fn select_family_by_name(&self, family_name: &str) -> Result<FamilyHandle, SelectionError> {
let attributes: CFDictionary<CFString, CFType> = CFDictionary::from_CFType_pairs(&[(
CFString::new("NSFontFamilyAttribute"),
CFString::new(family_name).as_CFType(),
)]);
let descriptor = font_descriptor::new_from_attributes(&attributes);
let descriptors = CFArray::from_CFTypes(&[descriptor]);
let collection = font_collection::new_from_descriptors(&descriptors);
let handles = create_handles_from_core_text_collection(collection)?;
Ok(FamilyHandle::from_font_handles(handles.into_iter()))
}
pub fn select_by_postscript_name(
&self,
postscript_name: &str,
) -> Result<Handle, SelectionError> {
let attributes: CFDictionary<CFString, CFType> = CFDictionary::from_CFType_pairs(&[(
CFString::new("NSFontNameAttribute"),
CFString::new(postscript_name).as_CFType(),
)]);
let descriptor = font_descriptor::new_from_attributes(&attributes);
let descriptors = CFArray::from_CFTypes(&[descriptor]);
let collection = font_collection::new_from_descriptors(&descriptors);
match collection.get_descriptors() {
None => Err(SelectionError::NotFound),
Some(descriptors) => Ok(create_handle_from_descriptor(&*descriptors.get(0).unwrap())),
}
}
#[inline]
pub fn select_best_match(
&self,
family_names: &[FamilyName],
properties: &Properties,
) -> Result<Handle, SelectionError> {
<Self as Source>::select_best_match(self, family_names, properties)
}
}
impl Source for CoreTextSource {
fn all_fonts(&self) -> Result<Vec<Handle>, SelectionError> {
self.all_fonts()
}
fn all_families(&self) -> Result<Vec<String>, SelectionError> {
self.all_families()
}
fn select_family_by_name(&self, family_name: &str) -> Result<FamilyHandle, SelectionError> {
self.select_family_by_name(family_name)
}
fn select_by_postscript_name(&self, postscript_name: &str) -> Result<Handle, SelectionError> {
self.select_by_postscript_name(postscript_name)
}
#[inline]
fn as_any(&self) -> &dyn Any {
self
}
#[inline]
fn as_mut_any(&mut self) -> &mut dyn Any {
self
}
}
#[allow(dead_code)]
fn css_to_core_text_font_weight(css_weight: Weight) -> f32 {
core_text_loader::piecewise_linear_lookup(
f32::max(100.0, css_weight.0) / 100.0 - 1.0,
&FONT_WEIGHT_MAPPING,
)
}
#[allow(dead_code)]
fn css_stretchiness_to_core_text_width(css_stretchiness: Stretch) -> f32 {
let css_stretchiness = utils::clamp(css_stretchiness.0, 0.5, 2.0);
0.25 * core_text_loader::piecewise_linear_find_index(css_stretchiness, &Stretch::MAPPING) - 1.0
}
fn create_handles_from_core_text_collection(
collection: CTFontCollection,
) -> Result<Vec<Handle>, SelectionError> {
let mut fonts = vec![];
if let Some(descriptors) = collection.get_descriptors() {
let mut font_data = HashMap::new();
'outer: for index in 0..descriptors.len() {
let descriptor = descriptors.get(index).unwrap();
let postscript_name = descriptor.font_name();
let font_path = descriptor.font_path().unwrap();
let data = if let Some(data) = font_data.get(&font_path) {
Arc::clone(data)
} else {
let mut file = if let Ok(file) = File::open(&font_path) {
file
} else {
continue;
};
let data = if let Ok(data) = utils::slurp_file(&mut file) {
Arc::new(data)
} else {
continue;
};
font_data.insert(font_path.clone(), Arc::clone(&data));
data
};
if let Ok(FileType::Collection(font_count)) = Font::analyze_bytes(Arc::clone(&data)) {
for font_index in 0..font_count {
if let Ok(font) = Font::from_bytes(Arc::clone(&data), font_index) {
if let Some(font_postscript_name) = font.postscript_name() {
if postscript_name == font_postscript_name {
fonts.push(Handle::from_memory(data, font_index));
continue 'outer;
}
}
}
}
fonts.push(Handle::from_memory(data, 0));
} else {
fonts.push(Handle::from_memory(data, 0));
}
}
}
if fonts.is_empty() {
Err(SelectionError::NotFound)
} else {
Ok(fonts)
}
}
fn create_handle_from_descriptor(descriptor: &CTFontDescriptor) -> Handle {
let font_path = Path::new(&descriptor.font_path().unwrap()).to_owned();
if let Ok(FileType::Collection(font_count)) = Font::analyze_path(font_path.clone()) {
let postscript_name = descriptor.font_name();
let mut file = if let Ok(file) = File::open(font_path.clone()) {
file
} else {
return Handle::from_path(font_path, 0);
};
let font_data = if let Ok(font_data) = utils::slurp_file(&mut file) {
Arc::new(font_data)
} else {
return Handle::from_path(font_path, 0);
};
for font_index in 0..font_count {
if let Ok(font) = Font::from_bytes(Arc::clone(&font_data), font_index) {
if let Some(font_postscript_name) = font.postscript_name() {
if postscript_name == font_postscript_name {
return Handle::from_memory(font_data, font_index);
}
}
}
}
Handle::from_memory(font_data, 0)
} else {
Handle::from_path(font_path, 0)
}
}
#[cfg(test)]
mod test {
use crate::properties::{Stretch, Weight};
#[test]
fn test_css_to_core_text_font_weight() {
assert_eq!(super::css_to_core_text_font_weight(Weight(100.0)), -0.7);
assert_eq!(super::css_to_core_text_font_weight(Weight(400.0)), 0.0);
assert_eq!(super::css_to_core_text_font_weight(Weight(700.0)), 0.4);
assert_eq!(super::css_to_core_text_font_weight(Weight(900.0)), 0.8);
assert_eq!(super::css_to_core_text_font_weight(Weight(450.0)), 0.1);
}
#[test]
fn test_css_to_core_text_font_stretch() {
assert_eq!(
super::css_stretchiness_to_core_text_width(Stretch(1.0)),
0.0
);
assert_eq!(
super::css_stretchiness_to_core_text_width(Stretch(0.5)),
-1.0
);
assert_eq!(
super::css_stretchiness_to_core_text_width(Stretch(2.0)),
1.0
);
assert_eq!(
super::css_stretchiness_to_core_text_width(Stretch(1.7)),
0.85
);
}
}