Debian Codegraph @

subprojects/fontconfig/fc-fontations/mod.rs

raw
1 /*
2 * fontconfig/fc-fontations/mod.rs
3 *
4 * Copyright 2025 Google LLC.
5 *
6 * Permission to use, copy, modify, distribute, and sell this software and its
7 * documentation for any purpose is hereby granted without fee, provided that
8 * the above copyright notice appear in all copies and that both that
9 * copyright notice and this permission notice appear in supporting
10 * documentation, and that the name of the author(s) not be used in
11 * advertising or publicity pertaining to distribution of the software without
12 * specific, written prior permission. The authors make no
13 * representations about the suitability of this software for any purpose. It
14 * is provided "as is" without express or implied warranty.
15 *
16 * THE AUTHOR(S) DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
17 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
18 * EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY SPECIAL, INDIRECT OR
19 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
20 * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
21 * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
22 * PERFORMANCE OF THIS SOFTWARE.
23 */
24
25 mod attributes;
26 mod bitmap;
27 mod capabilities;
28 mod charset;
29 mod foundries;
30 mod instance_enumerate;
31 mod lang;
32 mod name_records;
33 mod names;
34 mod pattern_bindings;
35
36 use attributes::append_style_elements;
37 use bitmap::add_pixel_size;
38 use capabilities::make_capabilities;
39 use foundries::make_foundry;
40 use lang::exclusive_lang;
41 use names::add_names;
42
43 use fontconfig_bindings::{FcFontSet, FcFontSetAdd, FcPattern};
44
45 use fcint_bindings::{
46 FcLangSetFromCharSet, FC_CAPABILITY_OBJECT, FC_CHARSET_OBJECT, FC_COLOR_OBJECT, FC_FILE_OBJECT,
47 FC_FONTFORMAT_OBJECT, FC_FONTVERSION_OBJECT, FC_FONT_HAS_HINT_OBJECT, FC_FONT_WRAPPER_OBJECT,
48 FC_FOUNDRY_OBJECT, FC_LANG_OBJECT, FC_ORDER_OBJECT, FC_OUTLINE_OBJECT, FC_SCALABLE_OBJECT,
49 FC_SYMBOL_OBJECT,
50 };
51
52 use font_types::Tag;
53 use pattern_bindings::{fc_wrapper::FcLangSetWrapper, FcPatternBuilder, PatternElement};
54 use skrifa::MetadataProvider;
55 use std::str::FromStr;
56
57 use read_fonts::{FileRef, FontRef, TableProvider};
58
59 use std::{
60 ffi::{CStr, CString, OsStr},
61 iter::IntoIterator,
62 os::unix::ffi::OsStrExt,
63 };
64
65 use instance_enumerate::{all_instances, fonts_and_indices};
66
67 #[no_mangle]
68 /// Externally called in fcfontations.c as the file scanner function
69 /// similar to the job that FreeType performs.
70 ///
71 /// # Safety
72 /// * At this point, the font file path is not dereferenced.
73 /// * In this initial sanity check mock call, only one empty pattern
74 /// is added to the FontSet, which is null checked, which is sound.
75 pub unsafe extern "C" fn add_patterns_to_fontset(
76 font_file: *const libc::c_char,
77 font_set: *mut FcFontSet,
78 ) -> libc::c_int {
79 let font_path = unsafe { OsStr::from_bytes(CStr::from_ptr(font_file).to_bytes()) };
80 let bytes = std::fs::read(font_path).ok().unwrap_or_default();
81 let fileref = FileRef::new(&bytes).ok();
82
83 let fonts = fonts_and_indices(fileref);
84
85 let mut patterns_added: u32 = 0;
86 for (font, ttc_index) in fonts {
87 for pattern in build_patterns_for_font(&font, font_file, ttc_index) {
88 unsafe {
89 if FcFontSetAdd(font_set, pattern) == 0 {
90 return 0;
91 }
92 patterns_added += 1;
93 }
94 }
95 }
96
97 // Fontations does not natively understand WOFF/WOFF2 compressed file,
98 // if we are asked to scan one of those, only add wrapper information
99 // and filename.
100 if patterns_added == 0 {
101 try_append_woff_pattern(font_set, bytes.as_slice(), font_file);
102 }
103
104 1
105 }
106
107 /// Used for controlling FontConfig's behavior per font instance.
108 ///
109 /// We add one pattern for the default instance, one for each named instance,
110 /// and one for using the font as a variable font, with ranges of values where applicable.
111 #[derive(Copy, Clone, Debug, PartialEq)]
112 #[allow(dead_code)]
113 enum InstanceMode {
114 Default,
115 Named(i32),
116 Variable,
117 }
118
119 fn try_append_woff_pattern(font_set: *mut FcFontSet, bytes: &[u8], font_file: *const libc::c_char) {
120 let wrapper: Option<CString> = match bytes.get(0..4) {
121 Some(b"wOFF") => CString::new("WOFF").ok(),
122 Some(b"wOF2") => CString::new("WOFF2").ok(),
123 _ => None,
124 };
125
126 if let Some(w) = wrapper {
127 let mut pattern = FcPatternBuilder::new();
128 pattern.append_element(PatternElement::new(FC_FONT_WRAPPER_OBJECT as i32, w.into()));
129 add_font_file_name(&mut pattern, font_file);
130
131 pattern
132 .create_fc_pattern()
133 .map(|p| unsafe { FcFontSetAdd(font_set, p.into_raw() as *mut FcPattern) });
134 }
135 }
136
137 fn has_one_of_tables<I>(font_ref: &FontRef, tags: I) -> bool
138 where
139 I: IntoIterator,
140 I::Item: ToString,
141 {
142 tags.into_iter().fold(false, |has_tag, tag| {
143 let tag = Tag::from_str(tag.to_string().as_str());
144 if let Ok(tag_converted) = tag {
145 return has_tag | font_ref.data_for_tag(tag_converted).is_some();
146 }
147 has_tag
148 })
149 }
150
151 fn has_hint(font_ref: &FontRef) -> bool {
152 if has_one_of_tables(font_ref, ["fpgm", "cvt "]) {
153 return true;
154 }
155
156 if let Some(prep_table) = font_ref.data_for_tag(Tag::new(b"prep")) {
157 return prep_table.len() > 7;
158 }
159 false
160 }
161
162 fn add_font_file_name(pattern: &mut FcPatternBuilder, font_file: *const libc::c_char) {
163 if !font_file.is_null() {
164 let filename = unsafe { std::ffi::CStr::from_ptr(font_file) };
165
166 pattern.append_element(PatternElement::new(
167 FC_FILE_OBJECT as i32,
168 filename.to_owned().into(),
169 ));
170 }
171 }
172
173 fn build_patterns_for_font(
174 font: &FontRef,
175 font_file: *const libc::c_char,
176 ttc_index: Option<i32>,
177 ) -> Vec<*mut FcPattern> {
178 let mut pattern = FcPatternBuilder::new();
179
180 let has_glyf = has_one_of_tables(font, ["glyf"]);
181 let has_cff = has_one_of_tables(font, ["CFF ", "CFF2"]);
182 let has_color = has_one_of_tables(font, ["COLR", "SVG ", "CBLC", "SBIX"]);
183
184 // Color and Outlines
185 let has_outlines = has_glyf | has_cff;
186
187 pattern.append_element(PatternElement::new(
188 FC_OUTLINE_OBJECT as i32,
189 has_outlines.into(),
190 ));
191 pattern.append_element(PatternElement::new(
192 FC_COLOR_OBJECT as i32,
193 has_color.into(),
194 ));
195 pattern.append_element(PatternElement::new(
196 FC_SCALABLE_OBJECT as i32,
197 (has_outlines || has_color).into(),
198 ));
199 pattern.append_element(PatternElement::new(
200 FC_FONT_HAS_HINT_OBJECT as i32,
201 has_hint(font).into(),
202 ));
203
204 match (has_glyf, has_cff) {
205 (_, true) => {
206 pattern.append_element(PatternElement::new(
207 FC_FONTFORMAT_OBJECT as i32,
208 CString::new("CFF").unwrap().into(),
209 ));
210 }
211 _ => {
212 pattern.append_element(PatternElement::new(
213 FC_FONTFORMAT_OBJECT as i32,
214 CString::new("TrueType").unwrap().into(),
215 ));
216 }
217 }
218
219 let foundry_string = make_foundry(font).unwrap_or(CString::new("unknown").unwrap());
220
221 pattern.append_element(PatternElement::new(
222 FC_FOUNDRY_OBJECT as i32,
223 foundry_string.into(),
224 ));
225
226 pattern.append_element(PatternElement::new(
227 FC_SYMBOL_OBJECT as i32,
228 font.charmap().is_symbol().into(),
229 ));
230
231 if let Some(capabilities) = make_capabilities(font) {
232 pattern.append_element(PatternElement::new(
233 FC_CAPABILITY_OBJECT as i32,
234 capabilities.into(),
235 ));
236 };
237
238 // CharSet and Langset.
239 if let Some(charset) = charset::make_charset(font) {
240 let exclusive_lang =
241 exclusive_lang(font).map_or(std::ptr::null(), |lang| lang.as_bytes_with_nul().as_ptr());
242
243 unsafe {
244 let langset =
245 FcLangSetWrapper::from_raw(FcLangSetFromCharSet(charset.as_ptr(), exclusive_lang)
246 as *mut fontconfig_bindings::_FcLangSet);
247
248 pattern.append_element(PatternElement::new(
249 FC_CHARSET_OBJECT as i32,
250 charset.into(),
251 ));
252
253 // TODO: Move FcFreeTypeLangSet to a different name, as the function does not actually depend on FreeType.
254 if !langset.is_null() {
255 pattern.append_element(PatternElement::new(FC_LANG_OBJECT as i32, langset.into()));
256 }
257 }
258 };
259
260 let version = font
261 .head()
262 .ok()
263 .map(|head| head.font_revision())
264 .unwrap_or_default()
265 .to_bits();
266
267 add_font_file_name(&mut pattern, font_file);
268
269 pattern.append_element(PatternElement::new(
270 FC_FONT_WRAPPER_OBJECT as i32,
271 CString::new("SFNT").unwrap().into(),
272 ));
273
274 pattern.append_element(PatternElement::new(
275 FC_FONTVERSION_OBJECT as i32,
276 version.into(),
277 ));
278
279 add_pixel_size(&mut pattern, font);
280
281 pattern.append_element(PatternElement::new(FC_ORDER_OBJECT as i32, 0.into()));
282
283 // So far the pattern elements applied to te whole font file, in the below,
284 // clone the current pattern state and add instance specific
285 // attributes. FontConfig for variable fonts produces a pattern for the
286 // default instance, each named instance, and a separate one for the
287 // "variable instance", which may contain ranges for pattern elements that
288 // describe variable aspects, such as weight of the font.
289 all_instances(font)
290 .flat_map(move |instance_mode| {
291 let mut instance_pattern = pattern.clone();
292
293 // Family, full name, postscript name, etc.
294 // Includes adding style name to the pattern, which is then used by append_style_elements.
295 add_names(font, instance_mode, &mut instance_pattern);
296
297 // Style names: fcfreetype adds TT_NAME_ID_WWS_SUBFAMILY, TT_NAME_ID_TYPOGRAPHIC_SUBFAMILY,
298 // TT_NAME_ID_FONT_SUBFAMILY as FC_STYLE_OBJECT, FC_STYLE_OBJECT_LANG unless a named instance
299 // is added,then the instance's name id is used as FC_STYLE_OBJECT.
300 append_style_elements(font, instance_mode, ttc_index, &mut instance_pattern);
301
302 instance_pattern
303 .create_fc_pattern()
304 .map(|wrapper| wrapper.into_raw() as *mut FcPattern)
305 })
306 .collect::<Vec<_>>()
307 }
308
309 #[cfg(test)]
310 mod test {
311 use crate::add_patterns_to_fontset;
312 use fontconfig_bindings::{FcFontSetCreate, FcFontSetDestroy};
313 use std::ffi::CString;
314
315 #[test]
316 fn basic_pattern_construction() {
317 unsafe {
318 let font_set = FcFontSetCreate();
319 assert!(add_patterns_to_fontset(CString::new("").unwrap().into_raw(), font_set) == 1);
320 FcFontSetDestroy(font_set);
321 }
322 }
323 }