use crate::error::Result; use crate::x::{ Connection, HasConnection, ConnectionExt, Display, HasDisplay }; use crate::x::text::Span; use std::cell::OnceCell; use std::ffi::CString; use std::sync::Arc; use x11::xft::{ XftCharExists, XftFontOpenName }; pub struct Font { display: Arc, font_state: *mut x11::xft::XftFont, metrics: OnceCell<(u16,u16)>, } impl PartialEq for Font { fn eq(&self, other: &Font) -> bool { self.display == other.display && self.font_state == other.font_state } } impl HasConnection for Font { fn connection(&self) -> &Connection { self.display.connection() } } impl HasDisplay for Font { fn display(&self) -> &Arc { &self.display } } impl Font { pub fn new(display: Arc, name: &str) -> Result> { let xlib_display = display.connection().get_xlib_display(); let screen_index = display.screen_index(); let name = CString::new(name).unwrap(); let font_state = unsafe { XftFontOpenName(xlib_display, screen_index, name.as_ptr().cast()) }; let font = Arc::new(Font { display, font_state, metrics: OnceCell::new(), }); let x_height = font.measure_character_heights("acemnorsuvwxz")?; let ascent = font.text_span("bdfhiklt")?.draw_size().height; let descent = font.text_span("gpqy")?.draw_size().height - x_height; let _ = font.metrics.set((ascent, descent)); Ok(font) } pub fn font_state(&self) -> *mut x11::xft::XftFont { self.font_state } pub fn ascent(self: &Arc) -> u16 { let (ascent, _) = self.metrics.get().unwrap(); *ascent } pub fn descent(self: &Arc) -> u16 { let (_, descent) = self.metrics.get().unwrap(); *descent } pub fn text_span(self: &Arc, text: &str) -> Result { Span::new(Arc::clone(self), text) } fn measure_character_heights(self: &Arc, repertoire: &str) -> Result { let mut max_height = 0; for c in repertoire.chars() { let span = self.text_span(&format!("{}", c))?; max_height = max_height.max(span.draw_size().height); } Ok(max_height) } pub fn check_char_exists(self: &Arc, codepoint: u32) -> Result { let xlib_display = self.display.connection().get_xlib_display(); let result = unsafe { XftCharExists(xlib_display, self.font_state, codepoint) }; Ok(result != 0) } }