1#![deny(clippy::undocumented_unsafe_blocks)]
8#![allow(clippy::unnecessary_cast)]
9
10use std::ffi::CStr;
11use std::marker::PhantomData;
12use std::num::NonZeroU32;
13use std::ops::BitOr;
14use std::ptr::NonNull;
15use std::sync::{Mutex, OnceLock};
16use std::{ptr, slice};
17
18mod sys;
19
20mod linkage {
23 #[allow(unused_imports)]
24 use tectonic_bridge_flate as clippyrenamehack1;
25 #[allow(unused_imports)]
26 use tectonic_bridge_png as clippyrenamehack2;
27}
28
29pub use sys::FT_BBox as BBox;
30pub use sys::FT_Fixed as Fixed;
31pub use sys::FT_Glyph_BBox_Mode as BBoxMode;
32pub use sys::FT_Glyph_Format as GlyphFormat;
33pub use sys::FT_Glyph_Metrics as GlyphMetrics;
34pub use sys::FT_Kerning_Mode as KerningMode;
35pub use sys::FT_Outline as Outline;
36pub use sys::FT_Sfnt_Tag as SfntTag;
37pub use sys::FT_Vector as Vector;
38
39pub mod tables {
41 pub use crate::sys::TT_Header as Header;
42 pub use crate::sys::TT_Postscript as Postscript;
43 pub use crate::sys::TT_OS2 as Os2;
44}
45
46pub(crate) struct SyncPtr<T>(*mut T);
47
48unsafe impl<T> Send for SyncPtr<T> {}
50unsafe impl<T> Sync for SyncPtr<T> {}
52
53static FREE_TYPE_LIBRARY: OnceLock<SyncPtr<sys::FT_LibraryRec>> = OnceLock::new();
56static FACE_MUTEX: Mutex<()> = Mutex::new(());
57
58fn ft_lib() -> sys::FT_Library {
59 FREE_TYPE_LIBRARY
60 .get_or_init(|| {
61 let mut lib = ptr::null_mut();
62 let error = unsafe { sys::FT_Init_FreeType(&mut lib) };
64 if error != 0 {
65 panic!("FreeType initialization failed, error {error}");
66 }
67 SyncPtr(lib)
68 })
69 .0
70}
71
72pub fn init() {
74 ft_lib();
75}
76
77#[derive(Copy, Clone, Debug)]
79pub enum TableTag {
80 Sfnt(SfntTag),
82 Other(u32),
84}
85
86impl TableTag {
87 fn as_u32(self) -> u32 {
88 match self {
89 TableTag::Sfnt(tag) => tag as u32,
90 TableTag::Other(other) => other,
91 }
92 }
93}
94
95#[derive(Copy, Clone, Debug)]
98pub struct LoadFlags(i32);
99
100impl LoadFlags {
101 pub const DEFAULT: LoadFlags = LoadFlags(0);
103 pub const NO_SCALE: LoadFlags = LoadFlags(sys::FT_LOAD_NO_SCALE);
105 pub const VERTICAL_LAYOUT: LoadFlags = LoadFlags(sys::FT_LOAD_VERTICAL_LAYOUT);
107
108 fn as_i32(self) -> i32 {
109 self.0
110 }
111}
112
113impl BitOr for LoadFlags {
114 type Output = LoadFlags;
115
116 fn bitor(self, rhs: Self) -> Self::Output {
117 LoadFlags(self.0 | rhs.0)
118 }
119}
120
121#[derive(Copy, Clone, Debug, PartialEq)]
123pub struct PlatformId(u16);
124
125impl PlatformId {
126 pub const APPLE_UNICODE: PlatformId = PlatformId(sys::TT_PLATFORM_APPLE_UNICODE as u16);
128 pub const MACINTOSH: PlatformId = PlatformId(sys::TT_PLATFORM_MACINTOSH as u16);
130 pub const MICROSOFT: PlatformId = PlatformId(sys::TT_PLATFORM_MICROSOFT as u16);
132}
133
134#[derive(Copy, Clone, Debug, PartialEq)]
136pub struct EncodingId(u16);
137
138impl EncodingId {
139 pub const MAC_ROMAN: EncodingId = EncodingId(sys::TT_MAC_ID_ROMAN as u16);
141 pub const WIN_UNICODE: EncodingId = EncodingId(sys::TT_MS_ID_UNICODE_CS as u16);
143}
144
145#[derive(Copy, Clone, Debug, PartialEq)]
147pub struct LanguageId(u16);
148
149impl LanguageId {
150 pub const MAC_ENGLISH: LanguageId = LanguageId(sys::TT_MAC_LANGID_ENGLISH as u16);
152
153 pub const WIN_ENGLISH_US: LanguageId =
155 LanguageId(sys::TT_MS_LANGID_ENGLISH_UNITED_STATES as u16);
156}
157
158#[derive(Debug)]
160pub struct Error(sys::FT_Error);
161
162impl Error {
163 fn or_else<T>(err: sys::FT_Error, f: impl FnOnce() -> T) -> Result<T, Error> {
164 if err == 0 {
165 Ok(f())
166 } else {
167 Err(Error(err))
168 }
169 }
170
171 pub fn message(&self) -> Option<&'static str> {
176 let str = unsafe { sys::FT_Error_String(self.0) };
178 if str.is_null() {
179 None
180 } else {
181 let str = unsafe { CStr::from_ptr(str) };
183 str::from_utf8(str.to_bytes()).ok()
184 }
185 }
186
187 pub fn code(&self) -> sys::FT_Error {
191 self.0
192 }
193}
194
195#[derive(Debug)]
197#[non_exhaustive]
198pub struct SfntName<'a> {
199 pub platform_id: PlatformId,
201 pub encoding_id: EncodingId,
203 pub language_id: LanguageId,
205 pub name_id: u16,
207 pub string: &'a [u8],
209}
210
211impl From<sys::FT_SfntName> for SfntName<'_> {
212 fn from(value: sys::FT_SfntName) -> Self {
213 SfntName {
214 platform_id: PlatformId(value.platform_id as u16),
215 encoding_id: EncodingId(value.encoding_id as u16),
216 language_id: LanguageId(value.language_id as u16),
217 name_id: value.name_id as u16,
218 string: if !value.string.is_null() {
219 unsafe { slice::from_raw_parts(value.string, value.string_len as usize) }
222 } else {
223 &[]
224 },
225 }
226 }
227}
228
229pub struct Glyph(NonNull<sys::FT_GlyphRec>);
231
232impl Glyph {
233 pub fn get_cbox(&self, mode: BBoxMode) -> BBox {
236 let mut ft_bbox = BBox::default();
237 unsafe { sys::FT_Glyph_Get_CBox(self.0.as_ptr(), mode, &mut ft_bbox) };
239 ft_bbox
240 }
241}
242
243impl Drop for Glyph {
244 fn drop(&mut self) {
245 unsafe { sys::FT_Done_Glyph(self.0.as_ptr()) }
247 }
248}
249
250pub struct GlyphSlot<'a>(
252 NonNull<sys::FT_GlyphSlotRec>,
253 PhantomData<&'a sys::FT_GlyphSlotRec>,
254);
255
256impl GlyphSlot<'_> {
257 fn as_ref(&self) -> &sys::FT_GlyphSlotRec {
258 unsafe { self.0.as_ref() }
261 }
262
263 pub fn get_glyph(&self) -> Result<Glyph, Error> {
265 let mut ptr = ptr::null_mut();
266 let err = unsafe { sys::FT_Get_Glyph(self.0.as_ptr(), &mut ptr) };
268 Error::or_else(err, || Glyph(NonNull::new(ptr).unwrap()))
269 }
270
271 pub fn metrics(&self) -> &GlyphMetrics {
273 &self.as_ref().metrics
274 }
275
276 pub fn format(&self) -> GlyphFormat {
278 self.as_ref().format
279 }
280
281 pub fn outline(&self) -> Option<&Outline> {
283 if self.format() == GlyphFormat::Outline {
284 Some(&self.as_ref().outline)
285 } else {
286 None
287 }
288 }
289}
290
291pub unsafe trait Table {
297 fn tag() -> SfntTag;
299}
300
301unsafe impl Table for tables::Os2 {
303 fn tag() -> SfntTag {
304 SfntTag::Os2
305 }
306}
307
308unsafe impl Table for tables::Header {
310 fn tag() -> SfntTag {
311 SfntTag::Head
312 }
313}
314
315unsafe impl Table for tables::Postscript {
317 fn tag() -> SfntTag {
318 SfntTag::Post
319 }
320}
321
322pub struct Face(NonNull<sys::FT_FaceRec>, Vec<Vec<u8>>);
324
325impl Face {
326 pub fn new(path: &CStr, index: usize) -> Result<Face, Error> {
329 let _l = FACE_MUTEX.lock();
330 let mut raw_face = ptr::null_mut();
331 let err = unsafe {
334 sys::FT_New_Face(
335 ft_lib(),
336 path.as_ptr(),
337 index as libc::c_long,
338 &mut raw_face,
339 )
340 };
341 drop(_l);
342 Error::or_else(err, || Face(NonNull::new(raw_face).unwrap(), Vec::new()))
343 }
344
345 pub fn new_memory(mut data: Vec<u8>, index: usize) -> Result<Face, Error> {
348 let _l = FACE_MUTEX.lock();
349 let mut raw_face = ptr::null_mut();
350 let err = unsafe {
353 sys::FT_New_Memory_Face(
354 ft_lib(),
355 data.as_mut_ptr().cast(),
356 data.len() as libc::c_long,
357 index as libc::c_long,
358 &mut raw_face,
359 )
360 };
361 drop(_l);
362 Error::or_else(err, || Face(NonNull::new(raw_face).unwrap(), vec![data]))
363 }
364
365 fn inner(&self) -> &sys::FT_FaceRec {
366 unsafe { self.0.as_ref() }
369 }
370
371 pub fn is_scalable(&self) -> bool {
373 self.inner().face_flags & sys::FT_FACE_FLAG_SCALABLE != 0
374 }
375
376 pub fn is_sfnt(&self) -> bool {
378 self.inner().face_flags & sys::FT_FACE_FLAG_SFNT != 0
379 }
380
381 pub fn has_glyph_names(&self) -> bool {
383 self.inner().face_flags & sys::FT_FACE_FLAG_GLYPH_NAMES != 0
384 }
385
386 pub fn units_per_em(&self) -> u16 {
388 self.inner().units_per_EM as u16
389 }
390
391 pub fn ascender(&self) -> i16 {
393 self.inner().ascender as i16
394 }
395
396 pub fn descender(&self) -> i16 {
398 self.inner().descender as i16
399 }
400
401 pub fn num_glyphs(&self) -> usize {
403 self.inner().num_glyphs as usize
404 }
405
406 pub fn num_faces(&self) -> usize {
408 self.inner().num_faces as usize
409 }
410
411 fn glyph(&self) -> GlyphSlot<'_> {
412 GlyphSlot(NonNull::new(self.inner().glyph).unwrap(), PhantomData)
413 }
414
415 pub fn get_advance(&self, index: u32, flags: LoadFlags) -> Result<i64, Error> {
418 let mut advance = 0;
419 let err = unsafe {
421 sys::FT_Get_Advance(
422 self.0.as_ptr(),
423 index as libc::c_uint,
424 flags.as_i32(),
425 &mut advance,
426 )
427 };
428 Error::or_else(err, || advance as i64)
429 }
430
431 pub fn get_first_char(&self) -> (u32, u32) {
433 let mut index = 0;
434 let code = unsafe { sys::FT_Get_First_Char(self.0.as_ptr(), &mut index) };
436 (code as u32, index as u32)
437 }
438
439 pub fn get_next_char(&self, char: u32) -> (u32, u32) {
442 let mut index = 0;
443 let code =
445 unsafe { sys::FT_Get_Next_Char(self.0.as_ptr(), char as libc::c_ulong, &mut index) };
446 (code as u32, index as u32)
447 }
448
449 pub fn get_char_index(&self, char: u32) -> Option<NonZeroU32> {
451 NonZeroU32::new(unsafe { sys::FT_Get_Char_Index(self.0.as_ptr(), char as libc::c_ulong) })
453 }
454
455 pub fn get_char_variant_index(&self, char: u32, variant: u32) -> Option<NonZeroU32> {
458 NonZeroU32::new(unsafe {
460 sys::FT_Face_GetCharVariantIndex(
461 self.0.as_ptr(),
462 char as libc::c_ulong,
463 variant as libc::c_ulong,
464 )
465 })
466 }
467
468 pub fn get_kerning(&self, left: u32, right: u32, mode: KerningMode) -> Result<Vector, Error> {
472 let mut vector = Vector::default();
473 let err = unsafe { sys::FT_Get_Kerning(self.0.as_ptr(), left, right, mode, &mut vector) };
475 Error::or_else(err, || vector)
476 }
477
478 pub fn get_glyph_name<'a>(&self, index: u32, buf: &'a mut [u8]) -> Result<&'a CStr, Error> {
482 let err = unsafe {
484 sys::FT_Get_Glyph_Name(
485 self.0.as_ptr(),
486 index as libc::c_uint,
487 buf.as_mut_ptr().cast(),
488 buf.len() as libc::c_uint,
489 )
490 };
491 Error::or_else(err, move || CStr::from_bytes_until_nul(buf).unwrap())
492 }
493
494 pub fn get_name_index(&self, name: &CStr) -> Option<NonZeroU32> {
498 NonZeroU32::new(unsafe { sys::FT_Get_Name_Index(self.0.as_ptr(), name.as_ptr()) as u32 })
501 }
502
503 pub fn get_postscript_name(&self) -> Option<&CStr> {
505 let ptr = unsafe { sys::FT_Get_Postscript_Name(self.0.as_ptr()) };
507 if ptr.is_null() {
508 None
509 } else {
510 Some(unsafe { CStr::from_ptr(ptr) })
513 }
514 }
515
516 pub fn get_sfnt_name_count(&self) -> u32 {
518 unsafe { sys::FT_Get_Sfnt_Name_Count(self.0.as_ptr()) as u32 }
520 }
521
522 pub fn get_sfnt_name(&self, idx: u32) -> Result<SfntName<'_>, Error> {
524 let mut name = sys::FT_SfntName::default();
525 let err = unsafe { sys::FT_Get_Sfnt_Name(self.0.as_ptr(), idx as libc::c_uint, &mut name) };
528 Error::or_else(err, || SfntName::from(name))
529 }
530
531 pub fn load_glyph(&mut self, index: u32, flags: LoadFlags) -> Result<GlyphSlot<'_>, Error> {
534 let err =
536 unsafe { sys::FT_Load_Glyph(self.0.as_ptr(), index as libc::c_uint, flags.as_i32()) };
537 match Error::or_else(err, || ()) {
538 Ok(_) => Ok(self.glyph()),
539 Err(e) => Err(e),
540 }
541 }
542
543 pub fn get_sfnt_table_dyn(&self, tag: SfntTag) -> Option<NonNull<()>> {
546 NonNull::new(unsafe { sys::FT_Get_Sfnt_Table(self.0.as_ptr(), tag) })
548 }
549
550 pub fn get_sfnt_table<T: Table>(&self) -> Option<&T> {
553 let ptr = unsafe { sys::FT_Get_Sfnt_Table(self.0.as_ptr(), T::tag()) };
555 unsafe { ptr.cast::<T>().as_ref() }
558 }
559
560 pub fn load_sfnt_table(&self, tag: TableTag) -> Result<Vec<u8>, Error> {
564 let mut len = 0;
565 let err = unsafe {
567 sys::FT_Load_Sfnt_Table(
568 self.0.as_ptr(),
569 tag.as_u32() as libc::c_ulong,
570 0,
571 ptr::null_mut(),
572 &mut len,
573 )
574 };
575 Error::or_else(err, || ())?;
576
577 let mut buf = vec![0u8; len as usize];
578
579 let err = unsafe {
583 sys::FT_Load_Sfnt_Table(
584 self.0.as_ptr(),
585 tag.as_u32() as libc::c_ulong,
586 0,
587 buf.as_mut_ptr().cast(),
588 &mut len,
589 )
590 };
591
592 Error::or_else(err, || buf)
593 }
594
595 pub fn attach_stream_mem(&mut self, mut stream: Vec<u8>) -> Result<(), Error> {
598 let mut oa = sys::FT_Open_Args::default();
599 oa.flags |= sys::FT_OPEN_MEMORY;
600 oa.memory_base = stream.as_mut_ptr().cast();
601 oa.memory_size = stream.len() as libc::c_long;
602 self.1.push(stream);
603 let err = unsafe { sys::FT_Attach_Stream(self.0.as_ptr(), &mut oa) };
607 Error::or_else(err, || ())
608 }
609}
610
611impl Drop for Face {
612 fn drop(&mut self) {
613 let _l = FACE_MUTEX.lock();
614 unsafe { sys::FT_Done_Face(self.0.as_ptr()) };
618 drop(_l);
619 }
620}
621
622unsafe impl Send for Face {}
625unsafe impl Sync for Face {}
628
629#[cfg(test)]
630mod tests {
631 use super::*;
632 use std::ffi::CString;
633 use std::fs;
634 use std::path::{Path, PathBuf};
635
636 fn assets_dir() -> PathBuf {
637 Path::new(env!("CARGO_MANIFEST_DIR"))
638 .join("../../tests/assets")
639 .canonicalize()
640 .unwrap()
641 }
642
643 fn get_face_data() -> Vec<u8> {
644 let roman = assets_dir().join("lmroman12-regular.otf");
645 fs::read(roman).unwrap()
646 }
647
648 fn get_face_file() -> Face {
649 let roman = assets_dir().join("lmroman12-regular.otf");
650 let roman_path = CString::new(roman.to_str().unwrap()).unwrap();
651
652 Face::new(&roman_path, 0).unwrap()
653 }
654
655 fn get_face_mem() -> Face {
656 let roman_data = get_face_data();
657
658 Face::new_memory(roman_data, 0).unwrap()
659 }
660
661 fn test_faces() -> Vec<Face> {
662 vec![get_face_file(), get_face_mem()]
663 }
664
665 #[test]
666 fn test_invalid_face() {
667 assert!(Face::new(c"/bad/path", 0).is_err());
668 assert!(Face::new_memory(vec![], 0).is_err());
669 }
670
671 #[test]
672 fn test_properties() {
673 for face in test_faces() {
674 assert!(face.is_scalable());
675 assert!(face.is_sfnt());
676 assert!(face.has_glyph_names());
677 assert_eq!(face.units_per_em(), 1000);
678 assert_eq!(face.ascender(), 1127);
679 assert_eq!(face.descender(), -280);
680 assert_eq!(face.num_glyphs(), 821);
681 assert_eq!(face.num_faces(), 1);
682 }
683 }
684
685 #[test]
686 fn test_roman_name() {
687 for face in test_faces() {
688 assert_eq!(face.get_sfnt_name_count(), 21);
689
690 let mac_name = face.get_sfnt_name(1).unwrap();
691
692 let name_16 = "Latin Modern Roman"
693 .encode_utf16()
694 .flat_map(|val| val.to_be_bytes())
695 .collect::<Vec<u8>>();
696
697 assert_eq!(mac_name.platform_id, PlatformId::MACINTOSH);
698 assert_eq!(mac_name.encoding_id, EncodingId::MAC_ROMAN);
699 assert_eq!(mac_name.language_id, LanguageId::MAC_ENGLISH);
700 assert_eq!(mac_name.string, b"Latin Modern Roman");
701
702 let win_name = face.get_sfnt_name(18).unwrap();
703 assert_eq!(win_name.platform_id, PlatformId::MICROSOFT);
704 assert_eq!(win_name.encoding_id, EncodingId::WIN_UNICODE);
705 assert_eq!(win_name.language_id, LanguageId::WIN_ENGLISH_US);
706 assert_eq!(win_name.string, &name_16);
707 }
708 }
709
710 #[test]
711 fn test_postscript_name() {
712 for face in test_faces() {
713 let name = face.get_postscript_name().unwrap();
714 assert_eq!(name.to_bytes(), b"LMRoman12-Regular");
715 }
716 }
717
718 #[test]
719 fn test_get_tables() {
720 for face in test_faces() {
721 let dyn_table = face.get_sfnt_table_dyn(SfntTag::Head).unwrap();
722 let table = face.get_sfnt_table::<tables::Header>().unwrap();
723
724 assert!(ptr::eq(table, dyn_table.as_ptr().cast_const().cast()));
725 assert_eq!(table.Units_Per_Em, face.units_per_em());
726
727 let dyn_table = face.get_sfnt_table_dyn(SfntTag::Os2).unwrap();
728 let table = face.get_sfnt_table::<tables::Os2>().unwrap();
729 assert!(ptr::eq(table, dyn_table.as_ptr().cast_const().cast()));
730
731 let dyn_table = face.get_sfnt_table_dyn(SfntTag::Post).unwrap();
732 let table = face.get_sfnt_table::<tables::Postscript>().unwrap();
733 assert!(ptr::eq(table, dyn_table.as_ptr().cast_const().cast()));
734 }
735 }
736
737 #[test]
738 fn test_load_tables() {
739 let data = get_face_data();
740 for face in test_faces() {
741 assert_eq!(
742 data,
743 face.load_sfnt_table(TableTag::Sfnt(SfntTag::Head)).unwrap()
744 );
745 face.load_sfnt_table(TableTag::Other(u32::MAX)).unwrap_err();
746 }
747 }
748
749 #[test]
750 fn test_get_char_index() {
751 for face in test_faces() {
752 face.get_char_index('!' as u32).unwrap();
753 assert!(face.get_char_index('∀' as u32).is_none());
754 }
755 }
756
757 #[test]
758 fn test_attach_stream() {
759 for mut face in test_faces() {
760 face.attach_stream_mem(b"Hello World!".to_vec())
761 .unwrap_err();
762 }
763 }
764
765 #[test]
766 fn test_bad_glyph() {
767 const BAD_IDX: u32 = 10000;
768 for mut face in test_faces() {
769 assert!(face.get_name_index(c"bad_name").is_none());
770 face.get_advance(BAD_IDX, LoadFlags::DEFAULT).unwrap_err();
771 face.get_glyph_name(BAD_IDX, &mut []).unwrap_err();
772 assert!(face.load_glyph(BAD_IDX, LoadFlags::DEFAULT).is_err());
773 }
774 }
775
776 #[test]
777 fn test_first_glyph() {
778 let mut buf = vec![0; 32];
779
780 for face in test_faces() {
781 let (c, idx) = face.get_first_char();
782 assert_eq!(c, ' ' as u32);
783
784 let advance = face.get_advance(idx, LoadFlags::NO_SCALE).unwrap();
785 assert_eq!(advance, 326);
786 assert_eq!(face.get_glyph_name(idx, &mut buf).unwrap(), c"space");
787 assert_eq!(face.get_char_index(' ' as u32).unwrap().get(), idx);
788 assert_eq!(face.get_name_index(c"space").unwrap().get(), idx);
789
790 let (c2, _) = face.get_next_char(c);
791 assert_eq!(c2, '!' as u32);
792
793 assert_eq!(face.get_char_variant_index(c, 0xFE00), None);
795 }
796 }
797
798 #[test]
799 fn test_kerning() {
800 for face in test_faces() {
801 let exc_idx = face.get_char_index('!' as u32).unwrap().get();
802 let at_idx = face.get_char_index('@' as u32).unwrap().get();
803
804 let kern = face
805 .get_kerning(exc_idx, at_idx, KerningMode::Default)
806 .unwrap();
807 assert_eq!(kern, Vector { x: 0, y: 0 });
809 }
810 }
811
812 #[test]
813 fn test_glyph_load() {
814 for mut face in test_faces() {
815 let idx = face.get_char_index(b'@' as u32).unwrap().get();
816
817 let slot = face.load_glyph(idx, LoadFlags::NO_SCALE).unwrap();
818
819 assert_eq!(slot.format(), GlyphFormat::Outline);
820 assert_eq!(slot.metrics().height, 714);
821 assert_eq!(slot.metrics().width, 653);
822
823 let outline = slot.outline().unwrap();
824 assert_eq!(outline.points().len(), 82);
825 assert_eq!(outline.contours().len(), 2);
826
827 let glyph = slot.get_glyph().unwrap();
828
829 assert_eq!(
830 glyph.get_cbox(BBoxMode::Unscaled),
831 BBox {
832 x_min: 54,
833 x_max: 707,
834 y_min: -10,
835 y_max: 704
836 }
837 );
838 }
839 }
840}