Debian Codegraph @

subprojects/fontconfig/fc-fontations/pattern_bindings/mod.rs

raw
1 /*
2 * fontconfig/fc-fontations/pattern_bindings/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 pub mod fc_wrapper;
26
27 use std::ffi::CString;
28 use std::fmt::Debug;
29
30 use fcint_bindings::{
31 FcPattern, FcPatternObjectAddBool, FcPatternObjectAddCharSet, FcPatternObjectAddDouble,
32 FcPatternObjectAddInteger, FcLangSet, FcPatternObjectAddLangSet, FcPatternObjectAddRange,
33 FcPatternObjectAddString, FC_FAMILY_OBJECT, FC_FILE_OBJECT,
34 };
35
36 use fc_wrapper::{FcCharSetWrapper, FcLangSetWrapper, FcPatternWrapper, FcRangeWrapper};
37
38 #[allow(unused)]
39 #[derive(Debug, Clone)]
40 pub enum PatternValue {
41 String(CString),
42 Boolean(bool),
43 Integer(i32),
44 Double(f64),
45 Range(FcRangeWrapper),
46 LangSet(FcLangSetWrapper),
47 CharSet(FcCharSetWrapper),
48 }
49
50 impl From<CString> for PatternValue {
51 fn from(item: CString) -> Self {
52 PatternValue::String(item)
53 }
54 }
55
56 impl From<i32> for PatternValue {
57 fn from(item: i32) -> Self {
58 PatternValue::Integer(item)
59 }
60 }
61
62 impl From<bool> for PatternValue {
63 fn from(item: bool) -> Self {
64 PatternValue::Boolean(item)
65 }
66 }
67
68 impl From<f64> for PatternValue {
69 fn from(item: f64) -> Self {
70 PatternValue::Double(item)
71 }
72 }
73
74 impl From<FcRangeWrapper> for PatternValue {
75 fn from(item: FcRangeWrapper) -> Self {
76 PatternValue::Range(item)
77 }
78 }
79
80 impl From<FcCharSetWrapper> for PatternValue {
81 fn from(value: FcCharSetWrapper) -> Self {
82 PatternValue::CharSet(value)
83 }
84 }
85
86 impl From<FcLangSetWrapper> for PatternValue {
87 fn from(value: FcLangSetWrapper) -> Self {
88 PatternValue::LangSet(value)
89 }
90 }
91
92 #[derive(Debug, Clone)]
93 pub struct PatternElement {
94 pub object_id: i32,
95 pub value: PatternValue,
96 }
97
98 impl PatternElement {
99 #[allow(unused)]
100 pub fn new(object_id: i32, value: PatternValue) -> Self {
101 Self { object_id, value }
102 }
103 }
104
105 #[derive(Debug, Clone)]
106 struct PatternAddError;
107
108 impl std::fmt::Display for PatternAddError {
109 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
110 write!(f, "Failed to add object to Fontconfig pattern.")
111 }
112 }
113
114 impl PatternElement {
115 fn append_to_fc_pattern(self, pattern: *mut FcPattern) -> Result<(), PatternAddError> {
116 let pattern_add_success = match self.value {
117 PatternValue::String(string) => unsafe {
118 FcPatternObjectAddString(pattern, self.object_id, string.as_ptr() as *const u8)
119 },
120 PatternValue::Boolean(value) => unsafe {
121 FcPatternObjectAddBool(pattern, self.object_id, value as i32)
122 },
123 PatternValue::Integer(value) => unsafe {
124 FcPatternObjectAddInteger(pattern, self.object_id, value)
125 },
126 PatternValue::Double(value) => unsafe {
127 FcPatternObjectAddDouble(pattern, self.object_id, value)
128 },
129 PatternValue::Range(value) => unsafe {
130 FcPatternObjectAddRange(pattern, self.object_id, value.into_raw())
131 },
132 PatternValue::CharSet(value) => unsafe {
133 FcPatternObjectAddCharSet(pattern, self.object_id, value.into_raw())
134 },
135 PatternValue::LangSet(value) => unsafe {
136 FcPatternObjectAddLangSet(
137 pattern,
138 self.object_id,
139 value.into_raw() as *const FcLangSet,
140 )
141 },
142 } == 1;
143 if pattern_add_success {
144 return Ok(());
145 }
146 Err(PatternAddError)
147 }
148 }
149
150 #[derive(Default, Debug, Clone)]
151 pub struct FcPatternBuilder {
152 elements: Vec<PatternElement>,
153 }
154
155 impl FcPatternBuilder {
156 #[allow(unused)]
157 pub fn new() -> Self {
158 Self::default()
159 }
160
161 #[allow(unused)]
162 pub fn append_element(&mut self, element: PatternElement) {
163 self.elements.push(element);
164 }
165
166 #[allow(unused)]
167 pub fn create_fc_pattern(&mut self) -> Option<FcPatternWrapper> {
168 let pattern = FcPatternWrapper::new()?;
169
170 let mut family_name_or_file_name_encountered = false;
171
172 const FAMILY_ID: i32 = FC_FAMILY_OBJECT as i32;
173 const FILE_ID: i32 = FC_FILE_OBJECT as i32;
174
175 for element in self.elements.drain(0..) {
176 if let PatternElement {
177 object_id: FAMILY_ID | FILE_ID,
178 value: PatternValue::String(ref file_fam_name),
179 } = element
180 {
181 if !file_fam_name.is_empty() {
182 family_name_or_file_name_encountered = true;
183 }
184 }
185 element.append_to_fc_pattern(pattern.as_ptr()).ok()?;
186 }
187
188 if !family_name_or_file_name_encountered {
189 return None;
190 }
191
192 Some(pattern)
193 }
194 }
195
196 /// Mainly needed for finding the style PatternElement in attributes.rs.
197 impl<'a> IntoIterator for &'a FcPatternBuilder {
198 type Item = &'a PatternElement;
199 type IntoIter = std::slice::Iter<'a, PatternElement>;
200
201 fn into_iter(self) -> Self::IntoIter {
202 self.elements.iter()
203 }
204 }
205
206 #[cfg(test)]
207 mod test {
208 use std::ffi::CString;
209
210 use crate::pattern_bindings::fc_wrapper::FcLangSetWrapper;
211
212 use super::{
213 fc_wrapper::FcCharSetWrapper, FcPatternBuilder, FcRangeWrapper, PatternElement,
214 PatternValue,
215 };
216 use fontconfig_bindings::{
217 FcCharSet, FcCharSetAddChar, FcCharSetHasChar, FcLangSet, FcLangSetAdd, FcLangSetHasLang,
218 _FcLangResult_FcLangEqual,
219 };
220
221 use fcint_bindings::{
222 FcPatternObjectGetBool, FcPatternObjectGetCharSet, FcPatternObjectGetDouble,
223 FcPatternObjectGetInteger, FcPatternObjectGetLangSet, FcPatternObjectGetRange,
224 FcPatternObjectGetString, FcRange, FC_CHARSET_OBJECT, FC_COLOR_OBJECT, FC_FAMILY_OBJECT,
225 FC_LANG_OBJECT, FC_SLANT_OBJECT, FC_WEIGHT_OBJECT, FC_WIDTH_OBJECT,
226 };
227
228 #[test]
229 fn verify_pattern_bindings() {
230 let mut pattern_builder = FcPatternBuilder::new();
231
232 // Add a bunch of test properties.
233 pattern_builder.append_element(PatternElement::new(
234 FC_COLOR_OBJECT as i32,
235 PatternValue::Boolean(true),
236 ));
237 pattern_builder.append_element(PatternElement::new(
238 FC_WEIGHT_OBJECT as i32,
239 PatternValue::Double(800.),
240 ));
241 pattern_builder.append_element(PatternElement::new(
242 FC_SLANT_OBJECT as i32,
243 PatternValue::Integer(15),
244 ));
245
246 pattern_builder.append_element(PatternElement::new(
247 FC_WIDTH_OBJECT as i32,
248 PatternValue::Range(FcRangeWrapper::new(100., 400.).unwrap()),
249 ));
250
251 pattern_builder.append_element(PatternElement::new(
252 FC_FAMILY_OBJECT as i32,
253 PatternValue::String(CString::new("TestFont").unwrap()),
254 ));
255
256 let test_charset = FcCharSetWrapper::new().unwrap();
257 const BIANG: u32 = 0x30EDE;
258 unsafe {
259 assert!(FcCharSetAddChar(test_charset.as_ptr(), BIANG) != 0);
260 }
261
262 pattern_builder.append_element(PatternElement::new(
263 FC_CHARSET_OBJECT as i32,
264 PatternValue::CharSet(test_charset),
265 ));
266
267 let test_langset = FcLangSetWrapper::new().unwrap();
268 const LANG_EN: &[u8] = b"en\0";
269 unsafe {
270 assert!(FcLangSetAdd(test_langset.as_ptr(), LANG_EN.as_ptr()) != 0);
271 }
272
273 pattern_builder.append_element(PatternElement::new(
274 FC_LANG_OBJECT as i32,
275 PatternValue::LangSet(test_langset),
276 ));
277
278 let pattern = pattern_builder.create_fc_pattern().unwrap();
279
280 let fontconfig_pattern = pattern.as_ptr();
281 unsafe {
282 // Verify color properties.
283 let mut result: i32 = 0;
284 let get_result =
285 FcPatternObjectGetBool(fontconfig_pattern, FC_COLOR_OBJECT as i32, 0, &mut result);
286 assert_eq!(get_result, 0);
287 assert_eq!(result, 1);
288
289 // Verify weight value.
290 let mut weight_result: f64 = 0.;
291 let get_result = FcPatternObjectGetDouble(
292 fontconfig_pattern,
293 FC_WEIGHT_OBJECT as i32,
294 0,
295 &mut weight_result,
296 );
297 assert_eq!(get_result, 0);
298 assert_eq!(weight_result, 800.0);
299
300 // Verify that weight is not a range.
301 let range_result: *mut *mut FcRange = std::mem::zeroed();
302 assert_eq!(
303 FcPatternObjectGetRange(
304 fontconfig_pattern,
305 FC_WEIGHT_OBJECT as i32,
306 0,
307 range_result
308 ),
309 2
310 );
311
312 // Verify slant.
313 let mut slant_result: i32 = 0;
314 let get_result = FcPatternObjectGetInteger(
315 fontconfig_pattern,
316 FC_SLANT_OBJECT as i32,
317 0,
318 &mut slant_result,
319 );
320 assert_eq!(get_result, 0);
321 assert_eq!(slant_result, 15);
322
323 // Verify width.
324 let mut width_result: *mut FcRange = std::mem::zeroed();
325 let get_result = FcPatternObjectGetRange(
326 fontconfig_pattern,
327 FC_WIDTH_OBJECT as i32,
328 0,
329 &mut width_result,
330 );
331 assert_eq!(get_result, 0);
332 assert_eq!((*width_result).begin, 100.);
333 assert_eq!((*width_result).end, 400.);
334
335 // Verify family name.
336 let mut family_result: *mut u8 = std::mem::zeroed();
337 let get_result = FcPatternObjectGetString(
338 fontconfig_pattern,
339 FC_FAMILY_OBJECT as i32,
340 0,
341 &mut family_result,
342 );
343 assert_eq!(get_result, 0);
344 assert_eq!(
345 std::ffi::CStr::from_ptr(family_result as *const i8)
346 .to_str()
347 .unwrap(),
348 "TestFont"
349 );
350
351 // Verify CharSet.
352 let mut retrieved_charset: *mut FcCharSet = std::mem::zeroed();
353 let get_result = FcPatternObjectGetCharSet(
354 fontconfig_pattern,
355 FC_CHARSET_OBJECT as i32,
356 0,
357 &mut retrieved_charset,
358 );
359 assert_eq!(get_result, 0);
360 assert_eq!(FcCharSetHasChar(retrieved_charset, BIANG), 1);
361
362 // Verify LangSet.
363 let mut retrieved_langset: *mut FcLangSet = std::mem::zeroed();
364 let get_result = FcPatternObjectGetLangSet(
365 fontconfig_pattern,
366 FC_LANG_OBJECT as i32,
367 0,
368 &mut retrieved_langset,
369 );
370 assert_eq!(get_result, 0);
371 assert_eq!(
372 FcLangSetHasLang(retrieved_langset, LANG_EN.as_ptr()),
373 _FcLangResult_FcLangEqual
374 );
375 }
376 }
377 }