summaryrefslogtreecommitdiffstats
path: root/src/ui/font.rs
blob: 6f3a1d74d22bb084b6e562cb47ccb8e2ac19ae78 (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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
use std::fmt;
use std::fmt::Display;

const DEFAULT_HEIGHT: f32 = 14.0;

pub enum FontUnit {
    Pixel,
    Point,
}

impl Display for FontUnit {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self {
            FontUnit::Pixel => write!(fmt, "px"),
            FontUnit::Point => write!(fmt, "pt"),
        }
    }
}

#[derive(Clone, Debug)]
pub struct Font {
    name: String,
    pub height: f32,
}

impl Font {
    /// Parses nvim `guifont` option.
    ///
    /// If invalid height is specified, defaults to `DEFAULT_HEIGHT`.
    pub fn from_guifont(guifont: &str) -> Result<Self, ()> {
        let mut parts = guifont.split(":").into_iter();

        let name = parts.next().ok_or(())?;

        if name.len() == 0 {
            return Err(());
        }

        let mut font = Font {
            name: name.to_string(),
            height: DEFAULT_HEIGHT,
        };

        while let Some(part) = parts.next() {
            let mut chars = part.chars().into_iter();
            if let Some(ch) = chars.next() {
                match ch {
                    'h' => {
                        let rest = chars.collect::<String>();
                        let h = rest.parse::<f32>().or(Err(()))?;
                        if h <= 0.0 {
                            // Ignore zero sized font.
                            continue;
                        }
                        font.height = h;
                    }
                    _ => {
                        println!("Not supported guifont option: {}", part);
                    }
                }
            }
        }

        Ok(font)
    }

    /// Returns a CSS representation of self for a wild (`*`) CSS selector.
    /// On gtk version below 3.20 unit needs to be `FontUnit::Pixel` and
    /// with version 3.20 and up, unit needs to be `FontUnit::Point`. This is
    /// to work around some gtk issues on versions before 3.20.
    pub fn as_wild_css(&self, unit: FontUnit) -> String {
        format!(
            "* {{ \
             font-family: \"{font_family}\"; \
             font-size: {font_size}{font_unit}; \
             }}",
            font_family = self.name,
            font_size = self.height,
            font_unit = unit,
        )
    }

    /// Returns a pango::FontDescription version of self.
    pub fn as_pango_font(&self) -> pango::FontDescription {
        let mut font_desc = pango::FontDescription::from_string(&format!(
            "{} {}",
            self.name, self.height
        ));

        // Make sure we dont have a font with size of 0, otherwise we'll
        // have problems later.
        if font_desc.get_size() == 0 {
            font_desc.set_size(DEFAULT_HEIGHT as i32 * pango::SCALE);
        }

        font_desc
    }
}

impl Default for Font {
    fn default() -> Self {
        Font {
            name: String::from("Monospace"),
            height: DEFAULT_HEIGHT,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_as_wild_css() {
        let font = Font {
            name: "foo".to_string(),
            height: 10.0,
        };

        assert_eq!(
            font.as_wild_css(FontUnit::Point),
            "* { \
             font-family: \"foo\"; \
             font-size: 10pt; \
             }"
        );

        assert_eq!(
            font.as_wild_css(FontUnit::Pixel),
            "* { \
             font-family: \"foo\"; \
             font-size: 10px; \
             }"
        );
    }

    #[test]
    fn test_from_guifont() {
        // Font with proper height.
        let f = Font::from_guifont("monospace:h11").unwrap();
        assert_eq!(f.name, "monospace");
        assert_eq!(f.height, 11.0);

        // Font with invalid height.
        let f = Font::from_guifont("font:h");
        assert_eq!(f.is_err(), true);
        let f = Font::from_guifont("font:hn");
        assert_eq!(f.is_err(), true);

        // Font with height zero.
        let f = Font::from_guifont("foo:h0").unwrap();
        assert_eq!(f.name, "foo");
        assert_eq!(f.height, DEFAULT_HEIGHT);

        // Font with negative height.
        let f = Font::from_guifont("font:h-1").unwrap();
        assert_eq!(f.name, "font");
        assert_eq!(f.height, DEFAULT_HEIGHT);

        // Font with no height.
        let f = Font::from_guifont("bar").unwrap();
        assert_eq!(f.name, "bar");
        assert_eq!(f.height, DEFAULT_HEIGHT);
    }
}