1use std::cell::RefCell;
37use std::collections::HashMap;
38use std::fmt;
39use std::path::Path;
40
41use eternal_ui::styler::{Color, Corners, FontStyle, Sides};
42use eternal_ui::{FontSpec, Fonts, Point, Rect, Renderer, TextMetrics};
43use skia_safe::font::Edging;
44use skia_safe::font_style::{Slant, Weight, Width};
45use skia_safe::{
46 Canvas, ClipOp, Color4f, Data, Font, FontHinting, FontMgr, Paint, PaintStyle, RRect, Typeface,
47 Vector,
48};
49
50pub struct SkiaFonts {
71 font_mgr: FontMgr,
72 custom: Vec<CustomFont>,
73 typefaces: RefCell<HashMap<TypefaceKey, Typeface>>,
74 smooth: bool,
75}
76
77struct CustomFont {
79 family: String,
81 weight: i32,
82 italic: bool,
83 typeface: Typeface,
84}
85
86#[derive(Clone, PartialEq, Eq, Hash)]
87struct TypefaceKey {
88 families: Vec<String>,
89 weight: i32,
90 italic: bool,
91}
92
93impl Default for SkiaFonts {
94 fn default() -> Self {
95 Self::new()
96 }
97}
98
99impl SkiaFonts {
100 pub fn new() -> Self {
101 Self {
102 font_mgr: FontMgr::new(),
103 custom: Vec::new(),
104 typefaces: RefCell::new(HashMap::new()),
105 smooth: false,
106 }
107 }
108
109 pub fn load_font(&mut self, bytes: &[u8]) -> Result<String, FontError> {
115 let typeface = self.typeface_from_bytes(bytes)?;
116 let family = typeface.family_name();
117 self.register(family.clone(), typeface);
118 Ok(family)
119 }
120
121 pub fn load_font_as(&mut self, family: &str, bytes: &[u8]) -> Result<(), FontError> {
125 let typeface = self.typeface_from_bytes(bytes)?;
126 self.register(family.to_owned(), typeface);
127 Ok(())
128 }
129
130 pub fn load_font_file(&mut self, path: impl AsRef<Path>) -> Result<String, FontError> {
132 let bytes = read_font_file(path.as_ref())?;
133 self.load_font(&bytes)
134 .map_err(|error| error.at(path.as_ref()))
135 }
136
137 pub fn load_font_file_as(
139 &mut self,
140 family: &str,
141 path: impl AsRef<Path>,
142 ) -> Result<(), FontError> {
143 let bytes = read_font_file(path.as_ref())?;
144 self.load_font_as(family, &bytes)
145 .map_err(|error| error.at(path.as_ref()))
146 }
147
148 pub fn loaded_families(&self) -> impl Iterator<Item = &str> {
151 self.custom.iter().map(|font| font.family.as_str())
152 }
153
154 fn typeface_from_bytes(&self, bytes: &[u8]) -> Result<Typeface, FontError> {
155 self.font_mgr
156 .new_from_data(Data::new_copy(bytes), None)
157 .ok_or(FontError::Unreadable { path: None })
158 }
159
160 fn register(&mut self, family: String, typeface: Typeface) {
161 let style = typeface.font_style();
162 self.custom.push(CustomFont {
163 family: family.to_ascii_lowercase(),
164 weight: *style.weight(),
165 italic: style.slant() != Slant::Upright,
166 typeface,
167 });
168 self.typefaces.borrow_mut().clear();
171 }
172
173 fn custom_typeface(&self, family: &str, weight: i32, italic: bool) -> Option<Typeface> {
176 self.custom
177 .iter()
178 .filter(|font| font.family.eq_ignore_ascii_case(family))
179 .min_by_key(|font| {
180 (font.weight - weight).abs() + if font.italic == italic { 0 } else { 1000 }
181 })
182 .map(|font| font.typeface.clone())
183 }
184
185 pub fn set_smooth(&mut self, smooth: bool) {
188 self.smooth = smooth;
189 }
190
191 pub fn smooth(&self) -> bool {
192 self.smooth
193 }
194
195 pub fn font(&self, spec: &FontSpec) -> Font {
197 let mut font = Font::new(self.typeface(spec), spec.size);
198 if self.smooth {
199 font.set_edging(Edging::AntiAlias);
200 font.set_subpixel(true);
201 } else {
202 font.set_edging(Edging::Alias);
203 font.set_subpixel(false);
204 font.set_hinting(FontHinting::Full);
205 }
206 font
207 }
208
209 fn typeface(&self, spec: &FontSpec) -> Typeface {
210 let key = TypefaceKey {
211 families: spec.family.names().to_vec(),
212 weight: spec.weight.value().round() as i32,
213 italic: spec.style != FontStyle::Normal,
214 };
215 if let Some(typeface) = self.typefaces.borrow().get(&key) {
216 return typeface.clone();
217 }
218 let slant = match spec.style {
219 FontStyle::Normal => Slant::Upright,
220 FontStyle::Italic => Slant::Italic,
221 FontStyle::Oblique => Slant::Oblique,
222 };
223 let style = skia_safe::FontStyle::new(Weight::from(key.weight), Width::NORMAL, slant);
224 let typeface = key
225 .families
226 .iter()
227 .find_map(|family| {
228 self.custom_typeface(family, key.weight, key.italic)
229 .or_else(|| {
230 candidates(family)
231 .into_iter()
232 .find_map(|name| self.font_mgr.match_family_style(name, style))
233 })
234 })
235 .or_else(|| self.font_mgr.legacy_make_typeface(None, style))
236 .expect("Skia has a default typeface");
237 self.typefaces.borrow_mut().insert(key, typeface.clone());
238 typeface
239 }
240}
241
242fn read_font_file(path: &Path) -> Result<Vec<u8>, FontError> {
243 std::fs::read(path).map_err(|source| FontError::Io {
244 path: path.display().to_string(),
245 source,
246 })
247}
248
249#[derive(Debug)]
251pub enum FontError {
252 Io {
254 path: String,
255 source: std::io::Error,
256 },
257 Unreadable {
259 path: Option<String>,
261 },
262}
263
264impl FontError {
265 fn at(self, path: &Path) -> Self {
266 match self {
267 Self::Unreadable { path: None } => Self::Unreadable {
268 path: Some(path.display().to_string()),
269 },
270 other => other,
271 }
272 }
273}
274
275impl fmt::Display for FontError {
276 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
277 match self {
278 Self::Io { path, source } => write!(f, "{path}: {source}"),
279 Self::Unreadable { path: Some(path) } => write!(f, "{path}: not a font Skia can read"),
280 Self::Unreadable { path: None } => f.write_str("not a font Skia can read"),
281 }
282 }
283}
284
285impl std::error::Error for FontError {
286 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
287 match self {
288 Self::Io { source, .. } => Some(source),
289 Self::Unreadable { .. } => None,
290 }
291 }
292}
293
294fn candidates(family: &str) -> Vec<&str> {
296 match family {
297 "monospace" | "ui-monospace" => vec![
298 "Menlo",
299 "SF Mono",
300 "Consolas",
301 "Cascadia Mono",
302 "DejaVu Sans Mono",
303 "Liberation Mono",
304 "Courier New",
305 "monospace",
306 ],
307 "sans-serif" | "system-ui" | "ui-sans-serif" => vec![
308 "Helvetica Neue",
309 "Segoe UI",
310 "DejaVu Sans",
311 "Liberation Sans",
312 "Arial",
313 "sans-serif",
314 ],
315 "serif" | "ui-serif" => vec![
316 "Georgia",
317 "Times New Roman",
318 "DejaVu Serif",
319 "Liberation Serif",
320 "serif",
321 ],
322 other => vec![other],
323 }
324}
325
326impl Fonts for SkiaFonts {
327 fn measure(&self, text: &str, spec: &FontSpec) -> TextMetrics {
328 let font = self.font(spec);
329 let (_, metrics) = font.metrics();
330 let ascent = -metrics.ascent;
331 let descent = metrics.descent;
332 let natural = (ascent + descent + metrics.leading).ceil();
333 TextMetrics {
334 width: font.measure_str(text, None).0,
335 ascent,
336 descent,
337 line_height: spec.line_height.unwrap_or(natural),
338 }
339 }
340}
341
342pub struct SkiaRenderer<'a> {
344 canvas: &'a Canvas,
345 fonts: &'a SkiaFonts,
346}
347
348impl<'a> SkiaRenderer<'a> {
349 pub fn new(canvas: &'a Canvas, fonts: &'a SkiaFonts) -> Self {
350 Self { canvas, fonts }
351 }
352
353 fn paint(&self, color: Color) -> Paint {
354 let mut paint = Paint::new(Color4f::new(color.r, color.g, color.b, color.a), None);
355 paint.set_anti_alias(self.fonts.smooth);
356 paint
357 }
358}
359
360fn skia_rect(rect: Rect) -> skia_safe::Rect {
361 skia_safe::Rect::from_xywh(rect.x, rect.y, rect.width, rect.height)
362}
363
364fn rounded(rect: Rect, radius: Corners<f32>) -> Option<RRect> {
365 let radii = [
366 radius.top_left,
367 radius.top_right,
368 radius.bottom_right,
369 radius.bottom_left,
370 ];
371 if radii.iter().all(|&r| r <= 0.0) {
372 return None;
373 }
374 Some(RRect::new_rect_radii(
375 skia_rect(rect),
376 &radii.map(|r| Vector::new(r, r)),
377 ))
378}
379
380impl Renderer for SkiaRenderer<'_> {
381 fn fill_rect(&mut self, rect: Rect, radius: Corners<f32>, color: Color) {
382 let paint = self.paint(color);
383 match rounded(rect, radius) {
384 Some(rrect) => self.canvas.draw_rrect(rrect, &paint),
385 None => self.canvas.draw_rect(skia_rect(rect), &paint),
386 };
387 }
388
389 fn border(
390 &mut self,
391 rect: Rect,
392 widths: Sides<f32>,
393 colors: Sides<Color>,
394 radius: Corners<f32>,
395 ) {
396 if let Some(outer) = rounded(rect, radius) {
397 let width = widths
400 .top
401 .max(widths.right)
402 .max(widths.bottom)
403 .max(widths.left);
404 let mut paint = self.paint(colors.top);
405 paint.set_style(PaintStyle::Stroke);
406 paint.set_stroke_width(width);
407 let inset = width / 2.0;
408 let mut inner = outer;
409 inner.inset((inset, inset));
410 self.canvas.draw_rrect(inner, &paint);
411 return;
412 }
413 let strips = [
414 (
415 Rect::new(rect.x, rect.y, rect.width, widths.top),
416 colors.top,
417 ),
418 (
419 Rect::new(
420 rect.x,
421 rect.bottom() - widths.bottom,
422 rect.width,
423 widths.bottom,
424 ),
425 colors.bottom,
426 ),
427 (
428 Rect::new(
429 rect.x,
430 rect.y + widths.top,
431 widths.left,
432 rect.height - widths.top - widths.bottom,
433 ),
434 colors.left,
435 ),
436 (
437 Rect::new(
438 rect.right() - widths.right,
439 rect.y + widths.top,
440 widths.right,
441 rect.height - widths.top - widths.bottom,
442 ),
443 colors.right,
444 ),
445 ];
446 for (strip, color) in strips {
447 if strip.width > 0.0 && strip.height > 0.0 && color.a > 0.0 {
448 self.canvas.draw_rect(skia_rect(strip), &self.paint(color));
449 }
450 }
451 }
452
453 fn text(&mut self, text: &str, spec: &FontSpec, top_left: Point, color: Color) {
454 let font = self.fonts.font(spec);
455 let metrics = self.fonts.measure("", spec);
456 let baseline = top_left.y
458 + ((metrics.line_height - (metrics.ascent + metrics.descent)) / 2.0).max(0.0)
459 + metrics.ascent;
460 let mut paint = self.paint(color);
461 paint.set_anti_alias(true);
462 self.canvas.draw_str(
463 text,
464 skia_safe::Point::new(top_left.x, baseline.round()),
465 &font,
466 &paint,
467 );
468 }
469
470 fn push_clip(&mut self, rect: Rect) {
471 self.canvas.save();
472 self.canvas
473 .clip_rect(skia_rect(rect), ClipOp::Intersect, false);
474 }
475
476 fn pop_clip(&mut self) {
477 self.canvas.restore();
478 }
479
480 fn push_opacity(&mut self, opacity: f32) {
481 self.canvas.save_layer_alpha_f(None, opacity);
482 }
483
484 fn pop_opacity(&mut self) {
485 self.canvas.restore();
486 }
487}