about summary refs log tree commit diff
path: root/src/x/font.rs
blob: 8b81fda4cdb0e40e2786d99f45488891e3a37e0b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
use crate::error::Result;
use crate::layout::Parcel;
use crate::geometry::{ Alignment, Point, Offset, Size };
use crate::x::*;

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<TextSpan> {
    TextSpan::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)
  }
}