fontconfig-rs 0.1.1

Safe, higher-level wrapper around the fontconfig library
Documentation
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
//!
use std::borrow::{Borrow, BorrowMut};
use std::ffi::{CStr, CString};

use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::os::raw::c_char;
use std::ptr::{self, NonNull};
use std::str::FromStr;

///!
use fontconfig_sys as sys;

#[cfg(feature = "dlopen")]
use sys::statics::LIB;
#[cfg(not(feature = "dlopen"))]
use sys::*;

use sys::constants::*;
use sys::{ffi_dispatch, FcPattern};

use crate::charset::OwnedCharSet;
use crate::{
    CharSet, Error, FcFalse, FcStr, FcTrue, FontConfig, FontFormat, FontSet, LangSet, Matrix,
    ObjectSet, Result, ToResult,
};

/// Representation of a borrowed fontconfig's [`sys::FcPattern`].
///
/// An `Pattern` is an opaque type that holds both patterns to match against the available fonts, as well as the information about each font.
#[doc(alias = "FcPattern")]
#[repr(transparent)]
pub struct Pattern(FcPattern);

/// A type representing an owned fontconfig's [`sys::FcPattern`].
#[doc(alias = "FcPattern")]
#[repr(transparent)]
pub struct OwnedPattern {
    /// Raw pointer to `FcPattern`
    pub(crate) pat: NonNull<FcPattern>,
}

impl OwnedPattern {
    /// Create a new empty [`OwnedPattern`].
    pub fn new() -> OwnedPattern {
        let pat = unsafe { ffi_dispatch!(LIB, FcPatternCreate,) };
        assert!(!pat.is_null());

        OwnedPattern {
            pat: NonNull::new(pat).expect("out of memory"),
        }
    }

    pub(crate) fn into_inner(self) -> *mut FcPattern {
        let ptr = self.pat.as_ptr() as *mut FcPattern;
        std::mem::forget(self);
        ptr
    }
}

impl Pattern {
    /// Delete a property from a pattern
    pub fn del(&mut self, name: &CStr) -> bool {
        FcTrue == unsafe { ffi_dispatch!(LIB, FcPatternDel, self.as_mut_ptr(), name.as_ptr()) }
    }

    /// Print this pattern to stdout with all its values.
    pub fn print(&self) {
        unsafe {
            ffi_dispatch!(LIB, FcPatternPrint, self.as_ptr());
        }
    }

    /// Filter the objects of pattern
    ///
    /// Returns a new pattern that only has those objects from `self` that are in os.
    /// If os is None, a duplicate of `self` is returned.
    pub fn filter(&self, os: Option<&mut ObjectSet>) -> Option<OwnedPattern> {
        let os = os.map(|o| o.as_mut_ptr()).unwrap_or(ptr::null_mut());
        let pat = unsafe {
            let pat = ffi_dispatch!(LIB, FcPatternFilter, self.as_ptr() as *mut FcPattern, os);
            if pat.is_null() {
                return None;
            }
            pat
        };
        NonNull::new(pat).map(|pat| OwnedPattern { pat })
    }

    /// Format a pattern into a string according to a format specifier
    ///
    /// See: [pattern-format](https://www.freedesktop.org/software/fontconfig/fontconfig-devel/fcpatternformat.html)
    pub fn format(&self, fmt: &CStr) -> Option<FcStr> {
        unsafe {
            let s = ffi_dispatch!(
                LIB,
                FcPatternFormat,
                self.as_ptr() as *mut FcPattern,
                fmt.as_ptr() as *const u8
            );
            FcStr::from_ptr(s)
        }
    }

    /// Perform default substitutions in a pattern
    ///
    /// Supplies default values for underspecified font patterns:
    ///
    /// * Patterns without a specified style or weight are set to Medium   
    /// * Patterns without a specified style or slant are set to Roman   
    /// * Patterns without a specified pixel size are given one computed from any specified point size (default 12), dpi (default 75) and scale (default 1).  
    pub fn default_substitute(&mut self) {
        unsafe {
            ffi_dispatch!(LIB, FcDefaultSubstitute, self.as_mut_ptr());
        }
    }

    /// Get the best available match for this pattern, returned as a new pattern.
    ///
    /// Finds the font in sets most closely matching pattern and returns the result of [`Pattern::render_prepare`] for that font and the provided pattern.   
    /// This function should be called only after [`FontConfig::substitute`] and [`Pattern::default_substitute`] have been called for the pattern.    
    /// otherwise the results will not be correct.
    #[doc(alias = "FcFontMatch")]
    pub fn font_match(&mut self, config: &mut FontConfig) -> OwnedPattern {
        // self.default_substitute();
        // config.substitute(self, MatchKind::Pattern);

        unsafe {
            let mut res = sys::FcResultNoMatch;
            let pat = ffi_dispatch!(
                LIB,
                FcFontMatch,
                config.as_mut_ptr(),
                self.as_mut_ptr(),
                &mut res
            );
            res.ok().unwrap();
            OwnedPattern {
                pat: NonNull::new(pat).unwrap(),
            }
        }
    }

    /// List fonts
    ///
    /// Selects fonts matching `self`,
    /// creates patterns from those fonts containing only the objects in os and returns the set of unique such patterns.    
    pub fn font_list(&self, config: &mut FontConfig, os: Option<&mut ObjectSet>) -> FontSet<'_> {
        let os = os.map(|o| o.as_mut_ptr()).unwrap_or(ptr::null_mut());
        let set = unsafe {
            ffi_dispatch!(
                LIB,
                FcFontList,
                config.as_mut_ptr(),
                self.as_ptr() as *mut _,
                os
            )
        };
        // NOTE: Referenced by FontSet, should not drop it.
        FontSet {
            fcset: NonNull::new(set).unwrap(),
            _marker: PhantomData,
        }
    }

    /// Get the list of fonts sorted by closeness to self.
    ///
    /// If trim is `true`, elements in the list which don't include Unicode coverage not provided by earlier elements in the list are elided.    
    /// This function should be called only after [`FontConfig::substitute`] and [`Pattern::default_substitute`] have been called for this pattern;    
    /// otherwise the results will not be correct.
    pub fn font_sort(&mut self, config: &mut FontConfig, trim: bool) -> Result<FontSet<'static>> {
        unsafe {
            // What is this result actually used for? Seems redundant with
            // return type.
            let mut res = sys::FcResultNoMatch;

            let mut charsets: *mut _ = ptr::null_mut();

            let fcset = ffi_dispatch!(
                LIB,
                FcFontSort,
                config.as_mut_ptr(),
                self.as_ptr() as *mut _,
                if trim { FcTrue } else { FcFalse }, // Trim font list.
                &mut charsets,
                &mut res
            );
            res.ok()?;
            if fcset.is_null() {
                return Err(Error::OutOfMemory);
            }
            let fcset = NonNull::new_unchecked(fcset);
            Ok(FontSet {
                fcset,
                _marker: PhantomData,
            })
        }
    }

    /// Get the list of fonts sorted by closeness to self.
    ///
    /// If trim is `true`, elements in the list which don't include Unicode coverage not provided by earlier elements in the list are elided.    
    /// The union of Unicode coverage of all of the fonts is returned in [`CharSet`].   
    /// This function should be called only after [`FontConfig::substitute`] and [`Pattern::default_substitute`] have been called for this pattern;    
    /// otherwise the results will not be correct.
    pub fn font_sort_with_charset(
        &mut self,
        config: &mut FontConfig,
        trim: bool,
    ) -> Option<(FontSet<'_>, OwnedCharSet)> {
        // self.default_substitute();
        // config.substitute(self, MatchKind::Pattern);
        unsafe {
            // What is this result actually used for? Seems redundant with
            // return type.
            let mut res = sys::FcResultNoMatch;

            let mut charsets: *mut _ = ptr::null_mut();

            let fcset = ffi_dispatch!(
                LIB,
                FcFontSort,
                config.as_mut_ptr(),
                self.as_mut_ptr(),
                if trim { FcTrue } else { FcFalse }, // Trim font list.
                &mut charsets,
                &mut res
            );
            res.opt()?;
            Some((
                FontSet {
                    fcset: NonNull::new(fcset).unwrap(),
                    _marker: PhantomData,
                },
                OwnedCharSet {
                    fcset: NonNull::new(charsets).unwrap(),
                },
            ))
        }
    }

    /// Prepare pattern for loading font file.
    ///
    /// Creates a new pattern consisting of elements of font not appearing in pat,
    /// elements of pat not appearing in font and the best matching value from pat for elements appearing in both.    
    /// The result is passed to [`FontConfig::substitute_with_pat`] with kind [`crate::MatchKind::Font`] and then returned.
    #[doc(alias = "FcFontRenderPrepare")]
    pub fn render_prepare(&mut self, config: &mut FontConfig, font: &mut Self) -> OwnedPattern {
        let pat = unsafe {
            ffi_dispatch!(
                LIB,
                FcFontRenderPrepare,
                config.as_mut_ptr(),
                self.as_mut_ptr(),
                font.as_mut_ptr()
            )
        };
        OwnedPattern {
            pat: NonNull::new(pat).unwrap(),
        }
    }

    /// Get character map
    #[doc(alias = "FcPatternGetCharSet")]
    pub fn charset(&self) -> Option<&CharSet> {
        unsafe {
            let mut charsets = ffi_dispatch!(LIB, FcCharSetCreate,);
            ffi_dispatch!(
                LIB,
                FcPatternGetCharSet,
                self.as_ptr() as *mut _,
                FC_CHARSET.as_ptr(),
                0,
                &mut charsets
            );
            if charsets.is_null() {
                None
            } else {
                Some(&*(charsets as *const CharSet))
            }
        }
    }

    /// Get the "fullname" (human-readable name) of this pattern.
    pub fn name(&self) -> Option<&str> {
        self.get(&properties::FC_FULLNAME, 0)
    }

    /// Get the "file" (path on the filesystem) of this font pattern.
    pub fn filename(&self) -> Option<&str> {
        self.get(&properties::FC_FILE, 0)
    }

    /// Get the "index" (The index of the font within the file) of this pattern.
    pub fn face_index(&self) -> Option<i32> {
        self.get(&properties::FC_INDEX, 0)
    }

    /// Get the "slant" (Italic, oblique or roman) of this pattern.
    pub fn slant(&self) -> Option<i32> {
        self.get(&properties::FC_SLANT, 0)
    }

    /// Get the "weight" (Light, medium, demibold, bold or black) of this pattern.
    pub fn weight(&self) -> Option<i32> {
        self.get(&properties::FC_WEIGHT, 0)
    }

    /// Get the "width" (Condensed, normal or expanded) of this pattern.
    pub fn width(&self) -> Option<i32> {
        self.get(&properties::FC_WIDTH, 0)
    }

    /// Get the "fontformat" ("TrueType" "Type 1" "BDF" "PCF" "Type 42" "CID Type 1" "CFF" "PFR" "Windows FNT") of this pattern.
    pub fn fontformat(&self) -> Result<FontFormat> {
        self.get(&properties::FC_FONTFORMAT, 0)
            .ok_or_else(|| Error::UnknownFontFormat(String::new()))
            .and_then(|format| format.parse())
    }

    ///
    pub fn hash(&self) -> u32 {
        unsafe { ffi_dispatch!(LIB, FcPatternHash, self.as_ptr() as *mut _) }
    }

    /// Returns a raw pointer to underlying [`sys::FcPattern`].
    pub(crate) fn as_ptr(&self) -> *const FcPattern {
        self as *const _ as *const FcPattern
    }

    /// Returns an unsafe mutable pointer to the underlying [`sys::FcPattern`].
    pub(crate) fn as_mut_ptr(&mut self) -> *mut FcPattern {
        self as *mut _ as *mut FcPattern
    }
}

impl ToOwned for Pattern {
    type Owned = OwnedPattern;

    fn to_owned(&self) -> OwnedPattern {
        OwnedPattern {
            pat: NonNull::new(unsafe { ffi_dispatch!(LIB, FcPatternDuplicate, self.as_ptr()) })
                .unwrap(),
        }
    }
}

impl Borrow<Pattern> for OwnedPattern {
    fn borrow(&self) -> &Pattern {
        unsafe { &*(self.as_ptr() as *const Pattern) }
    }
}

impl BorrowMut<Pattern> for OwnedPattern {
    fn borrow_mut(&mut self) -> &mut Pattern {
        unsafe { &mut *(self.as_mut_ptr() as *mut Pattern) }
    }
}

impl FromStr for OwnedPattern {
    type Err = Error;
    /// Converts `name` from the standard text format described above into a pattern.
    fn from_str(s: &str) -> Result<Self> {
        let c_str = CString::new(s).unwrap();
        unsafe {
            let pat = ffi_dispatch!(LIB, FcNameParse, c_str.as_ptr().cast());
            if let Some(pat) = NonNull::new(pat) {
                Ok(OwnedPattern { pat })
            } else {
                Err(Error::OutOfMemory)
            }
        }
    }
}

impl std::fmt::Debug for Pattern {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let fcstr = unsafe { ffi_dispatch!(LIB, FcNameUnparse, self.as_ptr() as *mut FcPattern) };
        let fcstr = unsafe { CStr::from_ptr(fcstr as *const c_char) };
        let result = write!(f, "{:?}", fcstr);
        unsafe { ffi_dispatch!(LIB, FcStrFree, fcstr.as_ptr() as *mut u8) };
        result
    }
}

impl Clone for OwnedPattern {
    fn clone(&self) -> Self {
        let cloned = unsafe { ffi_dispatch!(LIB, FcPatternDuplicate, self.pat.as_ptr()) };
        OwnedPattern {
            pat: NonNull::new(cloned).unwrap(),
        }
    }
}

impl Drop for OwnedPattern {
    fn drop(&mut self) {
        unsafe {
            ffi_dispatch!(LIB, FcPatternDestroy, self.pat.as_ptr());
        }
    }
}

impl Deref for OwnedPattern {
    type Target = Pattern;

    fn deref(&self) -> &Self::Target {
        unsafe { &*(self.pat.as_ptr() as *const _) }
    }
}

impl DerefMut for OwnedPattern {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { &mut *(self.pat.as_ptr() as *mut _) }
    }
}

impl AsRef<Pattern> for OwnedPattern {
    fn as_ref(&self) -> &Pattern {
        self
    }
}

impl AsMut<Pattern> for OwnedPattern {
    fn as_mut(&mut self) -> &mut Pattern {
        self
    }
}

impl Pattern {
    /// Get the languages set of this pattern.
    pub fn lang_set(&self) -> Option<LangSet> {
        // let mut langset = LangSet::new();
        let langset = unsafe {
            let mut langset = ffi_dispatch!(LIB, FcLangSetCreate,);
            ffi_dispatch!(
                LIB,
                FcPatternGetLangSet,
                self.as_ptr() as *mut _,
                FC_LANG.as_ptr(),
                0,
                &mut langset
            )
            .opt()?;
            ffi_dispatch!(LIB, FcLangSetCopy, langset)
        };
        NonNull::new(langset).map(|langset| LangSet { langset })
    }

    /// Get the matrix from this pattern.
    pub fn matrix(&mut self) -> Option<&Matrix> {
        let mut matrix = ptr::null_mut();
        unsafe {
            ffi_dispatch!(
                LIB,
                FcPatternGetMatrix,
                self.as_mut_ptr(),
                FC_MATRIX.as_ptr(),
                0,
                &mut matrix
            )
            .opt()?;
            if matrix.is_null() {
                None
            } else {
                Some(&*(matrix as *mut crate::Matrix))
            }
        }
    }

    ///
    pub fn get<'a, 'pat, V>(
        &'pat self,
        name: &'a properties::Property<'pat, V>,
        index: usize,
    ) -> Option<V::Returns>
    where
        V: properties::PropertyType<'pat>,
    {
        name.value_of(self, index)
    }

    ///
    pub fn add<'a, 'pat, V>(
        &'pat mut self,
        name: &'a properties::Property<'pat, V>,
        value: V,
    ) -> bool
    where
        V: properties::PropertyType<'pat>,
    {
        name.value_for(self, value)
    }
}

impl Default for OwnedPattern {
    fn default() -> Self {
        let mut pat = OwnedPattern::new();
        pat.default_substitute();
        pat
    }
}

///
pub mod properties {
    use std::ffi::CStr;
    use std::marker::PhantomData;
    use std::ptr::NonNull;

    use fontconfig_sys as sys;

    #[cfg(feature = "dlopen")]
    use sys::statics::LIB;
    #[cfg(not(feature = "dlopen"))]
    use sys::*;

    use sys::ffi_dispatch;

    use crate::{FcFalse, FcTrue, ToResult};

    use super::Pattern;

    ///
    pub struct Property<'pat, V: PropertyType<'pat>> {
        name: const_cstr::ConstCStr,
        val: PhantomData<&'pat V>,
    }

    impl<'pat, V> Property<'pat, V>
    where
        V: PropertyType<'pat>,
    {
        pub(super) fn value_of<'a>(
            &'a self,
            pat: &'pat Pattern,
            index: usize,
        ) -> Option<V::Returns> {
            V::value(pat, self, index)
        }

        pub(super) fn value_for<'a>(&'a self, pat: &'pat mut Pattern, value: V) -> bool {
            value.set_to(pat, self)
        }
    }

    mod private {
        use crate::Pattern;

        use super::{Property, PropertyType};

        pub trait MaybeRef<'a> {
            type Returns;
        }

        pub trait Sealed<'pat>: Sized + MaybeRef<'pat> {
            fn value<'a>(
                pat: &'pat Pattern,
                property: &'a Property<'pat, Self>,
                index: usize,
            ) -> Option<<Self as MaybeRef<'pat>>::Returns>
            where
                Self: PropertyType<'pat>;
            fn set_to<'a>(self, pat: &'pat mut Pattern, property: &'a Property<'pat, Self>) -> bool
            where
                Self: PropertyType<'pat>;
        }
    }

    ///
    pub trait PropertyType<'pat>: private::Sealed<'pat> {}

    impl<'pat, T> PropertyType<'pat> for T where T: private::Sealed<'pat> {}

    impl<'pat> private::MaybeRef<'pat> for String {
        type Returns = &'pat str;
    }

    impl<'pat> private::Sealed<'pat> for String {
        fn value<'a>(
            pat: &'pat Pattern,
            name: &'a Property<'pat, Self>,
            index: usize,
        ) -> Option<Self::Returns> {
            let c_str = unsafe {
                let mut ret: *mut sys::FcChar8 = std::ptr::null_mut();
                ffi_dispatch!(
                    LIB,
                    FcPatternGetString,
                    pat.as_ptr() as *mut _,
                    name.name.as_ptr(),
                    index as i32,
                    &mut ret
                )
                .opt()?;
                if ret.is_null() {
                    return None;
                }
                CStr::from_ptr(ret as *const _)
            };
            c_str.to_str().ok()
        }

        fn set_to<'a>(mut self, pat: &'pat mut Pattern, name: &'a Property<'pat, Self>) -> bool {
            self.push('\0');
            let c_str = CStr::from_bytes_with_nul(self.as_bytes()).unwrap();
            FcTrue
                == unsafe {
                    ffi_dispatch!(
                        LIB,
                        FcPatternAddString,
                        pat.as_mut_ptr(),
                        name.name.as_ptr(),
                        c_str.as_ptr() as *mut _
                    )
                }
        }
    }

    impl<'a> private::MaybeRef<'a> for i32 {
        type Returns = i32;
    }

    impl<'a> private::Sealed<'a> for i32 {
        fn value(pat: &Pattern, name: &Property<Self>, index: usize) -> Option<Self::Returns> {
            let mut val: i32 = 0;
            unsafe {
                ffi_dispatch!(
                    LIB,
                    FcPatternGetInteger,
                    pat.as_ptr() as *mut _,
                    name.name.as_ptr(),
                    index as i32,
                    &mut val
                )
                .opt()?;
            };
            Some(val)
        }

        fn set_to(self, pat: &mut Pattern, property: &Property<Self>) -> bool {
            FcTrue
                == unsafe {
                    ffi_dispatch!(
                        LIB,
                        FcPatternAddInteger,
                        pat.as_mut_ptr(),
                        property.name.as_ptr(),
                        self
                    )
                }
        }
    }

    impl<'a> private::MaybeRef<'a> for bool {
        type Returns = bool;
    }

    impl<'a> private::Sealed<'a> for bool {
        fn value(pat: &Pattern, name: &Property<Self>, index: usize) -> Option<Self::Returns> {
            let mut val: i32 = 0;
            unsafe {
                ffi_dispatch!(
                    LIB,
                    FcPatternGetBool,
                    pat.as_ptr() as *mut _,
                    name.name.as_ptr(),
                    index as i32,
                    &mut val
                )
                .opt()?;
            };
            Some(val == FcTrue)
        }

        fn set_to(self, pat: &mut Pattern, property: &Property<Self>) -> bool {
            FcTrue
                == unsafe {
                    ffi_dispatch!(
                        LIB,
                        FcPatternAddBool,
                        pat.as_mut_ptr(),
                        property.name.as_ptr(),
                        if self { FcTrue } else { FcFalse }
                    )
                }
        }
    }

    impl<'a> private::MaybeRef<'a> for f64 {
        type Returns = f64;
    }

    impl<'a> private::Sealed<'a> for f64 {
        fn value(pat: &Pattern, name: &Property<Self>, index: usize) -> Option<Self::Returns> {
            let mut val: f64 = 0.;
            unsafe {
                ffi_dispatch!(
                    LIB,
                    FcPatternGetDouble,
                    pat.as_ptr() as *mut _,
                    name.name.as_ptr(),
                    index as i32,
                    &mut val
                )
                .opt()?;
            };
            Some(val)
        }

        fn set_to(self, pat: &mut Pattern, property: &Property<Self>) -> bool {
            FcTrue
                == unsafe {
                    ffi_dispatch!(
                        LIB,
                        FcPatternAddDouble,
                        pat.as_mut_ptr(),
                        property.name.as_ptr(),
                        self
                    )
                }
        }
    }

    impl<'a> private::MaybeRef<'a> for crate::Matrix {
        type Returns = &'a crate::Matrix;
    }

    impl<'pat> private::Sealed<'pat> for crate::Matrix {
        fn value(pat: &'pat Pattern, name: &Property<Self>, index: usize) -> Option<Self::Returns> {
            let val = unsafe {
                let mut val = std::ptr::null_mut();
                ffi_dispatch!(
                    LIB,
                    FcPatternGetMatrix,
                    pat.as_ptr() as *mut _,
                    name.name.as_ptr(),
                    index as i32,
                    &mut val
                )
                .opt()?;
                if val.is_null() {
                    return None;
                }
                &*(val as *mut crate::Matrix)
            };
            Some(val)
        }

        fn set_to(self, pat: &mut Pattern, property: &Property<Self>) -> bool {
            // Safety: It copy the matrix, so it is safe to use it as a mutable pointer.
            FcTrue
                == unsafe {
                    ffi_dispatch!(
                        LIB,
                        FcPatternAddMatrix,
                        pat.as_mut_ptr(),
                        property.name.as_ptr(),
                        &self.matrix
                    )
                }
        }
    }

    impl<'a> private::MaybeRef<'a> for crate::OwnedCharSet {
        type Returns = &'a crate::CharSet;
    }

    impl<'a> private::Sealed<'a> for crate::OwnedCharSet {
        fn value(pat: &Pattern, name: &Property<Self>, index: usize) -> Option<Self::Returns> {
            unsafe {
                let mut val = std::ptr::null_mut();
                ffi_dispatch!(
                    LIB,
                    FcPatternGetCharSet,
                    pat.as_ptr() as *mut _,
                    name.name.as_ptr(),
                    index as i32,
                    &mut val
                )
                .opt()?;
                if val.is_null() {
                    return None;
                }
                Some(&*(val as *const crate::CharSet))
            }
        }

        fn set_to(self, pat: &mut Pattern, property: &Property<Self>) -> bool {
            // unimplemented!("set &'CharSet to pattern is unsound.");
            FcTrue
                == unsafe {
                    ffi_dispatch!(
                        LIB,
                        FcPatternAddCharSet,
                        pat.as_mut_ptr(),
                        property.name.as_ptr(),
                        self.fcset.as_ptr()
                    )
                }
        }
    }

    impl<'a> private::MaybeRef<'a> for crate::LangSet {
        type Returns = crate::LangSet;
    }

    impl<'a> private::Sealed<'a> for crate::LangSet {
        fn value(pat: &Pattern, name: &Property<Self>, index: usize) -> Option<Self::Returns> {
            let val = unsafe {
                let mut val = std::ptr::null_mut();
                ffi_dispatch!(
                    LIB,
                    FcPatternGetLangSet,
                    pat.as_ptr() as *mut _,
                    name.name.as_ptr(),
                    index as i32,
                    &mut val
                )
                .opt()?;
                ffi_dispatch!(LIB, FcLangSetCopy, val)
            };
            NonNull::new(val).map(|langset| crate::LangSet { langset })
        }

        fn set_to(self, pat: &mut Pattern, property: &Property<Self>) -> bool {
            FcTrue
                == unsafe {
                    ffi_dispatch!(
                        LIB,
                        FcPatternAddLangSet,
                        pat.as_mut_ptr(),
                        property.name.as_ptr(),
                        self.langset.as_ptr()
                    )
                }
        }
    }

    macro_rules! property_decl {
        ($bytes:literal, $name:ident, $vtype:ty, $comment:literal) => {
            /// $comment
            pub const $name: Property<$vtype> = Property {
                name: ::fontconfig_sys::constants::$name,
                val: PhantomData,
            };
        };
    }

    property_decl!(b"family\0", FC_FAMILY, String, "Font family names");
    property_decl!(
        b"familylang\0",
        FC_FAMILYLANG,
        String,
        "Language corresponding to each family name"
    );
    property_decl!(
        b"style\0",
        FC_STYLE,
        String,
        "Font style. Overrides weight and slant"
    );
    property_decl!(
        b"stylelang\0",
        FC_STYLELANG,
        String,
        "Language corresponding to each style name"
    );
    property_decl!(
        b"fullname\0",
        FC_FULLNAME,
        String,
        "Font face full name where different from family and family + style"
    );
    property_decl!(
        b"fullnamelang\0",
        FC_FULLNAMELANG,
        String,
        "Language corresponding to each fullname"
    );
    property_decl!(b"slant\0", FC_SLANT, i32, "Italic, oblique or roman");
    property_decl!(
        b"weight\0",
        FC_WEIGHT,
        i32,
        "Light, medium, demibold, bold or black"
    );
    property_decl!(b"width\0", FC_WIDTH, i32, "Condensed, normal or expanded");
    property_decl!(b"size\0", FC_SIZE, f64, "Point size");
    property_decl!(
        b"aspect\0",
        FC_ASPECT,
        f64,
        "Stretches glyphs horizontally before hinting"
    );
    property_decl!(b"pixelsize\0", FC_PIXEL_SIZE, f64, "Pixel size");
    property_decl!(
        b"spacing\0",
        FC_SPACING,
        i32,
        "Proportional, dual-width, monospace or charcell"
    );
    property_decl!(b"foundry\0", FC_FOUNDRY, String, "Font foundry name");
    property_decl!(
        b"antialias\0",
        FC_ANTIALIAS,
        bool,
        "Whether glyphs can be antialiased"
    );
    property_decl!(
        b"hintstyle\0",
        FC_HINT_STYLE,
        i32,
        "Automatic hinting style"
    );
    property_decl!(
        b"hinting\0",
        FC_HINTING,
        bool,
        "Whether the rasterizer should use hinting"
    );
    property_decl!(
        b"verticallayout\0",
        FC_VERTICAL_LAYOUT,
        bool,
        "Use vertical layout"
    );
    property_decl!(
        b"autohint\0",
        FC_AUTOHINT,
        bool,
        "Use autohinter instead of normal hinter"
    );
    property_decl!(
        b"globaladvance\0",
        FC_GLOBAL_ADVANCE,
        bool,
        "Use font global advance data (deprecated)"
    );
    property_decl!(
        b"file\0",
        FC_FILE,
        String,
        "The filename holding the font relative to the config's sysroot"
    );
    property_decl!(
        b"index\0",
        FC_INDEX,
        i32,
        "The index of the font within the file"
    );
    // property_decl!(
    //     b"ftface\0",
    //     FC_FT_FACE,
    //     FT_Face,
    //     "Use the specified FreeType face object"
    // );
    property_decl!(
        b"rasterizer\0",
        FC_RASTERIZER,
        String,
        "Which rasterizer is in use (deprecated)"
    );
    property_decl!(
        b"outline\0",
        FC_OUTLINE,
        bool,
        "Whether the glyphs are outlines"
    );
    property_decl!(
        b"scalable\0",
        FC_SCALABLE,
        bool,
        "Whether glyphs can be scaled"
    );
    property_decl!(b"dpi\0", FC_DPI, f64, "Target dots per inch");
    property_decl!(
        b"rgba\0",
        FC_RGBA,
        i32,
        "unknown, rgb, bgr, vrgb, vbgr, none - subpixel geometry"
    );
    property_decl!(
        b"scale\0",
        FC_SCALE,
        f64,
        "Scale factor for point->pixel conversions (deprecated)"
    );
    property_decl!(
        b"minspace\0",
        FC_MINSPACE,
        bool,
        "Eliminate leading from line spacing"
    );
    property_decl!(
        b"charset\0",
        FC_CHARSET,
        crate::OwnedCharSet,
        "Unicode chars encoded by the font"
    );
    property_decl!(
        b"lang\0",
        FC_LANG,
        crate::LangSet,
        "Set of RFC-3066-style languages this font supports"
    );
    property_decl!(
        b"fontversion\0",
        FC_FONTVERSION,
        i32,
        "Version number of the font"
    );
    property_decl!(
        b"capability\0",
        FC_CAPABILITY,
        String,
        "List of layout capabilities in the font"
    );
    property_decl!(
        b"fontformat\0",
        FC_FONTFORMAT,
        String,
        "String name of the font format"
    );
    property_decl!(
        b"embolden\0",
        FC_EMBOLDEN,
        bool,
        "Rasterizer should synthetically embolden the font"
    );
    property_decl!(
        b"embeddedbitmap\0",
        FC_EMBEDDED_BITMAP,
        bool,
        "Use the embedded bitmap instead of the outline"
    );
    property_decl!(
        b"decorative\0",
        FC_DECORATIVE,
        bool,
        "Whether the style is a decorative variant"
    );
    property_decl!(b"lcdfilter\0", FC_LCD_FILTER, i32, "Type of LCD filter");
    property_decl!(
        b"namelang\0",
        FC_NAMELANG,
        String,
        "Language name to be used for the default value of familylang, stylelang and fullnamelang"
    );
    property_decl!(
        b"fontfeatures\0",
        FC_FONT_FEATURES,
        String,
        "List of extra feature tags in OpenType to be enabled"
    );
    property_decl!(
        b"prgname\0",
        FC_PRGNAME,
        String,
        "Name of the running program"
    );
    property_decl!(
        b"hash\0",
        FC_HASH,
        String,
        "SHA256 hash value of the font data with \"sha256:\" prefix (deprecated)"
    );
    property_decl!(
        b"postscriptname\0",
        FC_POSTSCRIPT_NAME,
        String,
        "Font name in PostScript"
    );
    property_decl!(
        b"symbol\0",
        FC_SYMBOL,
        bool,
        "Whether font uses MS symbol-font encoding"
    );
    property_decl!(b"color\0", FC_COLOR, bool, "Whether any glyphs have color");
    property_decl!(
        b"fontvariations\0",
        FC_FONT_VARIATIONS,
        String,
        "comma-separated string of axes in variable font"
    );
    property_decl!(
        b"variable\0",
        FC_VARIABLE,
        bool,
        "Whether font is Variable Font"
    );
    property_decl!(
        b"fonthashint\0",
        FC_FONT_HAS_HINT,
        bool,
        "Whether font has hinting"
    );
    property_decl!(b"order\0", FC_ORDER, i32, "Order number of the font");
}

#[cfg(test)]
mod tests {
    use crate::pattern::properties;

    #[test]
    fn test_into_inner() {
        let mut pat = super::OwnedPattern::new();
        pat.add(&properties::FC_FAMILY, "nomospace".to_string());
        let pat = pat.into_inner();
        let pat = pat as *mut super::Pattern;
        assert_eq!(
            unsafe { &*pat }.get(&properties::FC_FAMILY, 0),
            Some("nomospace")
        );
    }

    #[test]
    fn test_get_family() {
        let pat = super::OwnedPattern::new();
        assert!(pat.get(&properties::FC_FAMILY, 0).is_none());
    }

    #[test]
    fn test_get_family_exists() {
        let mut pat = super::OwnedPattern::default();
        pat.add(&properties::FC_FAMILY, "nomospace".to_string());
        assert!(pat.get(&properties::FC_FAMILY, 0).is_some());
    }

    #[test]
    fn test_get_filepath() {
        let mut cfg = crate::FontConfig::default();
        let mut pat = super::OwnedPattern::default();
        pat.add(&properties::FC_FAMILY, "nomospace".to_string());
        cfg.substitute(&mut pat, crate::MatchKind::Pattern);
        let pat = pat.font_match(&mut cfg);
        let file = pat.get(&properties::FC_FILE, 0);
        assert!(file.is_some());
        let dpi = pat.get(&properties::FC_DPI, 0);
        println!("{:?}", dpi);
        if let Some(file) = file {
            assert!(file.starts_with("/usr/share/fonts"));
            assert!(std::path::Path::new(&file).exists(), "{}", file);
        }
    }
}