use crate::error::TextError;
use crate::types::FontMetrics;
use objc2_core_foundation::{CFData, CFRetained, CGFloat};
use objc2_core_text::{CTFont, CTFontManagerCreateFontDescriptorFromData};
use std::ptr;
pub fn create_font_from_bytes(
bytes: &'static [u8],
size_lpx: f32,
) -> Result<(CFRetained<CTFont>, CFRetained<CFData>), TextError> {
let data = CFData::from_bytes(bytes);
let descriptor =
unsafe { CTFontManagerCreateFontDescriptorFromData(&data) }.ok_or_else(|| {
TextError::FontFileLoad(
"CTFontManagerCreateFontDescriptorFromData returned null".into(),
)
})?;
let ct_size_pt = size_lpx as f64;
let ct_font =
unsafe { CTFont::with_font_descriptor(&descriptor, ct_size_pt as CGFloat, ptr::null()) };
Ok((ct_font, data))
}
pub fn extract_metrics(ct_font: &CTFont) -> FontMetrics {
let ascent = unsafe { ct_font.ascent() } as f32;
let descent = unsafe { ct_font.descent() } as f32;
let leading = unsafe { ct_font.leading() } as f32;
let x_height = unsafe { ct_font.x_height() } as f32;
let cap_height = unsafe { ct_font.cap_height() } as f32;
let units_per_em = unsafe { ct_font.units_per_em() };
FontMetrics {
ascent_lpx: ascent,
descent_lpx: -descent, line_gap_lpx: leading,
x_height_lpx: x_height,
cap_height_lpx: cap_height,
units_per_em,
}
}