From c8e87126b038a5f70b7c5a0eac018c0d12486f43 Mon Sep 17 00:00:00 2001 From: Irene Knapp Date: Fri, 13 Nov 2026 22:08:48 -0700 Subject: reverse-engineer font ascent and descent, and rely on them we now do the baseline computation "properly", during setup, rather than during text rendering. this allows us to be consistent about it; prior to this, the two spans of text we draw would often wind up with different baselines. Force-Push: yes Change-Id: Ic2f34c816fc0767d6e54c5415beb516f99cd3069 --- src/x/font.rs | 42 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 4 deletions(-) (limited to 'src/x/font.rs') diff --git a/src/x/font.rs b/src/x/font.rs index dc84199..8d49e98 100644 --- a/src/x/font.rs +++ b/src/x/font.rs @@ -1,6 +1,7 @@ use crate::x::*; use crate::geometry::{ Point, Offset, Size }; +use std::cell::OnceCell; use std::ffi::CString; use std::sync::Arc; @@ -11,6 +12,7 @@ use x11::xrender::XGlyphInfo; pub struct Font { display: Arc, font_state: *mut x11::xft::XftFont, + metrics: OnceCell<(u16,u16)>, } pub struct TextSpan { @@ -21,7 +23,7 @@ pub struct TextSpan { impl Font { - pub fn new(display: Arc, name: &str) -> xcb::Result { + pub fn new(display: Arc, name: &str) -> xcb::Result> { let xlib_display = display.connection().get_xlib_display(); let screen_index = display.screen_index(); @@ -30,12 +32,44 @@ impl Font { XftFontOpenName(xlib_display, screen_index, name.as_ptr().cast()) }; - Ok(Font { display, font_state }) + 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 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) -> xcb::Result { TextSpan::new(Arc::clone(self), text) } + + fn measure_character_heights(self: &Arc, repertoire: &str) + -> xcb::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) + } } @@ -147,8 +181,8 @@ impl TextSpan { * immediately after it would start from. * * This is rounded in some fashion, most likely to the nearest whole - * pixel, which causes it to often be smaller than logical_size(). See - * the note on draw() for some highly relevant philosophy. + * pixel, which causes it to often be smaller than draw_size(). See the note + * on draw() for some highly relevant philosophy. */ pub fn logical_offset(&self) -> Offset { Offset { -- cgit 1.4.1