1use std::mem;
2
3use crossfont::{GlyphKey, Rasterize, RasterizedGlyph};
4use tiny_skia::{Color, Pixmap, PixmapPaint, PixmapRef, Transform};
5
6use crate::title::config;
7
8pub struct CrossfontTitleText {
9 title: String,
10
11 font_desc: crossfont::FontDesc,
12 font_key: crossfont::FontKey,
13 size: crossfont::Size,
14 scale: u32,
15 metrics: crossfont::Metrics,
16 rasterizer: crossfont::Rasterizer,
17 color: Color,
18
19 pixmap: Option<Pixmap>,
20}
21
22impl std::fmt::Debug for CrossfontTitleText {
23 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24 f.debug_struct("TitleText")
25 .field("title", &self.title)
26 .field("font_desc", &self.font_desc)
27 .field("font_key", &self.font_key)
28 .field("size", &self.size)
29 .field("scale", &self.scale)
30 .field("pixmap", &self.pixmap)
31 .finish()
32 }
33}
34
35impl CrossfontTitleText {
36 pub fn new(color: Color) -> Result<Self, crossfont::Error> {
37 let title = "".into();
38
39 let font_pref = config::titlebar_font().unwrap_or_default();
40 let font_style = font_pref
41 .style
42 .map(crossfont::Style::Specific)
43 .unwrap_or_else(|| crossfont::Style::Description {
44 slant: crossfont::Slant::Normal,
45 weight: crossfont::Weight::Normal,
46 });
47 let font_desc = crossfont::FontDesc::new(&font_pref.name, font_style);
48
49 let mut rasterizer = crossfont::Rasterizer::new()?;
50 let size = crossfont::Size::new(font_pref.pt_size);
51 let font_key = rasterizer.load_font(&font_desc, size)?;
52
53 // Need to load at least one glyph for the face before calling metrics.
54 // The glyph requested here ('m' at the time of writing) has no special
55 // meaning.
56 rasterizer.get_glyph(GlyphKey {
57 font_key,
58 character: 'm',
59 size,
60 })?;
61
62 let metrics = rasterizer.metrics(font_key, size)?;
63
64 let mut this = Self {
65 pixmap: None,
66 rasterizer,
67 font_desc,
68 font_key,
69 scale: 1,
70 metrics,
71 title,
72 color,
73 size,
74 };
75
76 this.rerender();
77
78 Ok(this)
79 }
80
81 fn update_metrics(&mut self) -> Result<(), crossfont::Error> {
82 self.rasterizer.get_glyph(GlyphKey {
83 font_key: self.font_key,
84 character: 'm',
85 size: self.size,
86 })?;
87 self.metrics = self.rasterizer.metrics(self.font_key, self.size)?;
88 Ok(())
89 }
90
91 pub fn update_scale(&mut self, scale: u32) {
92 let old_scale = mem::replace(&mut self.scale, scale);
93 if old_scale != self.scale {
94 self.size = self.size.scale(self.scale as f32 / old_scale as f32);
95 self.update_metrics().ok();
96 self.rerender();
97 }
98 }
99
100 pub fn update_title<S: Into<String>>(&mut self, title: S) {
101 let title = title.into();
102 if self.title != title {
103 self.title = title;
104 self.rerender();
105 }
106 }
107
108 pub fn update_color(&mut self, color: Color) {
109 if self.color != color {
110 self.color = color;
111 self.rerender();
112 }
113 }
114
115 fn rerender(&mut self) {
116 let glyphs: Vec<_> = self
117 .title
118 .chars()
119 .filter_map(|character| {
120 let key = GlyphKey {
121 character,
122 font_key: self.font_key,
123 size: self.size,
124 };
125
126 self.rasterizer
127 .get_glyph(key)
128 .map(|glyph| (key, glyph))
129 .ok()
130 })
131 .collect();
132
133 if glyphs.is_empty() {
134 self.pixmap = None;
135 return;
136 }
137
138 let width = self.calc_width(&glyphs);
139 let height = self.metrics.line_height.round() as i32;
140
141 let mut pixmap = if let Some(p) = Pixmap::new(width as u32, height as u32) {
142 p
143 } else {
144 self.pixmap = None;
145 return;
146 };
147 // pixmap.fill(Color::from_rgba8(255, 0, 0, 55));
148
149 let mut caret = 0;
150 let mut last_glyph = None;
151
152 for (key, glyph) in glyphs {
153 let mut buffer = Vec::with_capacity(glyph.width as usize * 4);
154
155 let glyph_buffer = match &glyph.buffer {
156 crossfont::BitmapBuffer::Rgb(v) => v.chunks(3),
157 crossfont::BitmapBuffer::Rgba(v) => v.chunks(4),
158 };
159
160 for px in glyph_buffer {
161 let alpha = if let Some(alpha) = px.get(3) {
162 *alpha as f32 / 255.0
163 } else {
164 let r = px[0] as f32 / 255.0;
165 let g = px[1] as f32 / 255.0;
166 let b = px[2] as f32 / 255.0;
167 (r + g + b) / 3.0
168 };
169
170 let mut color = self.color;
171 color.set_alpha(alpha);
172 let color = color.premultiply().to_color_u8();
173
174 buffer.push(color.red());
175 buffer.push(color.green());
176 buffer.push(color.blue());
177 buffer.push(color.alpha());
178 }
179
180 if let Some(last) = last_glyph {
181 let (x, _) = self.rasterizer.kerning(last, key);
182 caret += x as i32;
183 }
184
185 if let Some(pixmap_glyph) =
186 PixmapRef::from_bytes(&buffer, glyph.width as _, glyph.height as _)
187 {
188 pixmap.draw_pixmap(
189 glyph.left + caret,
190 height - glyph.top + self.metrics.descent.round() as i32,
191 pixmap_glyph,
192 &PixmapPaint::default(),
193 Transform::identity(),
194 None,
195 );
196 }
197
198 caret += glyph.advance.0;
199
200 last_glyph = Some(key);
201 }
202
203 self.pixmap = Some(pixmap);
204 }
205
206 pub fn pixmap(&self) -> Option<&Pixmap> {
207 self.pixmap.as_ref()
208 }
209
210 fn calc_width(&mut self, glyphs: &[(GlyphKey, RasterizedGlyph)]) -> i32 {
211 let mut caret = 0;
212 let mut last_glyph: Option<&GlyphKey> = None;
213
214 for (key, glyph) in glyphs.iter() {
215 if let Some(last) = last_glyph {
216 let (x, _) = self.rasterizer.kerning(*last, *key);
217 caret += x as i32;
218 }
219
220 caret += glyph.advance.0;
221
222 last_glyph = Some(key);
223 }
224
225 caret
226 }
227}