diff options
| author | Irene Knapp <ireneista@irenes.space> | 2026-11-22 23:18:13 -0700 |
|---|---|---|
| committer | Irene Knapp <ireneista@irenes.space> | 2026-11-22 23:18:13 -0700 |
| commit | b7319af1ed9e5dc3c29d05d6f5de9f325fa64191 (patch) | |
| tree | d3ce5e3b0f6835e4e8179ab8caf2921c7e4ad295 /src/x/text | |
| parent | 1b24796bb97f64ab2771a884632d4b6f64d86f0f (diff) | |
new subdirectory src/x/text/
Force-Push: yes Change-Id: I1c428e1f7b42de263534965422dffe007300082c
Diffstat (limited to 'src/x/text')
| -rw-r--r-- | src/x/text/font.rs | 106 | ||||
| -rw-r--r-- | src/x/text/font_context.rs | 46 | ||||
| -rw-r--r-- | src/x/text/font_list.rs | 62 | ||||
| -rw-r--r-- | src/x/text/line.rs | 96 | ||||
| -rw-r--r-- | src/x/text/span.rs | 176 |
5 files changed, 486 insertions, 0 deletions
diff --git a/src/x/text/font.rs b/src/x/text/font.rs new file mode 100644 index 0000000..fe3429c --- /dev/null +++ b/src/x/text/font.rs @@ -0,0 +1,106 @@ +use crate::error::Result; +use crate::layout::Parcel; +use crate::geometry::{ Alignment, Point, Offset, Size }; +use crate::x::*; +use crate::x::text::Span; + +use std::cell::OnceCell; +use std::ffi::CString; +use std::sync::Arc; + +use x11::xft::{ + XftCharExists, XftDrawStringUtf8, XftTextExtentsUtf8, XftFontOpenName +}; +use x11::xrender::XGlyphInfo; + + +pub struct Font { + display: Arc<Display>, + 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<Display> { &self.display } +} + +impl Font { + pub fn new(display: Arc<Display>, name: &str) -> Result<Arc<Font>> { + 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<Self>) -> u16 { + let (ascent, _) = self.metrics.get().unwrap(); + + *ascent + } + + pub fn descent(self: &Arc<Self>) -> u16 { + let (_, descent) = self.metrics.get().unwrap(); + + *descent + } + + pub fn text_span(self: &Arc<Self>, text: &str) -> Result<Span> { + Span::new(Arc::clone(self), text) + } + + fn measure_character_heights(self: &Arc<Self>, repertoire: &str) + -> Result<u16> + { + 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<Self>, codepoint: u32) -> Result<bool> { + let xlib_display = self.display.connection().get_xlib_display(); + + let result = unsafe { + XftCharExists(xlib_display, + self.font_state, + codepoint) + }; + + Ok(result != 0) + } +} + diff --git a/src/x/text/font_context.rs b/src/x/text/font_context.rs new file mode 100644 index 0000000..56eb08e --- /dev/null +++ b/src/x/text/font_context.rs @@ -0,0 +1,46 @@ +use crate::x::*; + +use std::sync::Arc; + +use x11::xft::{ XftDraw, XftDrawCreate, XftDrawDestroy }; +use xcb::{ Xid }; + + +pub struct FontGraphicContext { + _display: Arc<Display>, + context_state: *mut XftDraw, +} + + +impl FontGraphicContext { + pub fn new(window: &Window) -> xcb::Result<FontGraphicContext> { + let display = Arc::clone(window.display()); + let xlib_display = display.connection().get_xlib_display(); + + let x_visual = unsafe { + x11::xlib::XDefaultVisual(xlib_display, display.screen_index()) + }; + + let colormap = window.screen().default_colormap(); + + let context_state = unsafe { + XftDrawCreate(xlib_display, + window.window_id().resource_id() as u64, + x_visual, + colormap.resource_id() as u64) + }; + + Ok(FontGraphicContext { _display: display, context_state }) + } + + pub fn get_xft_draw(&self) -> *mut XftDraw { + self.context_state + } +} + +impl Drop for FontGraphicContext { + fn drop(&mut self) { + unsafe { XftDrawDestroy(self.context_state) }; + } +} + diff --git a/src/x/text/font_list.rs b/src/x/text/font_list.rs new file mode 100644 index 0000000..1ef3499 --- /dev/null +++ b/src/x/text/font_list.rs @@ -0,0 +1,62 @@ +use crate::error::{ Error, Result }; +use crate::x::Display; +use crate::x::text::Font; + +use std::sync::Arc; + + +pub struct FontList { + display: Arc<Display>, + fonts: Vec<Arc<Font>>, +} + +impl FontList { + pub fn new(display: Arc<Display>) -> Result<FontList> { + let fonts = Vec::new(); + + Ok(FontList { display, fonts }) + } + + pub fn append(&mut self, name: &str) -> Result<()> { + let font = Font::new(Arc::clone(&self.display), name)?; + + self.append_font(font); + + Ok(()) + } + + pub fn append_font(&mut self, font: Arc<Font>) { + self.fonts.push(font); + } + + /* The primary font is the first one in the list. Ascribing meaning to this + * is up to the caller. + */ + pub fn primary_font(&self) -> Result<Arc<Font>> { + if self.fonts.len() > 0 { + return Ok(Arc::clone(&self.fonts[0])); + } + + Err(Error::custom("There are no fonts in the list.")) + } + + /* This accepts a Unicode codepoint, and returns a font containing it. At + * least, that's the hope. The xft docs are thin on the topic of what + * encoding the codepoint is in, and it's entirely possible something weird + * happens in fonts for which ISO-10646 is not an explicitly provided + * encoding, or for which it's provided in an unusual way. + * + * If the character isn't found in any font, this returns the primary font, + * on the assumption that's the one whose missing-glyph glyph we want. + */ + pub fn find_codepoint(&self, codepoint: u32) -> Result<Arc<Font>> { + for font in &self.fonts { + if font.check_char_exists(codepoint)? { + return Ok(Arc::clone(&font)); + } + } + + self.primary_font() + } +} + diff --git a/src/x/text/line.rs b/src/x/text/line.rs new file mode 100644 index 0000000..5e328ed --- /dev/null +++ b/src/x/text/line.rs @@ -0,0 +1,96 @@ +use crate::error::Result; +use crate::geometry::{ Alignment, Point }; +use crate::layout::Parcel; +use crate::x::Color; +use crate::x::text::{ Font, FontGraphicContext, FontList, Span }; + +use std::sync::{ Arc, Mutex }; + + +pub struct Line { + fonts: Arc<Mutex<FontList>>, + spans: Vec<Span>, +} + + +impl Line { + pub fn new(fonts: Arc<Mutex<FontList>>) -> Result<Line> { + let spans = Vec::new(); + + Ok(Line { fonts, spans }) + } + + pub fn append_text(&mut self, text: &str) -> Result<()> { + let mut current_span_font: Option<Arc<Font>> = None; + let mut current_span_text = String::new(); + + for char in text.chars() { + let codepoint = char as u32; + + let new_font = &self.fonts.lock()?.find_codepoint(codepoint)?; + if let Some(old_font) = ¤t_span_font { + if old_font != new_font { + let span = old_font.text_span(¤t_span_text)?; + self.spans.push(span); + + current_span_font = Some(Arc::clone(new_font)); + current_span_text = String::new(); + } + } else { + current_span_font = Some(Arc::clone(new_font)); + } + + current_span_text.push(char); + } + + if let Some(font) = current_span_font + && !current_span_text.is_empty() + { + let span = font.text_span(¤t_span_text)?; + self.spans.push(span); + } + + Ok(()) + } + + pub fn spans(&self) -> impl Iterator<Item=&Span> + DoubleEndedIterator { + self.spans.iter() + } + + pub fn layout_and_draw(&self, open_parcel: &mut Parcel, + alignment: Alignment, context: &FontGraphicContext, + color: &Color, baseline_position: i16) + -> Result<()> + { + let mut location = Point::<i32>::zero(); + location.y += baseline_position as i32; + + match alignment { + Alignment::Left => { + location.x += open_parcel.left as i32; + } + Alignment::Right => { + location.x += open_parcel.right as i32; + } + } + + /* A reversed iterator is a different type, so we need two of this loop. */ + match alignment { + Alignment::Left => { + for span in self.spans() { + span.layout_and_draw(open_parcel, &mut location, + alignment, context, color)?; + } + } + Alignment::Right => { + for span in self.spans().rev() { + span.layout_and_draw(open_parcel, &mut location, + alignment, context, color)?; + } + } + } + + Ok(()) + } +} + diff --git a/src/x/text/span.rs b/src/x/text/span.rs new file mode 100644 index 0000000..7208a3d --- /dev/null +++ b/src/x/text/span.rs @@ -0,0 +1,176 @@ +use crate::error::Result; +use crate::layout::Parcel; +use crate::geometry::{ Alignment, Point, Offset, Size }; +use crate::x::*; +use crate::x::text::{ Font, FontGraphicContext }; + +use std::cell::OnceCell; +use std::ffi::CString; +use std::sync::Arc; + +use x11::xft::{ + XftCharExists, XftDrawStringUtf8, XftTextExtentsUtf8, XftFontOpenName +}; +use x11::xrender::XGlyphInfo; + + +pub struct Span { + font: Arc<Font>, + text: CString, + extent: XGlyphInfo, +} + + +impl Span { + pub fn new(font: Arc<Font>, text: &str) -> Result<Self> { + let xlib_display = font.connection().get_xlib_display(); + + let text = CString::new(text).unwrap(); + + let mut extent = XGlyphInfo { + width: 0, + height: 0, + x: 0, + y: 0, + xOff: 0, + yOff: 0, + }; + unsafe { + XftTextExtentsUtf8(xlib_display, + font.font_state(), + text.as_ptr().cast(), + text.count_bytes() as i32, + &mut extent) + }; + + Ok(Span { font, text, extent }) + } + + /* The coordinates given to draw() are those of the left-side baseline of + * the span's as-drawn pixel boundaries, in window coordinate space. Recall + * that window coordinate space puts the origin at the top-left. + * + * As-drawn boundaries are about what pixels actually get marked on the + * screen, which include the descender and any marks that are outside the + * font's bounds as described by its metrics. + * + * Though this can be counterintuitive to programmers, it is normal for + * fonts to draw outside their bounds. Font metrics are primarily intended + * to advise about graphic-design topics, which are socially defined and do + * not necessarily obey mathematical identities, even when such identities + * are offered as explanations of their meaning. + * + * Instead, the mathematical meaning of these metrics serves as a first + * layer, a literal meaning which provides a reference point for additional + * layers of meaning to be added atop, in the same fashion as how the + * duration of a musical measure is not actually fixed during a live + * performance. + * + * There are very good reasons that programmers find this state of affairs + * deeply saddening, but there is nothing to be done but deal with it. + */ + pub fn draw(&self, context: &FontGraphicContext, color: &Color, + location: &Point<i32>) + -> Result<()> + { + let xft_draw = context.get_xft_draw(); + + unsafe { + XftDrawStringUtf8(xft_draw, + color.as_xft_color(), + self.font.font_state(), + location.x, location.y, + self.text.as_ptr().cast(), + self.text.count_bytes() as i32) + }; + + Ok(()) + } + + /* This returns the offset from the top-left of the span's logical parcel to the + * left-side baseline of its as-drawn pixel boundaries. See the note on draw() for + * more context on what these as-drawn boundaries mean and why. + */ + pub fn draw_offset(&self) -> Offset<i16> { + Offset { + x: self.extent.x, + y: self.extent.y, + } + } + + /* This is the as-drawn pixel size, rounded up to the next whole pixel, + * so that it is safe to use as a bounding box. It is computed only with + * respect to characters present in the span, and only considers the marks + * they actually draw. + * + * There are two important implications. First, due to rounding, + * pixel_size() is likely to be wider than logical_offset(). Second, trailing + * spaces are not included, since they do not draw any marks. + * + * In the vertical dimension, this size is conceptually similar to the + * maximum ascent plus the maximum descent of any character present in the + * span. Since there is no way within xft to obtain the font's declared + * ascent or descent, this measurement may be the best way to approximate + * those measurements. Note that there is nothing that even approximates line + * height; just guess. + * + * If you're thinking this all sounds highly inconvenient, you are correct. + * See the note on draw() for some highly relevant philosophy. + */ + pub fn draw_size(&self) -> Size<u16> { + Size { + width: self.extent.width, + height: self.extent.height, + } + } + + /* This returns the offset from the left-side baseline of the span's + * logical parcel to the new left-side baseline that a span occurring + * 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 draw_size(). See the note + * on draw() for some highly relevant philosophy. + */ + #[allow(unused)] + pub fn logical_offset(&self) -> Offset<i16> { + Offset { + x: self.extent.xOff, + y: self.extent.yOff, + } + } + + pub fn layout_and_draw(&self, + open_parcel: &mut Parcel, location: &mut Point<i32>, + alignment: Alignment, context: &FontGraphicContext, + color: &Color) + -> Result<()> + { + match alignment { + Alignment::Left => { + location.x += self.draw_offset().x as i32; + } + Alignment::Right => { + location.x -= self.draw_size().width as i32; + } + } + + self.draw(&context, color, &location)?; + + match alignment { + Alignment::Left => { + location.x += self.draw_size().width as i32; + + open_parcel.left += self.draw_size().width as u32; + } + Alignment::Right => { + location.x -= self.draw_offset().x as i32; + + open_parcel.right -= self.draw_size().width as u32; + } + } + + Ok(()) + } +} + |